Skip to content

Instantly share code, notes, and snippets.

@soffes
Last active January 6, 2024 07:22
Show Gist options
  • Select an option

  • Save soffes/7258422dfb903af1ac5a to your computer and use it in GitHub Desktop.

Select an option

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
Copy Markdown

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
Copy Markdown

You can also do this:

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

@steam

steam commented May 11, 2015

Copy link
Copy Markdown

@subdigital typo?

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

@soffes

soffes commented May 11, 2015

Copy link
Copy Markdown
Author

@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