Answers:
您绝对可以is
在一个switch
块中使用。请参阅Swift编程语言中的“ Any和AnyObject的类型转换”(尽管Any
当然不限于此)。他们有一个广泛的例子:
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")
}
}
is
”-然后他从不使用它。X)
case is Double
在答案中看到@Raphael
以“ case is- case is Int,is String: ”操作为例,可以将多个case组合使用,以对“相似对象”类型执行相同的活动。在这种情况下,如果类型像OR运算符一样,则分隔类型的“,”。
switch value{
case is Int, is String:
if value is Int{
print("Integer::\(value)")
}else{
print("String::\(value)")
}
default:
print("\(value)")
}
if
可能不是证明您观点的最佳示例。
value
是的东西,可以是一个Int
,Float
,Double
,和治疗Float
,并Double
以同样的方式。
如果您没有值,则可以使用任何对象:
迅捷4
func test(_ val:Any) {
switch val {
case is NSString:
print("it is NSString")
case is String:
print("it is a String")
case is Int:
print("it is int")
default:
print(val)
}
}
let str: NSString = "some nsstring value"
let i:Int=1
test(str)
// it is NSString
test(i)
// it is int
thing
在以上任何一项中均未在switch`中使用,因此在case
这里使用有thing
什么用?我没看到 谢谢。