Last active
January 6, 2024 07:22
-
-
Save soffes/7258422dfb903af1ac5a to your computer and use it in GitHub Desktop.
Checking for the presence of an optional method in a protocol
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
@objc protocol Foo { | |
optional func say() -> String | |
} | |
class Doesnt: NSObject, Foo { | |
} | |
class Does: NSObject, Foo { | |
func say() -> String { | |
return "hi" | |
} | |
} | |
let doesnt: Foo = Doesnt() | |
let does: Foo = Does() | |
// You can easily check to see if an object implements an optional protocol method: | |
if let f = doesnt.say { | |
f() // Never called | |
} else { | |
// Fallback to something | |
} | |
if let f = does.say { | |
f() // Returns "hi" | |
} | |
// You can also just do the following if you don't care if it's implemented or not. | |
doesnt.say?() // .None | |
does.say?() // Optional("hi") |
@subdigital typo?
doesnt.say?() // .None
does.say?() // returns Optional("hi")
@subdigitial that is great if you want to just call it if it doesn't exists or not. This is more for:
if let f = does.say {
f()
} else {
// Some fallback
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You can also do this: