StefLand
StefLand

Reputation: 21

Swift 4 - Convert string in double value with NSString

I want to convert a String in a NSString, for obtaining a double value. But I have an error:

Argument labels '(_:)' do not match any available overloads.

How can I fix this?

NSString as! String

Upvotes: 0

Views: 4115

Answers (4)

HardikDabhi
HardikDabhi

Reputation: 2952

Swift 3 & 4

String to Double

CartAmount = (response.object(forKey:"amount")as! NSString).doubleValue!

Double to String

let string = String(CartAmount)

Upvotes: 0

Vishal Vaghasiya
Vishal Vaghasiya

Reputation: 4901

swift 4 - String to Double || NSString to Double

try this

 let nsstring:NSString = "111.11"
        let str:String = "111.11"

        let tempString = (str as NSString).doubleValue
        print("String:-",tempString)

        let temp = nsstring.doubleValue
        print("NSString",temp)

Output

String:- 111.11
NSString 111.11

Upvotes: -1

vadian
vadian

Reputation: 285069

Don't do that.

Basically you can bridge cast String to NSString

let nsString = "12.34" as NSString
print(nsString.doubleValue)

rather than using an initializer (the error message says there is no appropriate initializer without a parameter label), but casting to NSString to get the doubleValue is the wrong way in Swift.

Get the String, use the Double initializer and unwrap the optionals safely

if let lat = array[indexPath.row]["lat"] as? String, 
   let latAsDouble = Double(lat) {
       // do something with latAsDouble
}

Upvotes: 5

Hesham Nasser
Hesham Nasser

Reputation: 121

I guess you have to use this syntax to convert

let myString = "556"
let myFloat = (myString as NSString).doubleValue

Upvotes: 1

Related Questions