input - How to get Int value from String Swift 2.0 -
basically i'm getting user input number 1-3 , want take user's inputted number , compare random number. code:
func input() -> string { let keyboard = nsfilehandle.filehandlewithstandardinput() let inputdata = keyboard.availabledata return nsstring(data: inputdata, encoding:nsutf8stringencoding) as! string } var userinput = input() var usernumber: int? = int(userinput)
when try print usernumber returns "nil" suggestions? thanks!
i'm dutch, english isn't good. sorry that.
this answer works:
import foundation print("what age?") var fhcpy: nsdata? = nsfilehandle.filehandlewithstandardinput().availabledata if let data = fhcpy{ var str: string = nsstring(data: data, encoding: nsutf8stringencoding) as! string var numstr: string = "" char in str.characters { if int("\(char)") != nil { numstr.append(char) } } var num: int? = int(numstr) if let opnum = num { print("your age \(opnum)") } else { print("that not valid number. ") } }
how have done it
first, tred swift 1.0 method, did cause error (get input in swift 1.0). if let
method (error handling). after that, have made optional called fhcpy
nsdate
value of fh.availbledata
. solved problem of if let
. want int
value (get int value). int(), returns every time nil
. use inside variable str
.
code:
import foundation print("what age?") var fhcpy: nsdata? = nsfilehandle.filehandlewithstandardinput().availabledata if let data = fhcpy{ var str: string = nsstring(data: data, encoding: nsutf8stringencoding) as! string char in str.characters { print(char) } var num: int? = int(str) print("your age \(num)") }
output:
what age? 12 1 2 age nil program ended exit code: 0
did see newline? program for
tests "if character in string int
character
append strnum
". @ end, strnum
exported int
.
sample code:
import foundation print("what name?") var fhcpy: nsdata? = nsfilehandle.filehandlewithstandardinput().availabledata if let data = fhcpy{ var str: string = nsstring(data: data, encoding: nsutf8stringencoding) as! string print("your name \(str)") }
Comments
Post a Comment