netdigger
netdigger

Reputation: 3789

Casting in Swift 3.0

I can't find anything about changes in the type-casting in the Swift 3.0 migration guide. However, I've stumbled upon some issued.

Consider this playground: (which btw doesnt compile in Xcode 7.3.1 version of Swift)

var data1: AnyObject?
var data2: AnyObject?
var data3: AnyObject?

var tmpAny: Any?
var tmpString = "Hello!"

tmpAny = tmpString

data1 = tmpAny as AnyObject
data2 = tmpAny as AnyObject?
data3 = tmpAny as? AnyObject // Warning "Conditional cast from 'Any?' to 'AnyObject' always succeeds

print(type(of: data1))
print(type(of: data1!))

print()

print(type(of: data2))
print(type(of: data2!))

print()

print(type(of: data3))
print(type(of: data3!))

it prints:

Optional<AnyObject>
_SwiftValue

Optional<AnyObject>
_NSContiguousString

Optional<AnyObject>
_SwiftValue

in Swift 3.0.

Mainly, what's the difference between, tmpAny as AnyObject and tmpAny as AnyObject??

Upvotes: 2

Views: 3472

Answers (1)

pedrouan
pedrouan

Reputation: 12910

Casting:

switch data1 {
    case 0 as Int: 
    // use 'as' operator if you want to to discover the specific type of a constant or variable that is known only to be of type Any or AnyObject.
}

In Swift 1.2 and later, as can only be used for upcasting (or disambiguation) and pattern matching. Upcasting means guaranteed casting, meaning that it will cast successfully).

data1 as AnyObject? 
// means that it's an Optional Value, it may either contain an AnyObject or it may be nil

data2 = tmpAny is AnyObject // when used 'is', data2 will be true if the instance is of that subclass type and false if it is not

Downcasting:

Since downcasting can fail, type casting can be marked with ? or !.

data3 = tmpAny as? AnyObject 
// returns optional value of the type you are trying to downcast to
// do this if you're not sure if it succeeds
// if data3 couldn't be AnyObject, it would assign nil to the optional 
// means when you don't know what you're downcasting, you are assuming that it is Any, but it might be AnyObject, Integer or Float...
// that's why compiler warns - casting from 'Any?' to 'AnyObject' always succeeds

data4 = tmpAny as! AnyObject 
// attempts to downcast and force-unwraps the result after, as well
// do this if you're sure it succeeds, otherwise it will cause a runtime error if a wrong class/type is set

Upvotes: 1

Related Questions