Convert NSNumber into String Swift 2

22,608

Solution 1

Since the numeric result is supposed to be an Int anyway you can omit the NSNumber detour.

let tempNumber = userInfoDict.valueForKey("designation") as! Int 
let stringTemp = String(tempNumber)

Side note: Since userInfoDict seems to be a dictionary, don't use the key-value coding method valueForKey: unless you really need the special functionality.
Either use key subscripting (recommended) userInfoDict["designation"] or objectForKey:

Solution 2

You'll have to format the NSNumber's doubleValue member to a string before outputting.

let tempNumber:NSNumber = 6.0
let s:String = String(format:"%f", tempNumber.doubleValue) //formats the string to accept double/float
print(s)

Solution 3

You can refer the following code to see how NSNumber can be converted into NSString.

 let a = 10
let aString = String(a)

Its better to avoid complicated codes for simple stuffs.

Share:
22,608
Maninderjit Singh
Author by

Maninderjit Singh

iOS Developer with Swift 2 and Objective C.I did MCA from GNDU Amritsar

Updated on July 30, 2022

Comments

  • Maninderjit Singh
    Maninderjit Singh almost 2 years

    To convert NSNumber Into String Swift 2

    let tempNumber = userInfoDict.valueForKey("designation") as! NSNumber
      let str2 = tempNumber.stringValue
    

    Accurate result

  • Zin Win Htet
    Zin Win Htet over 5 years
    It says "Cannot invoke initializer for type 'String' with an argument list of type '(NSNumber?)'"