Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Custom setter for tuple property (Swift)

I have a computed property in my class that is an optional tuple:

var contents: (Int, Bool)?

I want to write a custom setter but don't know how to reference the tuple components individually. Anyone knows? I've tried the following but it doesn't work:

var contents: (Int colorNumber, Bool selected)? {
    // getter & setter here...
}
like image 280
MLQ Avatar asked Sep 17 '25 21:09

MLQ


1 Answers

use let to decompose a tuple

var iVal:Int?
var bVal:Bool?

var contents:(Int, Bool)? {
    get {
        if iVal != nil && bVal != nil {
            return (iVal!, bVal!)
        }
        else {
            return nil
        }
    }
    set {
        if newValue != nil {
            let (i, b) = newValue!    // decompose the tuple
            iVal = i
            bVal = b
        }
        else {
            iVal = nil
            bVal = nil
        }
    }
}
like image 67
David Berry Avatar answered Sep 19 '25 13:09

David Berry