-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?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
  • 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
  • 9,289
  • 12
  • 69
  • 108
Woodstock
  • 22,184
  • 15
  • 80
  • 118
0

You should safely unwrap optionals:

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

or

guard let name = readLine() else { return }
print(name)
shim
  • 9,289
  • 12
  • 69
  • 108
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
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
  • 6,099
  • 1
  • 41
  • 44