rajvir singh
rajvir singh

Reputation: 111

How to get input from user using Swift in playground project in Xcode 8.2?

I am trying to get the dynamic input from user in playground for iOS but it's not working. I tried the following code but it didn't work.

import Foundation
import UIKit
func input() -> String {
    var keyboard = FileHandle.standardInput
    var inputData = keyboard.availableData
    var strData = NSString(data: inputData, encoding: String.Encoding.utf8.rawValue)!

    return strData.trimmingCharacters(in: NSCharacterSet.newlines)
}

input()

Upvotes: 4

Views: 19118

Answers (5)

oskarko
oskarko

Reputation: 4178

Is it possible to read keyboard input in a playground?

NO.

To experiment keyboard input features like readLine(), create an macOS > Command Line Tool project and run it in Xcode, You will be able to write in the Xcode console.screenshot

Upvotes: 0

Osama Khalifa
Osama Khalifa

Reputation: 373

Getting input from playground is not doable, You can do it in an XCode project using:

print("Please enter your name")
var name = readLine()
print("name: \(name!)")

Or:

func input() -> String {
   let keyboard = FileHandle.standardInput
   let inputData = keyboard.availableData
   return String(data: inputData, encoding: .utf8)!
}

print("Please enter your name")
var name = input()
print("name: \(name!)")

Upvotes: 6

AdskiYojeG
AdskiYojeG

Reputation: 31

Is it possible to “Answer” project in the same section as an empty playground. You can use “ask()” and “show()” methods.

For example:

func square(num: Double) -> Double {
    return num * num
}

show("Please type a number to square it:")
var sqrt = askForNumber()
show("Result: \(square(num: Double(sqrt)))")

Sorry, I’m writing on iPad and it’s difficult to input code.

How it looks during execution

Upvotes: -2

Saravit Soeng
Saravit Soeng

Reputation: 561

I don't think it's possible to get the user input on Playground of Xcode.

Upvotes: 2

Josh Homann
Josh Homann

Reputation: 16327

You can get your playground input from a textField as follows:

    import PlaygroundSupport
    import UIKit

    class V: UIViewController {
        var textField = UITextField(frame: CGRect(x: 20, y: 20, width: 200, height: 24))
        override func viewDidLoad() {
            super.viewDidLoad()
            view.addSubview(textField)
            textField.backgroundColor = .white
            textField.delegate = self
        }
    }
    extension V: UITextFieldDelegate {
        func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
            // Do stuff here
            return true
        }
    }
    let v = V()
    v.view.frame = CGRect(x: 0, y: 0, width: 300, height: 300)
    PlaygroundPage.current.liveView = v.view
    PlaygroundPage.current.needsIndefiniteExecution = true

Upvotes: 5

Related Questions