Reputation: 9351
I was trying to implement swift's alternative to the respondsToSelector:
syntax that was also shown in the keynote.
I have the following:
protocol CustomItemTableViewCellDelegate {
func changeCount(sender: UITableViewCell, change: Int)
}
and then later in the code I call
class CustomItemTableViewCell: UITableViewCell {
var delegate: CustomItemTableViewCellDelegate
...
override func touchesEnded(touches: NSSet!, withEvent event: UIEvent!) {
...
delegate?.changeCount?(self, change: -1)
}
...
}
I get the following errors
Operand of postfix '?' should have optional type; type is
'(UITableViewCell, change:Int) -> ()'
Operand of postfix '?' should
have optional type; type is 'CustomItemTableViewCellDelegate'
Partial application of protocol method is not allowed
What I am doing wrong?
Thanks
Upvotes: 2
Views: 11386
Reputation: 93276
You have two ?
operators, and they're both causing problems.
First, the one after delegate
indicates that you want to unwrap an optional value, but your delegate
property isn't declared that way. It should be:
var delegate: CustomItemTableViewCellDelegate?
Second, it looks like you want your changeCount
protocol method to be optional. If you do, you need to both mark the protocol with the @objc
attribute and mark the function with the optional
attribute:
@objc protocol CustomItemTableViewCellDelegate {
optional func changeCount(sender: UITableViewCell, change: Int)
}
(Note: Classes that conform to @objc
protocols need to be @objc
themselves. In this case you're subclassing an Objective-C class, so you're covered, but a new class would need to be marked with the @objc
attribute.)
If you only want the delegate to be optional (that is, it's okay to not have a delegate, but all delegates need to implement changeCount
), then leave your protocol as is and change that method call to:
delegate?.changeCount(self, change: -1)
Upvotes: 9
Reputation: 12446
The error says it all.
You use ?
on an explicit type, it can't be nil
, so simply don't use ?
on that variable.
If you have a var like this one
var changeCount: Int
or this
var changeCount = 3
You have an explicit type. When an explicit type is requested, then you should give an explicit type, which is changeCount
and not changeCount?
.
If you want optional variable to begin with, declare it with an ?
:
var changeCount: Int?
You can't use literal syntax with optional type if the type should be implicit. Because 3 is always explicit Int if not stated otherwise.
Upvotes: 0