3

The following code runs fine in the iOS Simulator, but causes an EXC_BAD_ACCESS exception on the device.

Is this a bug in Swift or am I just doing something weird here?

What doesn't work:

class Foo: NSObject {
    class var name: String {
        return "A foo"
    }
}

struct FooWrapper<T: Foo> {
    var fooName: String

    init(foo: T) {
        fooName = foo.dynamicType.name
    }
}

var foo = Foo()
var fooWrapper = FooWrapper(foo: foo)
println(fooWrapper.fooName)

To make it work, either:

  • Use (foo as Foo).dynamicType.name
  • Or, remove NSObject as the superclass of Foo
Rengers
  • 14,911
  • 1
  • 36
  • 54
  • What do you know, two questions about weird behaviour from mixing dynamic objc-like stuff with generics on the same day: http://stackoverflow.com/questions/27779473/how-to-use-a-protocol-with-optional-class-methods-in-an-extension-with-generic-i/27785342#27785342 Your code looks correct so presumably a bug unless there's something funny about a piece of code not shown – if you create a brand-new project with just this code, does it still crash? As an alternative, if the class function doesn't actually access class variables, you could ditch dynamicType and use a regular overridden function. – Airspeed Velocity Jan 05 '15 at 19:49
  • Ah haha yes, the perks of being a Swift guinea pig ;). This code comes from a brand-new test project to debug this. I need it to be a class variable, so for now I use a workaround. – Rengers Jan 05 '15 at 19:56

0 Answers0