John Doe
John Doe

Reputation: 25

Convert String to Double and check for nil

I have multiple Strings in an array: "1.1", "AA", "1", nil etc... I need to convert the Strings to Double if possible. I have tried this but the code crashes on nil.

let doubleValue = Double(array[3]!) // 3 = nil

It´s ok if I get nil, at least I know that the value can´t be a Double.

Any suggestions?

Upvotes: 0

Views: 96

Answers (2)

Alexander
Alexander

Reputation: 63271

The best approach to do this is to use map on Optional:

let doubleValue = array[3].map(Double.init)

In the case that you want to map all of the array to strings, use map:

let doubles = array.map(Double.init)

If you want to filter out all non-double Strings rather than keeping them as nil, use flatMap:

let doubles = array.flatMap(Double.init)

Upvotes: 0

RajeshKumar R
RajeshKumar R

Reputation: 15758

It crashes because you are trying to unwrap a nil value. Try giving a default value like this.

let doubleValue = Double(test[3] ?? "") 
print(doubleValue) //nil 

let dobuleArray = array.map({ Double($0 ?? "") })

Upvotes: 2

Related Questions