ios - Inconsistency in Swift optional protocol behaviour -
coming .net, trying learn swift3/ios , got puzzled following apparent inconsistent behaviour of optional protocol members. suspect got juggling between objc/swift words, missing here actually?
// in playground, given below: @objc protocol someptotocol { @objc optional func somemethod() } class somedelegate: nsobject, someptotocol { } class somecontroller: nsobject { var delegate: someptotocol = somedelegate() } // works , compiles without error let controller = somecontroller() controller.delegate.somemethod?() // no error, typed '(() -> ())?' // fails compile ?? let delegate = somedelegate() delegate.somemethod?() // error: 'somedelegate' has no member 'somemethod'
i expect either both fail or both pass, if please enlighten me on anomaly.
the difference between 2 blocks of code type of variable involved.
in first block, delegate
explicitly typed someptotocol
, , protocol defines somemethod
method, statement valid.
in second block, delegate
implicitly typed somedelegate
, although class conforms someptotocol
, doesn't implement optional method somemethod
, error.
if change second block
let delegate: someptotocol = somedelegate() delegate.somemethod?()
which equivalent first block, there no error.
Comments
Post a Comment