Swift: Typ klasy testowej w instrukcji switch

W języku Swift możesz sprawdzić typ klasy obiektu używając 'is'. Jak Mogę włączyć to do bloku "przełącznika"?

Myślę, że to niemożliwe, więc zastanawiam się, co jest najlepszym sposobem na obejście tego.

TIA, Peter.

Author: shim, 2014-09-08

3 answers

Możesz użyć is w bloku switch. Zobacz "Type Casting for Any and AnyObject" w języku programowania Swift (choć nie jest to oczywiście ograniczone do Any). Mają rozbudowany przykład:

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")
    }
}
 303
Author: Rob Napier,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-04-03 17:37:32

Przykład dla operacji " case is- case is Int, is String: ", gdzie można użyć wielu przypadków do wykonania tej samej czynności dla podobnych typów obiektów. Proszę."," rozdzielanie typów w przypadku działa jak operator lub.

switch value{
case is Int, is String:
    if value is Int{
        print("Integer::\(value)")
    }else{
        print("String::\(value)")
    }
default:
    print("\(value)")
}

Demo Link

 33
Author: Abhijeet,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-15 18:13:10

Jeśli nie masz wartości, tylko jakąkolwiek klasę:

func testIsString(aClass: AnyClass) {  
  switch aClass {  
  case is NSString.Type:  
    print(true)  
  default:  
    print(false)  
  }  
}  

testIsString(NSString.self) //->true  

let value: NSString = "some string value" 
testIsString(value.dynamicType) //->true  
 16
Author: Prcela,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-18 12:28:51