gpt4 book ai didi

swift - 从对象中读取静态属性

转载 作者:搜寻专家 更新时间:2023-10-31 22:22:37 25 4
gpt4 key购买 nike

我有一个带有静态属性的类,我想为特定对象访问它。代码如下:

import UIKit

protocol Theme {
static var name: String { get }

func getBackgroundColor() -> UIColor
}

class DefaultTheme: Theme {
static var name = "Default theme"

func getBackgroundColor() -> UIColor {
return UIColor.blackColor()
}
}

var currentTheme: Theme = DefaultTheme()
println(currentTheme.name) //Error: 'Theme' does not have a member named 'name'

我无法通过 DefaultTheme.name 访问主题名称,因为 currentTheme 可能是不同主题类的实例,但我确实需要知道它的名称。我怎样才能访问这个静态变量?

我正在使用 Xcode 6.3.1(带有 Swift 1.2)

最佳答案

您遇到了 Swift 1.2 中一个不起眼但非常有趣的错误。 Swift 长期以来一直存在与协议(protocol)所需的静态变量相关的错误,而这似乎是另一回事。

显然,这里的问题是您试图混合和匹配基于协议(protocol)的特征和基于类的特征。假设你这样说:

var currentTheme = DefaultTheme()

然后 currentTheme 将被键入为 DefaultTheme - 一个类的实例。这意味着您可以通过传递该实例的 dynamicType 从该实例访问类成员:

println(currentTheme.dynamicType.name) // "Default theme"

但是您不能在您的 代码中这样做,因为您已经将 currentTheme 作为主题 - 一个协议(protocol):

var currentTheme : Theme = DefaultTheme()

这对协议(protocol)强加的 name 属性的概念造成了奇怪的影响,因此您根本无法访问 name 属性。

如果 Theme 是 DefaultTheme 的父类(super class),您就不会遇到这个问题。在那种情况下,您可以使用一个类属性(它必须是一个计算属性)并且它可以多态地工作。在 Swift 1.2 中,这可能是您最好的选择:

class Theme {
class var name : String { return "Theme" }
}
class DefaultTheme: Theme {
override class var name : String { return "Default theme" }
}
var currentTheme : Theme = DefaultTheme()
println(currentTheme.dynamicType.name) // "Default theme"

另一方面,当您升级到 Swift 2 时,您会发现错误已修复,因此即使使用协议(protocol),print(currentTheme.dynamicType.name) 也能完美运行:

protocol Theme {
static var name : String { get }
}
class DefaultTheme: Theme {
static var name = "Default theme"
}
var currentTheme : Theme = DefaultTheme()
print(currentTheme.dynamicType.name) // "Default theme"

关于swift - 从对象中读取静态属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30823564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com