How to take input in swift

142 views Asked by At

I was trying to get Boolean data with readLine()! but cannot input it

There was a compilation error saying


error: cannot convert value of type 'String' to specified type 'Bool'

1

There are 1 answers

0
DarkDust On

readLine() returns a String?. You cannot implicitly convert a String to Bool.

Swift does not know what strings you consider to be a valid boolean value. Are 0 and 1 considered boolean values by your app? no and yes? falsch and wahr? Swift does not know. You need to parse it yourself, for example:

let myBool: Bool

switch stringInput.lowercased() {
case "false", "no", "0": myBool = false
case "true", "yes", "1": myBool = true
default:
    print("Invalid input")
    return
}

print(myBool)