问题描述
我有一个看起来像这样的类,我需要设置T恤(例如白色)的默认颜色,当用户从数组(例如。red)创建一个新T恤,其属性颜色仅填充选定的(红色)颜色。我该怎么办??
class Tshirt {
var color: [String]
var size: Int
var price: Int
init(color: [String],size: Int,price: Int) {
self.color = color
self.size = size
self.price = price
}
很抱歉,这听起来很愚蠢,但我是面向对象编程的新手。
解决方法
为什么要在选择颜色时创建新的T恤,而不仅仅是更改Tshits颜色的值?如果可以选择几种颜色,则可以为颜色创建一个枚举,并在将对象创建为白色时将默认颜色设置为默认颜色。
class Tshirt {
var color: Color = .white
var size: Int
var price: Int
enum Color {
case white,black,blue,green,red //etc...
}
init(size: Int,price: Int) {
self.size = size
self.price = price
}
}
let yourShirt = Tshirt(size: 8,price: 8)
和yourShirt
的颜色属性为.white
。然后,当用户选择所需的颜色时,只需更改衬衫的颜色即可。
yourShirt.color = .red
print(yourShirt.color)
//Prints "red"
如果您确实想用用户定义的颜色实例化一个新对象,或者提供使用指定颜色实例化Tshirt对象的选项,则可以将初始化程序更改为具有默认值的选项:
init(size: Int,price: Int,color: Color = .white) {
self.size = size
self.price = price
self.color = color
}