Optionals using?

I'm using a MacBook Air with macOS10.14.5 and Xcode 10.2.1. When testing the code below, why won't the default "Unknown" appear in LblMessage when no text has been entered in TxtName and the button is pushed?

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var LblMessage: UILabel!
@IBOutlet weak var TxtName: UITextField!
@IBAction func pushButton( _ sender: Any ) {
let userName: String = TxtName.text ?? "Unknown"
LblMessage.text = "Hello " + userName

override func viewDidLoad() {
super .viewDidLoad()


There's a difference between nil (ie. no string), and "" (ie, the empty string).
You could either test for the empty string, or maybe even create a convenience on strings through an extension:

extension StringProtocol {
  var nonEmpty: Self? {
    return isEmpty ? nil : self

let name = textfield.text.nonEmpty ?? "Unknown"
label.text = "Hello " + name

(Not tested)

Got it. Should have known a Text Field contains an empty string by default. Fixed the problem with:

var txtName: String? = TxtName.text
if txtName == "" {
txtName = nil
let userName: String = txtName ?? "Unknown"

Why not add an extension to Optional like this :

extension Optional where Wrapped == String
  var isNilOrEmpty: Bool
    switch self
      case .some(let value):
        return value.isEmpty
      case .none:
        return true

Then you can write something like this :

@IBAction func pushButton( _ sender: Any )
  label.text = textField.text.isNilOrEmpty ? "Unknown" : textField.text

By the way, don't use capital letters to begin variable and function names.

Terms of Service

Privacy Policy

Cookie Policy