Formatter for parsing a struct

I have a Formatter that handles value types. For the purposes of this example, let's say it is a Bool formatter:


@objc final class BoolFormatter : Formatter {
    override func string(for obj: Any?) -> String? {
        return (obj as? Bool) == true ? "true" : "false"
    }
}


It works fine. But now I want to be able to parse the Bool:



@objc final class BoolFormatter : Formatter {
    override func string(for obj: Any?) -> String? {
        return (obj as? Bool) == true ? "true" : "false"
    }
   
    override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        if string == "true" {
            obj?.pointee = true
            return true
        } else if string == "false" {
            obj?.pointee = false
            return true
        } else {
            if let error = error {
                error.pointee = "String was not a boolean"
            }
            return false
        }
    }
}


This fails, because Bool is not an AnyObject. Is there some special reason why Formatter can format Any (value or class), but requires AnyObject for parsing? It seems wasteful to have to wrap the value in a NSNumber or some other class.

It's that way because Formatter is really NSFormatter underneath, and it uses Obj-C conventions, where there's no type like "Any" that applies to non-objects. The only non-specific type in Obj-C is "id", the equivalent of Swift's "AnyObject". Even in Obj-C code using this API, you have to wrap non-objects in an object, somehow.


Set "pointee" to "true as NSNumber" or "false as NSNumber" and don't lose any sleep over it.

Formatter for parsing a struct
 
 
Q