콘텐츠로 건너뛰기
Home » Selector in Swift

Selector in Swift

셀렉터(Swift)

셀렉터는 Objective-C 메소드의 이름을 가리키는 참조타입이다. @selector() 디렉티브를 써서 메소드 이름을 정수값으로 맵핑하여 표시한다. Swift에서는 이 셀렉터는 Selector라는 구조체로 표현되며 문자열 리터럴로 만들 수 있다. 만드는 방법은 Objective-C 스타일과 거의 유사하다.

import UIKit
class MyViewController: UIViewController {
    let myButton = UIButton(frame: CGRect(x:0, y:0, width:100, height:50))
    init(nibName nibNameOrNil:String?, bundle nibBundleOrNil:NSBundle?) {
        super.init(nibName:nibNameOrNil, bundle: nibBundleOrNil)
        myButton.addTarget(self, action:"tappedButton:", forControlEvents:.TouchUpInside)
    }
    func tappedButton(sender:UIButton!) {
        println("tapped inside")
    }
}

NSObject의 performSelector:의 경우 안정성의 문제로 현재(2015. 01)까지는 Swift에서는 불가능하다.

만약 Swift 클래스가 Objective-C의 클래스를 상속받지 않았다면, 클래스 및 함수명은 @objc() 디렉티브를 써서 셀렉터를 명시해주어야 한다.