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