-3

I have some code in Swift on repl.it

let name = readLine()
print("Hello, \(name)!")

When I run it, I type in my name, and then it says "Hello, Optional("Andrew")!". I tried making the variable an optional string, like so:

let name: String? = readLine()
print("Hello, \(name)!")

Same result. What is wrong, and how do I avoid these errors?

Flimzy
  • 68,325
  • 15
  • 126
  • 165
  • 4
    Please read [Optionals](https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html#ID330) in the Swift Language Guide. And as you are a beginner you are encouraged to read the entire Guide – vadian Dec 18 '19 at 19:48
  • Note the print output `Optional("Andrew")!` does not mean the string is equal to that; what you're seeing there is the output of the `debugDescription` for that value. – shim Dec 18 '19 at 19:53
  • Does this answer your question? [What is an optional value in Swift?](https://stackoverflow.com/questions/24003642/what-is-an-optional-value-in-swift) – fhe Dec 18 '19 at 20:13

3 Answers3

2

That's not an error, that's how optionals work!

Clearly the readline() function returns an optional string, which is why you have the issue in the first call.

readline()'s method signature is:

func readLine(strippingNewline: Bool = true) -> String?

So it will always return an optional string.

So if you wish to print without optionals just do:

print("Hello, \(name!)!")

You could also follow best practice and safely 'unwrap':

if let name = readLine() {
  print(name)
}
shim
  • 8,356
  • 10
  • 70
  • 102
Woodstock
  • 21,230
  • 15
  • 76
  • 114
0

You should safely unwrap optionals:

if let name = readLine() {
  print(name)
}

or

guard let name = readLine() else { return }
print(name)
shim
  • 8,356
  • 10
  • 70
  • 102
Sh_Khan
  • 93,445
  • 7
  • 57
  • 76
0

readLine() can most likely also return nil — that's why an optional String is returned.

Use optional binding so that you only use the name if it actually contains a value.

if let name = readLine() {
    print("Hello, \(name)!")
}
fhe
  • 5,977
  • 1
  • 40
  • 43