Swift:根据设置的另一个属性,是否需要属性?

时间:2017-12-06 05:48:10

标签: ios swift uiviewcontroller

我想重新使用一个viewcontroller但稍微重新定位,我想知道是否有一种结构化方法需要根据另一个属性设置一些属性。

For example assume that the viewcontroller has the following properties - var displayMode: DisplayMode // see below - var id: Int - var description: String - var name: String

如果我们处于quickView模式,那么我希望设置ID和Description值。 否则,如果我们处于defaultView模式,我希望设置Name属性。

enum DisplayMode {
    case quickView
    case defaultView
}

显然我可以设置它们并期望它们被设置但是我想知道是否存在一种类似Swift的强制方式,比如将属性嵌套在DisplayMode类型中?

2 个答案:

答案 0 :(得分:2)

考虑将associated values用于enum个案例,例如:

enum DisplayMode {
    case quickview(id: Int, description: String)
    case defaultview(name: String)
}

这会强制用户在声明DisplayMode变量时提供有效的关联值:

var mode = DisplayMode.quickView(id: 11, description: "Prosecco")

要恢复关联的值,请将它们绑定到switch

中的变量
switch mode {
case let .quickView(id, description):
    // do something with id and description
case let .defaultview(name):
    // do something with name
}

通过使用关联值,您不必为iddescriptionname声明独立属性(即对象变量)。

答案 1 :(得分:1)

我觉得这样的事情就是你想要的:

var displayMode: DisplayMode {
    didSet {
        if displayMode == quickview {
            // self.id = whatever
            // do whatever else you want
        }
        else if displayMode == default {
            // self.id = whatever
            // do whatever else you want
        }
    }
}

var id: Int
var description: String
var name: String

(编辑:当然,它会有点不同,因为你正在使用枚举,但你得到了它的要点。)

另一种选择可能是使用KVO。 https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/KeyValueObserving/KeyValueObserving.html

相关问题