da1lbi3 da1lbi3 - 1 year ago 150
Swift Question

Convert or cast object to string

how can i convert any object type to a string?

let single_result = results[i]
var result = ""
result = single_result.valueForKey("Level")

now i get the error: could not assign a value of type any object to a value of type string.

and if i cast it:

result = single_result.valueForKey("Level") as! String

i get the error:
Could not cast value of type '__NSCFNumber' (0x103215cf0) to 'NSString' (0x1036a68e0).

How can i solve this issue?

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download