1
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)
MrHoj
  • 13
  • 2
  • 2
    What are you actually trying to ask ? – Amais Sheikh Apr 04 '21 at 22:10
  • Can I Transform `p:Any` into a `p:Any?` to get an 1.23 from there. is it possible? – MrHoj Apr 04 '21 at 22:23
  • 4
    Optional are just another kind of value, which themselves can be assigned an `Any`. This can lead to confusing behaviour, which is why doing so raises a compiler warning. You ignored that warning, so now you’re seeing that confusing behaviour. So what exactly are you trying to achieve? – Alexander Apr 04 '21 at 23:01

1 Answers1

2

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

aheze
  • 24,434
  • 8
  • 68
  • 125
  • 1
    not a bad solution. if I don't know the original data type in the OpDoub? is there a way not to check each data type? I would like to translate any type of data into a string, right away... – MrHoj Apr 06 '21 at 15:07