shle2821
shle2821

Reputation: 1886

Swift Optionals(?). What's the difference between two?

In terms of the optionals(?), what's the difference between the two? I'm trying to pick up swift and it seems that the location of "?" matters and i'm having a hard time grasping the effect of having "?" in different places.

    var beaconGroup:GroupData = filteredArray.firstObject? as GroupData

    var beaconGroup:GroupData = filteredArray.firstObject as GroupData

Upvotes: 0

Views: 987

Answers (2)

rickster
rickster

Reputation: 126177

There is no difference between those two lines:

var beaconGroup:GroupData = filteredArray.firstObject? as GroupData

var beaconGroup:GroupData = filteredArray.firstObject as GroupData

In the first, the ? is unnecessary — firstObject already returns an Optional. Using the optional chaining operator without actually chaining a further member lookup or access expression has no effect.

In Swift 1.2 (currently available in the Xcode 6.3 beta), superfluous use of the optional chaining operator is a compile error:

error: optional chain has no effect, operation already produces 'AnyObject?'

Upvotes: 3

Zigii Wong
Zigii Wong

Reputation: 7826

An optional in Swift is a variable that can hold either a value or no value. Optionals are written by appending a ? to the type:

var myOptionalString:String? = "Hello"

? are used in two normal ways:

1.Declare a optional var (just add ? after the type)

var strValue : String? 

2.To judge var will respond to the methods or properties while being called

let hashValue = strValue?.hashValue  

If strValue is nil, hashValue is nil. If strValue not nil, thus hashValue is the value of strValue.

Upvotes: 1

Related Questions