Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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

This comment has been minimized.

Copy link

commented May 11, 2015

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

This comment has been minimized.

Copy link

commented May 11, 2015

You can also do this:

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

This comment has been minimized.

Copy link

commented May 11, 2015

@subdigital typo?

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

This comment has been minimized.

Copy link
Owner Author

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
You can’t perform that action at this time.