Reputation: 1
How do I use data from a UITextField as an Array in Swift? Example: I created the UITextField in ViewController and in it the user inserts: "1, 3, 8, 9, 10, 20" (without the ""). How can I convert this information into an Array in the programming of swift 4 and/or 5 ???
To have as a result:
var arrayInt: [Int] = [mytextField]
arrayInt = [1, 3, 8, 9, 10, 20]
Upvotes: 0
Views: 158
Reputation: 446
Get the text on the UITextField and use .split() method with separator.
"1, 3, 8, 9, 10, 20".split(separator: ",")
That will give you a String array with all the numbers and you'd just have to convert them to Ints.
Edited to exactly match the requirements:
.replacingOccurrences(of: " ", with: "").split(separator: ",").compactMap({Int($0)})
Upvotes: 0
Reputation: 236360
You can use split
method if Character isWholeNumber
property is false and map the resulting elements to Int:
let numbers = textField.text!.split{!$0.isWholeNumber}.compactMap({Int($0)})
numbers // [1, 3, 8, 9, 10, 20]
Upvotes: 1