0

Seems swift has some problems when it deal with generic class. Seems these code can be compiled but will have run time error when meet println(act.actId). It throw out a EXC_BAD_ACCESS bug.

Is there any other way or workaround about this issue?

public class Item {
    public var id: String
    public init(str: String) {
        id = str
    }
}

public class Account: Item {
    public var actId: String
    public override init(str: String) {
        actId = "antId: \(str)"
        super.init(str: str)
    }
}

public class Keyword: Item {
    public var keywordId: String
    public override init(str: String) {
        keywordId = "keywordId: \(str)"
        super.init(str: str)
    }

}

public class Creator<T: Item> {
    public func parse(str: String) -> T {
        var result: T = T(str: str)
        return result
    }
}

var a = Creator<Account>()
var act = a.parse("Apple")
println(act.actId)
Bruno Bu
  • 63
  • 1
  • 1
  • 4

1 Answers1

0

In my case, this doesn't compile in playground.

Subclasses do not inherit their superclass initializers by default -> Apple

You need marking init() as required

I've changed it and it works now

public class Item {
    public var id: String
    public required init(str: String) {
        id = str
    }
}

public class Account: Item {
    public var actId: String
    public required init(str: String) {
        actId = "antId: \(str)"
        super.init(str: str)
    }
}

public class Keyword: Item {
    public var keywordId: String
    public required init(str: String) {
        keywordId = "keywordId: \(str)"
        super.init(str: str)
    }

}

public class Creator<T: Item> {
    public func parse(str: String) -> T {
        let result: T = T(str: str)
        return result
    }
}

var a = Creator<Account>()
var act = a.parse("Apple")
print(act.actId)

See similar question for more details

Community
  • 1
  • 1
Tikhonov Aleksandr
  • 13,945
  • 6
  • 39
  • 53