Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert or cast object to string

Tags:

swift

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?

like image 431
da1lbi3 Avatar asked May 16 '15 19:05

da1lbi3


People also ask

How do you cast an object to a string in Python?

Python is all about objects thus the objects can be directly converted into strings using methods like str() and repr(). Str() method is used for the conversion of all built-in objects into strings. Similarly, repr() method as part of object conversion method is also used to convert an object back to a string.

How do I convert an object to a string in Salesforce?

String jsonStr = JSON. serialize(obj);

How do I cast an object to a string in VB net?

CType (var, String) will convert the given type into a string, using any provided conversion operators. DirectCast (var, String) is used to up-cast an object into a string. If you know that an object variable is, in fact, a string, use this.


2 Answers

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"] 
like image 113
Duncan C Avatar answered Nov 10 '22 23:11

Duncan C


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.

like image 30
ScottyBlades Avatar answered Nov 11 '22 01:11

ScottyBlades