Swift: Tipo de clase de prueba en la instrucción switch


En Swift se puede comprobar el tipo de clase de un objeto usando 'is'. ¿Cómo puedo incorporar esto en un bloque 'switch'?

Creo que no es posible, así que me pregunto cuál es la mejor manera de evitar esto.

TIA, Pedro.

Author: shim, 2014-09-08

3 answers

Definitivamente puedes usar is en un bloque switch. Consulte "Type Casting for Any y AnyObject" en el Lenguaje de programación Swift (aunque no está limitado a Any, por supuesto). Tienen un ejemplo extenso:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-03 17:37:32

Poniendo el ejemplo para la operación "case is - case is Int, is String:", donde se pueden usar múltiples casos agrupados para realizar la misma actividad para tipos de objetos Similares. Aquí "," separar los tipos en caso es operar como un operador O.

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

Enlace de demostración

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-09-15 18:13:10

En caso de que no tenga un valor, cualquier clase:

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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-18 12:28:51