Skip to content

Instantly share code, notes, and snippets.

@rjstelling
Created June 15, 2016 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rjstelling/02b6beaf6c73e4be953f9c13b577ac62 to your computer and use it in GitHub Desktop.
Save rjstelling/02b6beaf6c73e4be953f9c13b577ac62 to your computer and use it in GitHub Desktop.
A Playground that demos a bug where a cast using `as` causes a, "fatal error: can't unsafeBitCast between types of different sizes".
//: Playground - Demos a bug where a cast using `as` causes a, "fatal error: can't unsafeBitCast between types of different sizes"
import UIKit
protocol Thingable {
func getStuff()
}
enum MyList: Thingable {
case One
case Two
func getStuff() {
print("BOOM!")
}
}
class MyClass<T: Thingable> {
lazy var things: [Thingable]? = nil
}
class MyConcreateClass: MyClass<MyList> {
override init() {
super.init()
/*** Because `things` is of type `T: Thingable` adding MyList objects worksa as expected,
however truing to cast using `self.things as? [MyList]` fails with the error
"fatal error: can't unsafeBitCast between types of different sizes" ***/
self.things = [MyList.One, MyList.One, MyList.Two, MyList.Two]
}
func doCast() -> [MyList]? {
var temp1 : [MyList] = []
for item in self.things! {
/*** Reports its type as MyList ***/
//print("ITEM: \(item.dynamicType) -> \(item)")
/*** This gives the error
Playground execution failed: MyPlayground.playground:35:26: error: cannot convert value of type 'Thingable' to expected argument type 'MyList' ***/
//temp1.append(item)
/*** This works!? ***/
temp1.append(item as! MyList)
}
/*** Also fails with: fatal error: can't unsafeBitCast between types of different sizes ***/
//if self.things is [MyList] {
// //wont work!
//}
/*** This fails: fatal error: can't unsafeBitCast between types of different sizes ***/
//let temp = self.things as? [MyList]
/*** flatMap() is a workaround ***/
return self.things?.flatMap { $0 as? MyList }
/*** fails ***/
//return self.things as [MyList]
//return temp1
}
}
class Wrapper: NSObject {
lazy var concreate: MyConcreateClass = MyConcreateClass()
}
let stone = Wrapper()
let objects = stone.concreate.doCast()
print("Objects: \(objects!)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment