简体   繁体   English

如何在 Swift 的一般用例中访问类型的 didSet?

[英]How can I access to didSet of a Type in general use case in Swift?

I am working on a custom type called UIL stand for Unique Identifiable Label , here is my code:我正在研究一种称为UIL的自定义类型,代表Unique Identifiable Label ,这是我的代码:

struct UIL: Equatable {

    init?(labelValue: String) {

        if checkLabelAvailability(for: labelValue) {
            
            identifiableLabelCollection.insert(labelValue)
            self.labelValue = labelValue
            
        }
        else {
            return nil
        }
        
    }

    var labelValue: String
    
    static func ==(lhs: UIL, rhs: UIL) -> Bool {
        return lhs.labelValue == rhs.labelValue
    }
    
}

var identifiableLabelCollection: Set<String> = Set<String>()


func checkLabelAvailability(for label: String) -> Bool {
    return !identifiableLabelCollection.contains(label)
}

And this my use case:这是我的用例:

var myLabel: UIL? = UIL(labelValue: "Hello, world")

if let unwrappedValue: UIL = myLabel {
    print("myLabel:", unwrappedValue.labelValue)
}

myLabel = UIL(labelValue: "Hello, world!")

if let unwrappedValue: UIL = myLabel {
    print("myLabel:", unwrappedValue.labelValue)
}


myLabel = UIL(labelValue: "Hello, world")

if let unwrappedValue: UIL = myLabel {
    print("myLabel:", unwrappedValue.labelValue)
}
else {
    print("cannot use it! myLabel is now nil!")
}

And this the results:这是结果:

myLabel: Hello, world myLabel:你好,世界

myLabel: Hello, world! myLabel:你好,世界!

cannot use it!不能用! myLabel is now nil! myLabel 现在为零!

The issue is here that I should remove the string of replaced UIL from collection to make it available for next access, I can put codes in didSet of myLabel for this goal, but I want make this happen undercover and make developer free to thinking about it.问题就在这里,我应该从集合中删除替换的 UIL 字符串以使其可用于下一次访问,我可以将代码放入myLabel的 didSet 中以实现此目标,但我想让这发生在秘密中,让开发人员可以自由地考虑它. I want access the didSet of type UIL and then I remove that label string from collection if the oldValue and newValue are deferent than each other.我想访问 UIL 类型的 didSet ,然后如果 oldValue 和 newValue 彼此不同,我从集合中删除 label 字符串。

The only solution I see is to make UIL a class and then remove the value in a deinit我看到的唯一解决方案是使UIL成为 class 然后删除deinit中的值

deinit {        
    identifiableLabelCollection.remove(labelValue)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM