0

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
shle2821
  • 1,856
  • 1
  • 19
  • 26
  • possible duplicate of [What does an exclamation mark mean in the Swift language?](http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language) – Nikos M. Mar 11 '15 at 17:14
  • 1
    Actually there is no difference between both. The second is just a shorter form (syntactic sugar) of the first – qwerty_so Mar 11 '15 at 17:50

2 Answers2

3

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

rickster
  • 124,678
  • 26
  • 272
  • 326
1

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.

Zigii Wong
  • 7,766
  • 8
  • 51
  • 79