我有一个名为 FoodItem 的结构,它有 3 个属性
struct FoodItem {
foodName: String
foodAmount: Double
amountMetric: String
}
当用户向应用添加食物时,他/她分两步完成。第一步只需要这三件事。然而,第 2 步需要一些额外的东西...比如 amountOfSteps: Int, stepTitle: String...
protocol CookingInstructions {
var amountOfSteps: Int { get }
var stepTitle: String { get }
}
是否可以将第 2 步部分添加为协议(protocol),但在第 1 步完成后添加协议(protocol)?所以在第 2 步之前,结构不知道协议(protocol),但随后添加了协议(protocol)?
最后我只希望第 1 步只需要 3 个东西,然后第 2 步需要不同的几个东西。
最佳答案
不,不可能在运行时更改结构的一致性。
也许您可以为第 2 步添加另一个结构,然后添加一个包含 FoodItem 和 CookingInstructions 的结构?
像这样:
struct FoodItem {
foodName: String
foodAmount: Double
amountMetric: String
}
struct CookingInstructions {
var amountOfSteps: Int
var stepTitle: String
}
struct Composite {
var step1: FoodItem
var step2: CookingInstructions?
}
关于swift - 满足条件后向结构添加协议(protocol) Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43880527/