是否可以从结构复制期间排除某些属性(如类类型)复制?

时间:2019-07-07 20:06:19

标签: swift

我有以下包含类的结构。

import Foundation

func generateRichText(body: String?) -> NSMutableAttributedString? {
    if body == nil {
        return nil
    }

    // TODO: Some complex logic to decorate body string will be added soon...

    let myAttrString = NSMutableAttributedString(string: body!)
    return myAttrString
}

struct Note {
    var body: String?

    // Technique described in https://stackoverflow.com/a/25073176/72437
    var bodyAsRichText: NSMutableAttributedString? {
        mutating get {
            if (cachedBodyAsRichText == nil) {
                cachedBodyAsRichText = generateRichText(body: body)
            }
            return cachedBodyAsRichText
        }
    }

    // TODO: This is a class. I don't want it to be copied over during struct copy.
    // If it is copied during struct copy, both struct will be sharing the same
    // class instance.
    private var cachedBodyAsRichText: NSMutableAttributedString?
}

var note = Note()
note.body = "hello"
print("note.bodyAsRichText = \(Unmanaged.passUnretained(note.bodyAsRichText!).toOpaque())")

var note_copy = note
print("note_copy.bodyAsRichText = \(Unmanaged.passUnretained(note_copy.bodyAsRichText!).toOpaque())")

对于上面的代码,输出将为

note.bodyAsRichText = 0x000055c035cfce70
note_copy.bodyAsRichText = 0x000055c035cfce70

我想要的输出是什么,不同的结构实例,应该有自己的类实例(cachedBodyAsRichText

因此,有没有办法在结构复制期间排除cachedBodyAsRichText被复制?

1 个答案:

答案 0 :(得分:1)

您的解决方案不完整。这是一个完整正确的解决方案。

struct Note {
    var body: String = "" {
        didSet {
            cachedBodyAsRichText = nil
        }
    }

    var bodyAsRichText: NSAttributedString {
        mutating get {
            if (cachedBodyAsRichText == nil) {
                cachedBodyAsRichText = generateRichText(body: body)
            }
            return cachedBodyAsRichText!.copy() as! NSAttributedString
        }
    }

    private var cachedBodyAsRichText: NSAttributedString? = nil
}

每次修改正文时,您都需要清除缓存。完成此操作后,对象是否在结构之间共享就没有关系了。