Skip to content

Instantly share code, notes, and snippets.

@takasek
Created June 2, 2019 07:45
Show Gist options
  • Save takasek/3fca497cb8be3e10e7eeb463b3633a31 to your computer and use it in GitHub Desktop.
Save takasek/3fca497cb8be3e10e7eeb463b3633a31 to your computer and use it in GitHub Desktop.
静的型付け言語であるSwiftもダックタイピングはできるよ(オブジェクト指向(メッセージ指向)言語であるObj-Cとcompatibleだから)というコード #CodePiece
class Cat: NSObject {
@objc func bark() { print("meow") }
func hoge() {}
}
class Dog: NSObject {
@objc func bark() { print("bow-wow") }
func hoge() {}
}
let cat = Cat()
cat.perform(#selector(Dog.bark)) // "meow"
cat.perform("bark")
// Warning: Use of string literal for Objective-C selectors is deprecated; use '#selector' instead
// …と出るけど実行は可能
//cat.perform(#selector(Dog.hoge))
// これはコンパイルエラー:
// Argument of '#selector' refers to instance method 'hoge()' that is not exposed to Objective-C
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment