I am trying to make an app that will allow a user to input a 9-digit integer into a text field. The app will then add the 3rd and 5th integers of the number and display the result on a separate label. I figured the best way to go about this would be to convert the 9-digit integer into an array and then adding the 2nd and 4th value of the array together and displaying the value. I am not sure how to do this though. Any help is appreciated! Thanks
1 Answer
Here's how you can do it. You take the text from text field, make an array of characters from it and then convert it to [Int] array.
let text = "24513567" // get the text from text field
let textArray = text.characters
let numbers = textArray.map { Int(String($0)) }
if let first = numbers[3], second = numbers[5] {
let sum = first + second
}
This will yield 6 as a result