Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift: setting an optional property of a protocol

Tags:

swift

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 }
}
like image 673
Mark Horgan Avatar asked Sep 28 '14 09:09

Mark Horgan


2 Answers

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.

like image 94
akashivskyy Avatar answered Oct 21 '22 09:10

akashivskyy


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.

like image 37
atlex2 Avatar answered Oct 21 '22 10:10

atlex2