ios - convert user input to array of Ints in swift -
i'm trying make simple ios game learn programming in swift. user inputs 4 digits number in text field (keyboard type number pad if matters) , program should take 4 digits number , put each digit in array. want like
userinput = "1234"
to become
inputarray = [1,2,3,4]
i know converting string array of characters easy in swift
var text : string = "barfoo" var arraytext = array(text) //returns ["b","a","r","f","o","o"]
my problem need array filled integers, not characters. if convert user input int, becomes single number if user enters "1234" array gets populated [1234] , not [1,2,3,4]
so tried treat user input string, make array of characters and, loop through elements of array, convert them ints , put them second array, like:
var input : string = textfield.text var inputarray = array(input) var intsarray = [int]() var = 0; < inputarray.count ; i++ { intsarray[i] = inputarray[i].toint() }
but doesn't compile , gives me error: 'character' not have member named 'toint'
what doing wrong?
you use:
let text : string = "123a" let digits = array(text).map { string($0).toint()! } // crash if character not int
but crash if input not valid.
you can validate checking result of toint()
:
let text : string = "1234" var digits = array(text).reduce([int](), combine: { (var digits, optionaldigit) -> [int] in if let digit = string(optionaldigit).toint() { digits.append(digit) } return digits }) if countelements(text) == digits.count { // digits valid } else { // has invalid digits }
Comments
Post a Comment