如何在swift子类中初始化未拥有的存储属性?

时间:2015-05-04 18:59:50

标签: swift

我有一个UICollectionViewController的自定义swift子类,它有属性unowned var mainController。我无法弄清楚如何初始化此属性。如果我在调用super.init之前尝试初始化它,Xcode会抱怨在super.init之前使用'self'。如果我之后尝试初始化它,Xcode会抱怨属性'self.mainController'没有在super.init调用时初始化。

一般情况下,是否可以在swift中将无主变量作为子类的属性?

class CustomCollection: UICollectionViewController {

    unowned var mainController: MainController

    convenience init(mainController: MainController) {
        var collectionViewLayout = UICollectionViewLayout()
        self.mainController = mainController
        self.init(collectionViewLayout: collectionViewLayout)
    }

    override init(collectionViewLayout layout: UICollectionViewLayout) {
        super.init(collectionViewLayout: layout)
    }
    ...
}

2 个答案:

答案 0 :(得分:1)

这似乎适用于我的游乐场文件......

class Fruit {

    var taste:String

    init(){
        taste = "sweet"
    }

    deinit{
        println("Deinitializing Fruit")
    }
}

class Apple:Fruit{

    let color: UIColor
    unowned var meme:NSObject

    override init () {
        color = UIColor.greenColor()
        meme = "The Big Apple"
        super.init()
    }

    convenience init ( newMemeValue: AnyObject) {
        self.init()
        self.meme = newMemeValue as! NSObject
    }
}

var redApple:Apple?
redApple = Apple(newMemeValue: "A Bigger Bite")
println("\(redApple)")
var color = redApple!.color

答案 1 :(得分:0)

It doesn't feel like the best solution, but this is what I ended up doing:

class CustomCollection: UICollectionViewController {

    unowned var mainController = MainController()

    convenience init(mainController: MainController) {
        var collectionViewLayout = UICollectionViewLayout()
        self.init(collectionViewLayout: collectionViewLayout)
        self.mainController = mainController
    }

    override init(collectionViewLayout layout: UICollectionViewLayout) {
        super.init(collectionViewLayout: layout)
    }

and in MainController:

class MainController: UIViewController {

    lazy var customCollection: CustomCollection = CustomCollection(mainController: self)

    init () {
        ...
    }
    ...
}

@Shoaib is right that mainController needs to be initialized in all init functions, so I just ended up initializing it at the top and setting it again after calling super.init().