【问题标题】:Create a value type property in Class iOS swift在 Class iOS swift 中创建值类型属性
【发布时间】:2021-07-14 06:29:03
【问题描述】:

我们都知道类的属性总是引用类型,但是有没有办法在类中创建一个值类型的属性呢?

类:

class Color {
    var name : String!
    init(name : String) {
        self.name = name
    }
}

利用:

    let red = Color(name: "Red")
    let yellow = red
    print("red \(red.name ?? "")")  // prints Red
    print("yellow \(yellow.name ?? "")") // prints Red


   // assigning a new value to yellow instance

    yellow.name = "Yellow"
    print("red \(red.name ?? "")")  // prints Yellow
    print("yellow \(yellow.name ?? "")") // prints Yellow

在为黄色实例赋值后,它也在改变红色实例的值。

【问题讨论】:

  • "类的属性总是引用类型" 不正确。如果你曾经在一个类中声明了IntString 属性,你就会知道,
  • 嗨@Sweeper,感谢您的快速回复,我编辑我的问题,请检查
  • 这与类是否具有引用类型或值类型属性无关。它与类Color 自身 是引用类型还是值类型有关。好吧,类总是引用类型,所以答案是否定的。

标签: ios swift class pass-by-reference pass-by-value


【解决方案1】:

类应该是引用类型,因此您可以尝试从类的实例中复制。

也许this 可以提供帮助。

【讨论】:

    【解决方案2】:
    class Color: NSObject, NSCopying {
                var name : String!
                init(name : String) {
                    self.name = name
                }
            
                func copy(with zone: NSZone? = nil) -> Any {
                    let copy = Color(name: name)
                    return copy
                }
       }
    
        let red = Color(name: "red")
        let yellow = red.copy() as! Color
        
        print("red \(red.name ?? "")")  // prints Red
        print("yellow \(yellow.name ?? "")") // prints Red
        
        // assigning a new value to yellow instance
        
         yellow.name = "Yellow"
         print("red \(red.name ?? "")")  // prints red
         print("yellow \(yellow.name ?? "")") // prints Yellow
    
    • 使您的类符合 NSCopying。这不是严格要求,但可以明确您的意图。
    • 实现方法copy(with:),实际复制的地方 发生。
    • 在您的对象上调用 copy()。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2020-01-14
      • 1970-01-01
      • 2018-05-09
      • 1970-01-01
      相关资源
      最近更新 更多