ios - 元组属性的自定义 setter (Swift)

标签 ios iphone cocoa cocoa-touch swift

我的类中有一个计算属性,它是一个可选的元组:

var contents: (Int, Bool)?

我想编写自定义 setter ,但不知道如何单独引用元组组件。有谁知道?我尝试了以下但它不起作用:

var contents: (Int colorNumber, Bool selected)? {
    // getter & setter here...
}

最佳答案

使用let分解元组

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

关于ios - 元组属性的自定义 setter (Swift),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25917088/

相关文章:

iphone - 在 NSObject 上使用非正式协议(protocol)或使用可选方法的协议(protocol)有什么区别?

ios - 使用 SpriteKit throw 物体

iphone - 检查是否已实现可选协议(protocol)方法

ios - iOS 上的 Safari 是否拒绝下载 `application/octet-stream` 内容?

iphone - willAnimateToRotation 没有被调用

objective-c - 了解 NSHTTPCookieStorage 的内部结构

ios - 如何在 iphone 2.0 中以编程方式发送短信

macos - 拦截 os x 中的全局音频输出?

objective-c - 异构 NSTreeController

iphone - 使用 NSOperationQueue 作为 View Controller 实例变量