IT

스위프트 : switch 문의 테스트 클래스 유형

lottoking 2020. 5. 19. 08:25
반응형

스위프트 : 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

반응형