简体   繁体   中英

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:

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: Hello, world!

cannot use it! myLabel is now nil!

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. 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.

The only solution I see is to make UIL a class and then remove the value in a deinit

deinit {        
    identifiableLabelCollection.remove(labelValue)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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