给定的数组[Any]具有可选和非可选值的混合,例如:
[Any]
let int:Int? = 1 let str:String? = "foo" let values:[Any] = [int,2,str,"bar"]
我们怎样才能提取的值Optional的Any类型(如果有的话),所以我们可以创建一个通用的打印功能,仅打印出的值。
Optional
Any
例如,此printArray函数通过并打印每个元素:
func printArray(values:[Any]) { for i in 0..<values.count { println("value[\(i)] = \(values[i])") } } printArray(values)
将输出:
value[0] = Optional(1) value[1] = 2 value[2] = Optional("foo") value[3] = bar
我们如何更改它,以便它仅打印基础值,以便在“可选”时解开该值?例如:
value[0] = 1 value[1] = 2 value[2] = foo value[3] = bar
将参数更改为时[Any?],它可以工作,例如:
[Any?]
let values:[Any?] = [int,2,str,"bar"] func printArray(values:[Any?]) { for i in 0..<values.count { println("value[\(i)] = \(values[i]!)") } } printArray(values)
这将打印所需的:
但是仍然想看看我们如何解开Optional,Any因为MirrorType.value返回的结果使得提取Optional值变得困难,例如:
MirrorType.value
class Person { var id:Int = 1 var name:String? } var person = Person() person.name = "foo" var mt:MirrorType = reflect(person) for i in 0 ..< mt.count { let (name, pt) = mt[i] println("\(name) = \(pt.value)") }
打印输出:
id = 1 name = Optional("foo")
当我需要时:
id = 1 name = foo
对于Xcode 7和Swift 2:
func unwrap(any:Any) -> Any { let mi = Mirror(reflecting: any) if mi.displayStyle != .Optional { return any } if mi.children.count == 0 { return NSNull() } let (_, some) = mi.children.first! return some } let int:Int? = 1 let str:String? = "foo" let null:Any? = nil let values:[Any] = [unwrap(int),2,unwrap(str),"bar", unwrap(null)]
这会给你 [1, 2, "foo", "bar", {NSObject}]
[1, 2, "foo", "bar", {NSObject}]
更改NSNull()为,nil并且unfrap func的返回值Any?始终将解开任何类型。
NSNull()
nil
Any?