swift 3 - ios : convert anyObject to string

Anthony Shahine picture Anthony Shahine · Oct 14, 2016 · Viewed 49.1k times · Source

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.

Answer

sketchyTech picture sketchyTech · Oct 14, 2016

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.