如何解开 Any 类型的可选值? [英] How to unwrap an optional value from Any type?

查看:26
本文介绍了如何解开 Any 类型的可选值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给定一个 [Any] 数组,它混合了可选和非可选值,例如:

Given an array of [Any] that has a mix of optional and non optional values, e.g:

let int:Int? = 1
let str:String? = "foo"

let values:[Any] = [int,2,str,"bar"]

我们如何提取 Any 类型中 Optional 的值(如果有的话),以便我们可以创建一个仅打印出值的通用打印函数.

How can we extract the value of the Optional in the Any type (if there is one) so we can create a generic print function that only prints out the values.

例如这个 printArray 函数遍历并打印每个元素:

E.g. this printArray function goes through and prints each element:

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

我们如何更改它,使其仅打印底层值,以便在它是 Optional 时解开该值?例如:

How can we change it so it only prints the underlying value so that it unwraps the value if it's Optional? e.g:

value[0] = 1
value[1] = 2
value[2] = foo
value[3] = bar

<小时>

更新进度...

将参数更改为 [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)

哪个将打印所需的:

value[0] = 1
value[1] = 2
value[2] = foo
value[3] = bar

但仍想看看我们如何从 Any 中解开 Optional,因为这是 MirrorType.value 返回的内容,因此很难提取 Optional 值,例如:

But would still like to see how we can unwrap an Optional from Any as this is what MirrorType.value returns making it difficult to extract the Optional value, e.g:

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:

For Xcode 7 and 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}]

NSNull() 更改为 nil 并将 unwrap func 的返回值更改为 Any? 将始终打开任何类型.

Change NSNull() to nil and the return value of unwrap func to Any? will always unwrap any type.

这篇关于如何解开 Any 类型的可选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆