ios - Match the data type of a object in Swift -
how match data type of object in swift?
like:
var xyz : xyz = 1; switch xyz { case let x xyz as?anyobject[]: println("\(x) anyobject type") case let x xyz as?string[]: println("\(x) string type") case let x xyz as?int[]: println("\(x) int type") case let x xyz as?double[]: println("\(x) double type") case let x xyz as?float[]: println("\(x) float type") default:println("none") }
in case switch case run default case
change var xyz : anyobject
var xyz : any
, add match case
case let x int:
from repl
1> var : = 1 a: int = <read memory 0x7fec8ad8bed0 failed (0 of 8 bytes read)> 2> switch { case let x int: println("int"); default: println("default"); } int
from the swift programming language
you can use , operators in switch statement’s cases discover specific type of constant or variable known of type or anyobject. example below iterates on items in things array , queries type of each item switch statement. several of switch statement’s cases bind matched value constant of specified type enable value printed:
for thing in things { switch thing { case 0 int: println("zero int") case 0 double: println("zero double") case let someint int: println("an integer value of \(someint)") case let somedouble double somedouble > 0: println("a positive double value of \(somedouble)") case double: println("some other double value don't want print") case let somestring string: println("a string value of \"\(somestring)\"") case let (x, y) (double, double): println("an (x, y) point @ \(x), \(y)") case let movie movie: println("a movie called '\(movie.name)', dir. \(movie.director)") default: println("something else") } } // 0 int // 0 double // integer value of 42 // positive double value of 3.14159 // string value of "hello" // (x, y) point @ 3.0, 5.0 // movie called 'ghostbusters', dir. ivan reitman
note:
var xyz : anyobject = 1
will give nsnumber
because int
not object auto convert nsnumber
object
Comments
Post a Comment