简体   繁体   English

有什么方法可以优化 Swift 中的结构复制?

[英]Is there any way to optimize struct copy in Swift?

I'm developing an iOS app and have the following data model:我正在开发一个 iOS 应用程序并拥有以下数据 model:

struct Student {
    var name: String?
    var age: UInt?
    var hobbies: String?
    ...
}

This model is used as the data source in one view controller, where each property value will be filled in an UITextfield instance so that the user can edit a student's information.此 model 用作一个视图 controller 中的数据源,其中每个属性值将填充到 UITextfield 实例中,以便用户可以编辑学生的信息。 Every time a user finishes typing an item, eg the name, the new value will override the old model's corresponding property.每次用户完成输入项目,例如名称,新值将覆盖旧模型的相应属性。

The problem is, since struct is a value type instead of a reference type, a new model instance is generated every time I assign a new property value to it.问题是,由于struct是值类型而不是引用类型,每次我为其分配新的属性值时,都会生成一个新的 model 实例。 There may be above 20 properties in my model and I think so many copies are quite a waste.我的 model 中可能有超过 20 个属性,我认为这么多副本是相当浪费的。 For some reasons I'm not allowed to use class .由于某些原因,我不允许使用class Is there any way to optimize this?有没有办法优化这个? Will these copies cause any performance issues?这些副本会导致任何性能问题吗?

you can create a func with mutating keyword like below您可以使用 mutating 关键字创建一个函数,如下所示

 struct Point {
      var x = 0.0
      mutating func add(_ t: Double){
        x += t
     }
   }

find more here这里找到更多

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM