在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)
}
}
答案 0 :(得分:5)
您无法在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]