How does one set an optional property of a protocol? For example UITextInputTraits has a number of optional read/write properties. When I try the following I get a compile error (Cannot assign to 'keyboardType' in 'textInputTraits'):
func initializeTextInputTraits(textInputTraits: UITextInputTraits) {
textInputTraits.keyboardType = .Default
}
Normally when accessing an optional property of a protocol you add a question mark but this doesn't work when assigning a value (error: Cannot assign to the result of this expression):
textInputTraits.keyboardType? = .Default
The protocol looks like:
protocol UITextInputTraits : NSObjectProtocol {
optional var keyboardType: UIKeyboardType { get set }
}
It's impossible in Swift (yet?). Referenced from an ADF thread:
Optional property requirements, and optional method requirements that return a value, will always return an optional value of the appropriate type when they are accessed or called, to reflect the fact that the optional requirement may not have been implemented.
So it's no surprise to get optional values easily. However, setting a property requires implementation to be guaranteed.
I'd consider making an extension returning your default value for keyboardType
, and having the setter do nothing.
extension UITextInputTraits {
var keyboardType: UIKeyboardType {
get { return .default }
set { /* do nothing */ }
}
}
That way you can remove the optional
from your property declaration.
protocol UITextInputTraits : NSObjectProtocol {
var keyboardType: UIKeyboardType { get set }
}
Or, if you prefer, you can make it of optional return type, var keyboardType: UIKeyboardType?
, and return nil
instead of .Default
in your extension.
This way, you can test for myObject.keyboardType == nil
to see if your property is implemented.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With