在 Javascript 或 jQuery 中,可以像这样连接字符串和变量名:
var id = 5;
$("#wrapper_" + id).hide();
我想用 Swift 达到同样的效果,比如:
func eventColors (colorID: Int, view: UIView) {
view.backgroundColor = Constants.Color.eventColor + colorID // Incorrect
}
常量结构:
struct Constants {
struct Color {
static let eventColor1: UIColor = UIColor(red:0.06, green:0.44, blue:0.64, alpha:1)
static let eventColor2: UIColor = UIColor(red:0.86, green:0.30, blue:0.99, alpha:1)
static let eventColor3: UIColor = UIColor(red:0.50, green:0.44, blue:0.64, alpha:1)
}
}
最佳答案
您不能在 Swift 中即时创建变量名。您应该考虑在此处使用数组。使 eventColor
成为颜色数组:
struct Constants {
struct Color {
static let eventColor: [UIColor] = [
UIColor(red:0.06, green:0.44, blue:0.64, alpha:1),
UIColor(red:0.86, green:0.30, blue:0.99, alpha:1),
UIColor(red:0.50, green:0.44, blue:0.64, alpha:1)
]
}
}
然后像这样选择你的颜色:
view.backgroundColor = Constants.Color.eventColor[colorID - 1]
关于ios - 是否可以在 Swift 中连接变量名和字符串/整数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49816899/