0

What exactly is the difference between a property definition in Swift of:

var window: UIWindow?

vs

var window: UIWindow

I've read it's basically an "optional" but I don't understand what it's for.

This is creating a class property called window right? so what's the need for the '?'

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Woodstock
  • 22,184
  • 15
  • 80
  • 118
  • 2
    Read about it in the documentation: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-XID_428. It's a fundamental concept to Swift – Jack Jun 03 '14 at 21:48
  • Why would uiwindow in this case require an optional? – Woodstock Jun 03 '14 at 21:51
  • 2
    Also all the down votes on this question for no reason make me not want to help out around here as much as I try to. – Woodstock Jun 03 '14 at 21:52
  • 2
    I think in this case, a window might not be initialized/available. Thus, by defining it as an `optional`, if you call `window.addSubView()`, it will not unwrap and just return `nil` – Jack Jun 03 '14 at 21:53
  • 1
    A better example of an `optional` would be for a `delegate` property. This would allow you to call `delegate.protocolFunction()` without checking if `delegate` is `nil`. Please do go read about it in the docs though it does a great job explaining! – Jack Jun 03 '14 at 21:56
  • 1
    After answering and editing, realised that this has already been asked. – nevan king Jun 03 '14 at 22:36

2 Answers2

2

UIWindow? means that the value may be absent. It's either an UIWindow instance or nothing.

Rudolf Adamkovič
  • 31,030
  • 13
  • 103
  • 118
2

The ? identifier means that the variable is optional, meaning its value can be nil. If you have a value in your code, declaring it as non-optional allows the compiler to check at build time if it has a chance to become nil.

You can check whether it is nil in an if statement:

var optionalName: String? = "John Appleseed"

if optionalName {
    // <-- here we know it's not nil, for sure!
}

Many methods that require a parameter to be non-nil will declare that they explicitly need a non-optional value. If you have an optional value, you can convert it into non-optional (for example, UIWindow? -> UIWindow) by unwrapping it. One of the primary methods for unwrapping is an if let statement:

var greeting = "Hello!"

// at this point in the code, optionalName could be nil

if let name = optionalName {
    // here, we've unwrapped it into name, which is not optional and can't be nil
    greeting = "Hello, \(name)"
}

See The Swift Programming Language, page 11 for a brief introduction, or page 46 for a more detailed description.

Tim
  • 14,447
  • 6
  • 40
  • 63