i created a delegate for a class
@protocol gameDelegate <NSObject>
@optional
-(void)gameStarted;
@required
@end
now in my game object i called this method:
[self.delegate gameStarted];
so now, if i initiate this object anywhere and set the delegate everything works fine until the gameStated gets called, because its not implemented in the main object where the game object is created (because its optional).
i tried some variations of this
if(![self.delegate respondsToSelector: @selector(gameStarted)]) {
//[self.delegate gameStarted];
}
but this is not working for me. any ideas how to make this "really" optional?
thanks in advance
To define Optional Protocol in swift you should use @objc keyword before Protocol declaration and attribute / method declaration inside that protocol. Below is a sample of Optional Property of a protocol.
For pure Swift code, you can instead use a property whose type is the same as the type of the function you want be optional (but wrapped into an Optional ), and assign it to nil in implementing types that you don't want to implement that function (unfortunately, you won't have named arguments and generics).
In Swift, a delegate is a controller object with a defined interface that can be used to control or modify the behavior of another object.
Omit the negation from your if
statement:
if ([self.delegate respondsToSelector:@selector(gameStarted)]) {
...
}
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