Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active January 6, 2024 07:22
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save soffes/7258422dfb903af1ac5a to your computer and use it in GitHub Desktop.
Save soffes/7258422dfb903af1ac5a to your computer and use it in GitHub Desktop.
Checking for the presence of an optional method in a protocol
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")
@hyperspacemark
Copy link

Makes sense. Instance methods in swift are just curried class functions that take the instance as the first argument and return an optional function that then gets resolved... somehow. It's wild.

@subdigital
Copy link

You can also do this:

doesnt?.say()  // no-op
does?.say()  // returns "hi"

@steam
Copy link

steam commented May 11, 2015

@subdigital typo?

doesnt.say?()  // .None
does.say?()  // returns Optional("hi")

@soffes
Copy link
Author

soffes commented May 11, 2015

@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