匹配Swift中对象的数据类型
如何匹配Swift中对象的数据类型?
喜欢:
var xyz : Any xyz = 1; switch xyz { case let x where xyz as?AnyObject[]: println("\(x) is AnyObject Type") case let x where xyz as?String[]: println("\(x) is String Type") case let x where xyz as?Int[]: println("\(x) is Int Type") case let x where xyz as?Double[]: println("\(x) is Double Type") case let x where xyz as?Float[]: println("\(x) is Float Type") default:println("None") }
在这种情况下,开关盒运行默认情况
将var xyz : AnyObject
更改为var xyz : Any
并添加它将匹配此案例
case let x as Int:
来自REPL
1> var a : Any = 1 a: Int = 2> switch a { case let x as Int: println("int"); default: println("default"); } int
来自Swift编程语言
您可以在switch语句的情况下使用is和as运算符来发现常量或变量的特定类型,该常量或变量只有Any或AnyObject类型。 下面的示例遍历things数组中的项目,并使用switch语句查询每个项目的类型。 有几个switch语句将它们的匹配值绑定到指定类型的常量,以使其值可以打印:
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)") 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") } } // zero as an Int // zero as a Double // an integer value of 42 // a positive double value of 3.14159 // a string value of "hello" // an (x, y) point at 3.0, 5.0 // a movie called 'Ghostbusters', dir. Ivan Reitman
注意:
var xyz : AnyObject = 1
将为您提供NSNumber
因为Int
不是对象,因此它会自动将其转换为NSNumber
,这是对象
提出“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)") }
类似post与演示链接