Convert or cast object to string

This is the documentation for the String initializer provided here.

let s = String(describing: <AnyObject>)

Nothing else is needed. This works for a diverse range of objects.


You can't cast any random value to a string. A force cast (as!) will fail if the object can't be cast to a string.

If you know it will always contain an NSNumber then you need to add code that converts the NSNumber to a string. This code should work:

if let result_number = single_result.valueForKey("Level") as? NSNumber
{
  let result_string = "\(result_number)"
}

If the object returned for the "Level" key can be different object types then you'll need to write more flexible code to deal with those other possible types.

Swift arrays and dictionaries are normally typed, which makes this kind of thing cleaner.

I'd say that @AirSpeedVelocity's answer (European or African?) is the best. Use the built-in toString function. It sounds like it works on ANY Swift type.

EDIT:

In Swift 3, the answer appears to have changed. Now, you want to use the String initializer

init(describing:)

Or, to use the code from the question:

result = single_result.valueForKey("Level")
let resultString = String(describing: result)

Note that usually you don't want valueForKey. That is a KVO method that will only work on NSObjects. Assuming single_result is a Dictionary, you probably want this syntax instead:

result = single_result["Level"]

Tags:

Swift