swift - 满足条件后向结构添加协议(protocol) Swift 3

标签 swift

我有一个名为 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/

相关文章:

arrays - try catch 加速度计轴

swift - 一元运算符 '!' 不能应用于类型 '()' 的操作数

ios - EKEventStore 请求访问不起作用

swift - 如何在 Swift 4 中安全地解包字典值?

ios - Swift - 捕获闭包 - Apple 的快速编程指南片段

swift - 程序流程问题

iphone - MKMapViewDelegate + JSON Alamofire

ios - 从 UITableView 中删除项目后索引超出范围

ios - 突然得到 do/catch 错误

swift - 获取空指针异常尝试在 OSX 上使用 swift 从当前事件窗口获取边界