반응형
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
반응형
'programing' 카테고리의 다른 글
부울 목록을 기준으로 목록 필터링 (0) | 2023.04.14 |
---|---|
다운로드한 Xcode 시뮬레이터를 제거하는 방법 (0) | 2023.04.14 |
목표 C에서의 NULL 대 0 (0) | 2023.04.14 |
Nullable, __nullable 및 _Nullable in Objective-C의 Nullable의 차이 (0) | 2023.04.14 |
Windows에서 pip install 액세스가 거부되었습니다. (0) | 2023.04.09 |