展开非可选值

Unwrap value of non-optional

var OpDoub:Optional<Double> = 1.23

func noopt(_ pp: Any) -> Any  {
    return pp
}
var p:Any = noopt(OpDoub)
print(p)  // Optional(1.23)
print(p!) // error: cannot force unwrap value of non-optional type 'Any'

我可以在声明 P 后得到值 1.23 吗? 我试过了:

var pp:Any? = p
print(pp)  // Optional(Optional(1.23)) it turned out even worse :D
print(pp!) // Optional(1.23)

如果你想得到

1.23

... 那么你应该 downcast pDouble:

var OpDoub:Optional<Double> = 1.23

func noopt(_ pp: Any) -> Any  {
    return pp
}
var p:Any = noopt(OpDoub)
    
if let doubleP = p as? Double { /// here!
    print(doubleP) /// result: 1.23
}

编辑

如果你想解包 p(让它不是可选的)并将它变成一个字符串,那么试试这个(基于 ):

func unwrap(_ instance: Any) -> Any {
    let mirror = Mirror(reflecting: instance)
    if mirror.displayStyle != .optional {
        return instance
    }
    
    if mirror.children.count == 0 { return NSNull() }
    let (_, some) = mirror.children.first!
    return some
}

let unwrappedP = unwrap(p)
let string = "\(unwrappedP)" /// using String Interpolation https://docs.swift.org/swift-book/LanguageGuide/StringsAndCharacters.html#ID292
print("unwrapped string: \(string)")

结果:

unwrapped string: 1.23