SwiftReflection icon indicating copy to clipboard operation
SwiftReflection copied to clipboard

Limitation on optional Int?

Open MatthewCawley opened this issue 8 years ago • 1 comments

I wasn't sure how to comment on this as it so I have put it here.

The issue with Int? not working is due to the data type needing to be available as an Objective-C data type. Objective-C does not support Int values that can be nullified, which is why this mapping will never work.

To get around this from a coding perspective, there are 2 approaches.

1: Do not declare a Int? but instead declare an Int with a default value of 0

@objc dynamic var propertyName: Int = 0

2: Revert to a object based number that is supported by Objective-C, i.e. NSNumber

@objc dynamic var propertyName: NSNumber? = nil

It may be possible to use a mixture of your current Objective-C runtime methods with Swift Mirror reflection.

You can gain a list of properties for a class using the following:

func propertyNames() -> [String] {
        var propertyNames = Mirror(reflecting: self).children.flatMap {
            $0.label
        }
        return propertyNames
    }

You could then parse the data types using the following method.

let m = Mirror(reflecting: self)
        for child in m.children {
                let subMirror = Mirror(reflecting: child.value)
                types[name] = subMirror.subjectType
            }
        }

MatthewCawley avatar Nov 06 '17 03:11 MatthewCawley

Note that the above is untested and is purely theory based :)

MatthewCawley avatar Nov 06 '17 03:11 MatthewCawley