Search code examples
iosswiftstringanyobject

swift 3 - ios : convert anyObject to string


How could we convert anyobject to string in swift 3, it's very easy in the older version by using.

var str = toString(AnyObject)

I tried String(AnyObject) but the output is always optional, even when i'm sure that AnyObject is not a optional value.


Solution

  • The compiler suggests that you replace your code with:

    let s = String(describing: str)
    

    One other option is available if you have a situation where you want to silently fail with an empty string rather than store something that might not originally be a string as a string.

    let s =  str as? String ?? ""
    

    else you have the ways of identifying and throwing an error in the answers above/below.