[英]Access static variables in struct in class extension, by key using strings
The goal is to access a static variable in a struct in a class extension: 目标是访问类扩展中的结构中的静态变量:
extension UIColor {
struct MyColors {
static var happy: UIColor {
return UIColor(hexString: "#FFB100")!
}
static var superHappy: UIColor {
return UIColor(hexString: "#FFB101")!
}
static func withName(_ name: String = "") -> UIColor? {
return UIColor.value(forKey: name) as? UIColor
}
}
}
// Produces error "this class is not key value coding-compliant for the key happy."
let myHappyColor = UIColor.MyColors.withName("happy")
Can we do something like that in PHP ? 我们可以在PHP中做类似的事吗?
<?php
$prop = 'Name';
echo $obj->$prop;
You can use either static variables or enumeration: 您可以使用静态变量或枚举:
extension UIColor {
// MARK: - Static
static let myColor = UIColor(/* setup */)
or 要么
enum MyColors {
case red
var color: UIColor {
switch self {
case .red:
return .red
}
}
You can create Color set in xcassets
catalog with some name. 您可以使用某个名称在
xcassets
目录中创建颜色集 。 Then, you can initalize color from this set using designed initalizer 然后,您可以使用设计的初始化器从该组中初始化颜色
UIColor(named: "Name")
Anyway, in Swift you should avoid initalizing objects with identifiers (I'm not talking about named sets but about your current approach). 无论如何,在Swift中你应该避免使用标识符初始化对象(我不是在谈论命名集,而是关于你当前的方法)。 Swift is safe-type language.
Swift是安全型语言。 Try to obey rules of safe-type language.
尽量遵守安全型语言的规则。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.