簡體   English   中英

在 Class iOS swift 中創建值類型屬性

[英]Create a value type property in Class iOS swift

我們都知道 class 的屬性總是引用類型,但是有沒有辦法在 class 中創建一個值類型的屬性呢?

Class:

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

在將值分配給黃色實例后,它也會更改值紅色實例。

class 是引用類型,因此您可以嘗試從 class 的實例復制。

也許會有所幫助。

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
  • 使您的 class 符合 NSCopying。 這不是嚴格要求的,但它使您的意圖清晰。
  • 實現方法 copy(with:),實際復制發生的地方。
  • 在 object 上調用 copy()。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM