programing

swift와 함께 isKindOfClass 사용

subpage 2023. 4. 14. 21:42
반응형

swift와 함께 isKindOfClass 사용

Swift lang을 사용하려고 하는데 다음 Objective-C를 Swift로 변환하는 방법을 알고 싶습니다.

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
    [super touchesBegan:touches withEvent:event];

    UITouch *touch = [touches anyObject];

    if ([touch.view isKindOfClass: UIPickerView.class]) {
      //your touch was in a uipickerview ... do whatever you have to do
    }
}

보다 구체적으로, 사용법을 알고 싶다.isKindOfClass새로운 구문에서.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    ???

    if ??? {
        // your touch was in a uipickerview ...

    }
}

적절한 Swift 연산자는is:

if touch.view is UIPickerView {
    // touch.view is of type UIPickerView
}

물론 보기를 새 상수에 할당해야 하는 경우if let ... as? ...케빈이 말한 것처럼 구문은 당신의 아들입니다그러나 값이 필요하지 않고 유형만 확인해야 하는 경우is교환입니다.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if touch.view.isKindOfClass(UIPickerView)
    {

    }
}

편집

@Kevin의 답변에서 지적된 바와 같이, 올바른 방법은 옵션 타입의 캐스트 연산자를 사용하는 것입니다.as?자세한 것은, 을 참조해 주세요.Optional Chaining서브섹션Downcasting.

편집 2

사용자 @KPM의 다른 답변에서 지적된 바와 같이is연산자가 올바른 방법입니다.

체크와 캐스트를 하나의 스테이트먼트로 조합할 수 있습니다.

let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
    ...
}

그럼, 을 사용할 수 있습니다.picker의 범위 내에서if차단합니다.

다음을 사용합니다.

override func touchesBegan(touches: NSSet, withEvent event: UIEvent) {

    super.touchesBegan(touches, withEvent: event)
    let touch : UITouch = touches.anyObject() as UITouch

    if let touchView = touch.view as? UIPickerView
    {

    }
}

새로운 Swift 2 구문을 사용하는 또 다른 접근법은 가드를 사용하여 모든 것을 하나의 조건부로 중첩하는 것입니다.

guard let touch = object.AnyObject() as? UITouch, let picker = touch.view as? UIPickerView else {
    return //Do Nothing
}
//Do something with picker

언급URL : https://stackoverflow.com/questions/24019707/using-iskindofclass-with-swift

반응형