0

Basically I'm getting the user to input a number 1-3 and I want to take the user's inputted number and compare it with a random number. This is my 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 I try to print userNumber it returns "nil" any suggestions? thanks!

Amit Raj
  • 1,358
  • 3
  • 22
  • 47

4 Answers4

1

I'm Dutch, so my English isn't very good. Sorry for that.
This is the answer that works:

import Foundation

print("What is your age?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData

if let data = fhcpy{
    var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
    var numstr: String = ""
    for char in str.characters {
        if Int("\(char)") != nil {
            numstr.append(char)
        }
    }
    var num: Int? = Int(numstr)
    if let opNum = num {
        print("Your age is \(opNum)")
    } else {
        print("That is not a valid number. ")
    }
}

How I have done it
First, I tred the Swift 1.0 method, but that did cause a error (Get input in swift 1.0). It was the if let method (Error handling). after that, I have made a optional called fhcpy with the NSDate value of fh.availbleData. Which solved the problem of the if let. Now we want to get an Int value (Get Int value). Now we do that with Int(), but it returns every time nil. We use a for to look what is inside the variable str.
Code:

import Foundation

print("What is your age?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData

if let data = fhcpy{
    var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String
    for char in str.characters {
        print(char)
    }
    var num: Int? = Int(str)
    print("Your age is \(num)")
}

Output:

What is your age?
12
1
2


Your age is nil
Program ended with exit code: 0

Did you see the newline? So we program a for that tests for "If a character in the string is an Int the Character will be append to the strnum". At the end, the strnum is exported to an Int.

Sample code:

import Foundation

print("What is your name?")
var fhcpy: NSData? = NSFileHandle.fileHandleWithStandardInput().availableData

if let data = fhcpy{
    var str: String = NSString(data: data, encoding: NSUTF8StringEncoding) as! String

    print("Your name is \(str)")
}
Community
  • 1
  • 1
  • Use in place of `fhcpy`, `fhad` (file handle available Data). Which is a lot more universal. – DutchCraftMaster Nov 14 '15 at 15:27
  • Also, "the answer that works" is not specialized on the Int value. Becaus if you enter `#%@3!$#5`, it wil display: `Your age is 35`. But now you know that there is a `"\n"` after the input. – DutchCraftMaster Nov 14 '15 at 15:31
0

It might cause of syntax ordering. Parse string to int and print result would be faster than fetch user input. I suggest you to make completion closure, something like below code.

inputTest({
    (result: String?) in
    print("got back: \(result)")
    var userNumber: Int? = Int(result!)
    print(userNumber)
})

func inputTest(completion: (result: String?) -> Void) {
    let keyboard = NSFileHandle.fileHandleWithStandardInput()
    let inputData = keyboard.availableData

    completion(result: NSString(data: inputData, encoding:NSUTF8StringEncoding) as? String)
}
jamesBlake
  • 166
  • 1
  • 8
0

The initializer Int() is basically correct but could return nil because for example letters cannot be converted to an integer representation. So you have to perform a check

let userInput = "Hello" 
if let userInputInteger = Int(userInput) {
  print("OK")
  // do something with userInputInteger
} else {
  print("\(userInput) cannot be converted to integer")
}
vadian
  • 274,689
  • 30
  • 353
  • 361
-1

Try this one

var userNumber: Int = userInput.toInt()!
MaappeaL
  • 514
  • 1
  • 8
  • 16
  • The question is addressing Swift 2.0 as `.toInt()` was removed from `String`. See http://stackoverflow.com/a/30773127/5181636 – Caleb Sep 30 '15 at 03:12