Reputation: 13
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)
Upvotes: 1
Views: 202
Reputation: 30228
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
Upvotes: 2