0

I am building an iOS application using Swift Language. Inside my ViewController2, i have an array of String. How do i convert this array of String to an array of Float value? toPass1 stores numerical values that user enters through the UITextField.

var toPass1 = [String]()
var force = [Float] ()
0

3 Answers 3

7

You can do this

var toPass1 : [String] = ["1.0","2.90","23"]

var force = toPass1.map{
    ($0 as NSString).floatValue
}
Sign up to request clarification or add additional context in comments.

1 Comment

It gives an error stating that ViewController does not have a member named 'toPass1' Part of the code is here [link] (github.com/cherrythia/arraystringstoarrayfloat)
2

Here is an alternative:

var toPass : [String] = ["21.0","3.12","23"]
var force = [Float]()

for item in toPass {
    force.append((item as NSString).floatValue)
}

Comments

1
let toPass = ["1.2", "-15", "4.137e+02"]
let force = toPass.map { Float($0)! }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.