关于Swift中实现Lazy initialize的方式

在oc中我们通过

-(CardMatchingGame *)game
{
    if(!_game) _game=[[CardMatchingGame alloc] initWithCardCount:[self.cardButtons count] usingDeck:[self createDeck]];
    return _game;
}

方式来实现Lazy initialize,即在对象第一次调用的时候才进行实例化,按照上面这种方式,我尝试在Swift中用如下代码实现

    var gameModel: CardMatchingGame?{
        if !self.gameModel{
            return CardMatchingGame(cardCount: cardButtons.count, usingDeck: playDec)
        }else{
            return self.gameModel
        }
    }

编译没有问题,但是运行中会进入死循环,在self.gameModel上,会再次调用gameModel的get方法,循环往复,直到程序崩溃。

那就用lazy关键字吧,但是。。。。

居然说变量找不到,这不坑爹么。

lazy关键字去掉还是这个错, 我觉得应该不是lazy的问题,肯定是在声明过程中哪个细节疏忽了,现在还无法解决。

现在先用别的方法替代这个继续下去了,等找到解决方法或者出错的地方后再上来修改。~~~

刚看到了这个方法,可能可以,等会去试试,但是这样的话就感觉比较麻烦,没有OC中的方法那么简单

Your property has a getter, so is a 'computed property' as a result it does not have a setter (unless you supply one yourself). I suspect what you want to do is back your computed property with a private stored property:

private var _pageControl: UIPageControl?

var pageControl: UIPageControl {
get{
    // if the private backing variable doesn't exist, create it
    if (_pageControl == nil) {
        _pageControl = UIPageControl()
        // ...
    }
    return _pageControl
}
}

 这种方法还是比较靠谱了,可行!

原文地址:https://www.cnblogs.com/scaptain/p/3875193.html