Hi everyone.
I realy wonder what the purpose of the _ObjectiveCBridgeable protocol is.
Say that you make a Swift struct that could bridge to NSNumber. A thing simple enough to look like that:
struct IntHolder {
var holdInt: Int
init(value: Int) {
self.holdInt = value
}
mutating func makeItDouble() {
holdInt *= 2
}
}Now say that you want to bridge it to ObjectiveC to bind an IntHolder property to another for exemple. All you'll (normaly) need is to conform IntHolder to _ObjectiveCBridgeable protocol:
extension IntHolder: _ObjectiveCBridgeable {
typealias _ObjectiveCType = NSNumber
init(fromObjectiveC source: _ObjectiveCType) {
self.holdInt = source.integerValue
}
static func _getObjectiveCType() -> Any.Type {
return _ObjectiveCType.self
}
static func _isBridgedToObjectiveC() -> Bool {
return true
}
func _bridgeToObjectiveC() -> IntHolder._ObjectiveCType {
return NSNumber(integer: self.holdInt)
}
static func _forceBridgeFromObjectiveC(source: IntHolder._ObjectiveCType, inout result: IntHolder?) {
result = IntHolder(fromObjectiveC: source)
}
static func _conditionallyBridgeFromObjectiveC(source: IntHolder._ObjectiveCType, inout result: IntHolder?) -> Bool {
_forceBridgeFromObjectiveC(source, result: &result)
return true
}
}Now you can use IntHolder as any objc class without forgeting to make anotate the property as dynamic (best with binding):
class Dummy: NSObject {
dynamic var holder: IntHolder
override init() {
self.holder = IntHolder(value: 22)
}
}And..... :
error: property cannot be marked dynamic because its type cannot be represented in Objective-C dynamic var holder: IntHolder
note: Swift structs cannot be represented in Objective-C dynamic var holder: IntHolderSo is _ObjectiveCBridgeable useful for things other than :
let arr = [IntHolder(value: 1), IntHolder(value: 2), IntHolder(value: 3)]
let bridgedArr = arr as NSArray?
If yes how can I do ?