Swift 中如何匹配对象的数据类型?
Like:
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")
}
在这种情况下 switch case 运行 default case
change var xyz : AnyObject
to var xyz : Any
并添加它将与这种情况匹配
case let x as Int:
来自 REPL
1> var a : Any = 1
a: Int = <read memory from 0x7fec8ad8bed0 failed (0 of 8 bytes read)>
2> switch a { case let x as Int: println("int"); default: println("default"); }
int
from Swift 编程语言
您可以在 switch 语句的 case 中使用 is 和 as 运算符来
发现已知常量或变量的特定类型
只能是 Any 或 AnyObject 类型。下面的例子迭代了
things 数组中的项目并使用 a 查询每个项目的类型
开关语句。 switch 语句的几个 case 绑定了它们
将值与指定类型的常量匹配以启用其值
待打印:
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
Note:
var xyz : AnyObject = 1
会给你NSNumber
因为Int
不是对象,因此它会自动将其转换为NSNumber
这是对象
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)