반응형
스위프트 : switch 문의 테스트 클래스 유형
Swift에서는 'is'를 사용하여 객체의 클래스 유형을 확인할 수 있습니다. 이것을 '스위치'블록에 어떻게 통합 할 수 있습니까?
나는 그것이 불가능하다고 생각하므로 이것에 가장 좋은 방법이 무엇인지 궁금합니다.
당신은 절대적 is
으로 switch
블록 에서 사용할 수 있습니다 . Swift Programming Language의 "Any and AnyObject에 대한 유형 캐스팅"을 참조하십시오 ( Any
물론 이에 국한되지는 않음 ). 그들은 광범위한 예를 가지고 있습니다 :
for thing in things {
switch thing {
case 0 as Int:
println("zero as an Int")
case 0 as Double:
println("zero as a Double")
case let someInt as Int:
println("an integer value of \(someInt)")
case let someDouble as Double where someDouble > 0:
println("a positive double value of \(someDouble)")
// here it comes:
case is Double:
println("some other double value that I don't want to print")
case let someString as String:
println("a string value of \"\(someString)\"")
case let (x, y) as (Double, Double):
println("an (x, y) point at \(x), \(y)")
case let movie as Movie:
println("a movie called '\(movie.name)', dir. \(movie.director)")
default:
println("something else")
}
}
"case is- case is Int, is string : "작업에 대한 예를 들어 , 여러 케이스를 함께 사용하여 유사한 객체 유형에 대해 동일한 활동을 수행 할 수 있습니다. 여기서 "," 는 OR 연산자 처럼 작동하는 경우 유형을 구분합니다 .
switch value{
case is Int, is String:
if value is Int{
print("Integer::\(value)")
}else{
print("String::\(value)")
}
default:
print("\(value)")
}
값이없는 경우 객체 만 있습니다.
스위프트 4
func test(_ val:Any) {
switch val {
case is NSString:
print("it is NSString")
case is String:
print("it is a String")
case is Int:
print("it is Int")
default:
print(val)
}
}
let str: NSString = "some nsstring value"
let i:Int=1
test(str) // it is NSString
test(i) // it is Int
나는이 문법을 좋아한다 :
switch thing {
case _ as Int: print("thing is Int")
case _ as Double: print("thing is Double")
}
다음과 같이 기능을 빠르게 확장 할 수 있습니다.
switch thing {
case let myInt as Int: print("\(myInt) is Int")
case _ as Double: print("thing is Double")
}
참고 URL : https://stackoverflow.com/questions/25724527/swift-test-class-type-in-switch-statement
반응형
'IT' 카테고리의 다른 글
Joda-Time DateTime을 mm / dd / yyyy로만 포맷하는 방법은 무엇입니까? (0) | 2020.05.19 |
---|---|
SSMS 2008의“상위 200 개 행 편집”에서 SQL을 변경하는 방법 (0) | 2020.05.19 |
git bash의 명령 줄에서 Python이 작동하지 않습니다. (0) | 2020.05.19 |
빈 줄없이 긴 줄을 어떻게 감쌀 수 있습니까? (0) | 2020.05.19 |
외래 키 제약 조건 : ON UPDATE 및 ON DELETE 사용시기 (0) | 2020.05.19 |