简体   繁体   中英

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'

Can I, after declaring a P, get the value 1.23? I tried:

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

If you're trying to get just

1.23

... then you should downcast p to a Double :

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
}

Edit

If you want to unwrap p (make it not optional) and turn it into a String, then try this (based off this awesome answer ):

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)")

Result:

unwrapped string: 1.23

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM