枚举中的一段代码(一副牌,它们应该有一个 true 或 false 的“状态”)
enum Card:Int
{
case zero = 0, one, two, three, four, five, six, seven, eight, nine
init()
{
self = .zero
}
init?(digit: Int)
{
switch digit
{
case 0: self = .zero case 1: self = .one case 2: self = .two
case 3: self = .three case 4: self = .four case 5: self = .five
case 6: self = .six case 7: self = .seven case 8: self = .eight
case 9: self = .nine
default:
return nil
}
}
var status
{
get
{
switch self
{
case .zero: return false
case .one: return false
case .two: return false
case .three: return false
case .four: return false
case .five: return false
case .six: return false
case .seven: return false
case .eight: return false
case .nine: return false
}
}
}
我试图在这里创建一个变异函数,当函数运行时将其值更改为 true
mutating func swap() {
switch status {
case TRUE:
self = false
case false:
self = TRUE
}
}
}
上面的代码不起作用。
最佳答案
创建一个名为 Cards 的结构,它具有两个存储属性,其中一个为 Card enum 类型,另一个为 Bool 类型来跟踪状态在这里您可以声明一个函数 swap() 来更改状态值:
struct Cards {
let card:Card? //This property stores an instance of Card enum
var status = true
mutating func swap()
{
self.status = !self.status
}
init(cardDigit: Int)
{
self.card = Card(digit: cardDigit)
}
init()
{
self.card = Card()
}
}
var aCard :Cards = Cards(cardDigit: 2)
aCard.status // returns true
aCard.swap()
aCard.status //returns false
您可以从枚举中删除状态计算属性,因为我们可以从结构中访问它。
关于swift - 如何使枚举中的变异函数具有不同的返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31445899/