Search code examples
swiftresponsewaitadventure

Let a function wait for response - Swift


Im trying to programm a text adventure. I have a NSTextView in which the user can write commands and get a response but I can't find a way to "pause" a function to wait for the users response.

import Cocoa

@IBOutlet var textView: NSTextView!

var playerName:String = ""
var enteredString:String = ""

//Keyboard Input

private func returnChar(theEvent: NSEvent) -> Character?{
    let s: String = theEvent.characters!
    for char in s{
        return char
    }
    return nil
}

override func keyUp (theEvent: NSEvent) {
    let s: String = String(self.returnChar(theEvent)!)
    enteredString.extend(s)

    if theEvent.keyCode == 36 {

        //Here I'd like to 
        //say that start() 
        //should continue

    }
}

//Story

func start() {
    textView.string?.extend("Hi, what's your name?\n")

    //Here I'd like to 
    //wait for the
    //users response

    playerName = enteredString
    textView.string?.extend("Are you sure that I should call you \(playerName)")

}

Thanks for your reply :D


Solution

  • If you are using Swift 2 you can use readLine() that waits until the user presses enter in the command line. And it returns String? because the user can hit enter without having typed anything.