Swift 弱惰性变量不会编译

标签 swift cocoa lazy-evaluation weak-references

为了演示这个问题,我做了一个普通的 Cocoa 项目。这是 AppDelegate.swift:

import Cocoa

@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate {

    weak lazy var isGood : NSNumber? = {
        return true
    }()

    func doSomething() {
        let result = isGood!
    }

    func applicationDidFinishLaunching(aNotification: NSNotification) {
        // Insert code here to initialize your application
    }

    func applicationWillTerminate(aNotification: NSNotification) {
        // Insert code here to tear down your application
    }
}

Xcode 给出了这个:

unkown :0: error: cannot convert return expression of type 'NSNumber?' (aka 'Optional') to return type 'NSNumber?'

unkown :0: cannot assign value of type 'NSNumber?' to type 'NSNumber??'

unkown :0: cannot assign value of type 'NSNumber?' to type 'NSNumber??'

在我的实际项目中,它是 MyCustomClass 的另一个对象(而不是 NSNumber)。除了类型是 MyCustomClass 之外,错误是相同的。

如果我从声明中删除 weaklazy,一切都很好。但我想避免引用计数为 +1,因为 MyCustomClass 是一个 NSViewController,它肯定会一直存在。

知道如何使用弱惰性变量吗?

最佳答案

软弱和懒惰混在一起不好。错误消息对于解释正在发生的事情完全没有用,但本质上 lazyweak 是相互矛盾的:

  • lazy 告诉 Swift,您不想在第一次访问变量之前创建它,但是一旦创建了它,您希望无限期地保留它以供将来引用,而
  • weak 告诉 Swift 你不希望你的变量成为阻止你的变量被释放的最后一个链接,这违背了 lazy 变量。

你可以通过模拟 lazy 来解决这个问题,就像这样:

class Foo {

    weak var isGoodCache : NSNumber?

    private var makeIsGood : NSNumber {
        isGoodCache = true
        return isGoodCache!
    }

    var isGood:NSNumber? {
        return isGoodCache ?? makeIsGood
    }
}

关于Swift 弱惰性变量不会编译,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38171933/

相关文章:

ios - 如何异步绘制InRect

cocoa-touch - Wifi与核心资料库样式同步

c# - C# 中的后期评估?

c++ - 具有表达式模板的多维数组模板类

ios - 将 subview 定位在圆形 View 的边缘

arrays - 当所有类型都正确定义时,为什么 Swift 的 reduce 函数会抛出 'Type of expression ambigious without more context' 错误?

swift - 为什么我收到错误 : Type 'Any' has no subscript members when trying to use ELCimagepickercontroller

cocoa - 滑动 CCMenu

macos - 绘制到透明覆盖 subview NSView

clojure - 如何在 Clojure 中将惰性序列转换为非惰性序列