gpt4 book ai didi

swift - 通过引用从值创建值/常量,然后有什么区别?

转载 作者:搜寻专家 更新时间:2023-10-31 23:00:10 24 4
gpt4 key购买 nike

我大致知道什么是引用和值,但对于某些点我对细节感到很困惑

让我们定义类 Person并从中初始化一个常量和一个变量,然后将它们传递给代码

class Person{
var ID: Int
var name: String

init (ID: Int, name: String){
self.ID = ID
self.name = name
}
}

var bornVar = Person(ID: 101, name: "me") // initialize a variable
let Tom = bornVar // pass the varialbe to a constant
var Tim = Tom // pass the variable to a variable


let bornLet = Person(ID: 102, name: "I") // initialize a constant
let Kim = bornLet // pass the constant to another constant
var Jim = Kim // pass the constant to a variable

问题:如果有人问我:Tom有什么区别? , Tim , KimJim ,我无法给出明确的答案。如果有人可以帮助我,非常感谢

最佳答案

var bornVar = Person(ID: 101, name: "me")  //  initialize a variable
let Tom = bornVar // assigning the ref of `bornVar` which is having person object reference and you can't assign the any other object to `Tom`
var Tim = Tom // assigning the reference of person object using `Tom`


let bornLet = Person(ID: 102, name: "I") // initialize a constant
let Kim = bornLet // pass the constant to another constant
var Jim = Kim // pass the constant to a variable

你在这里创建了两个对象 bornVarbornLet ,它们带有指向 Person 的 parameterzied init

Tom 是一个我们无法更改的引用属性,它指向 bornVar,这是一个 having person 对象引用

Tim 是一个指向 bornVar 的属性,您可以更改它的引用

以同样的方式

Kim 是一个我们无法更改的引用属性,它指向 bornLet,这是一个 having person 对象引用

Jim 是一个指向 bornLet 的属性,您可以更改它的引用

看这个例子

class MyObject : Equatable {
let a : Int, b : String
init(a: Int, b: String) { self.a = a; self.b = b }
}
// ...

let a = MyObject(a: 10, b: "foo")
let b = a
let c = MyObject(a: 10, b: "foo")

a == b // true; 'a' and 'b' are equal in value
a === b // true; 'a' and 'b' point to the same instance

a == c // true; 'a' and 'b' are equal in value
a === c // false; 'a' and 'c' are different instances

关于swift - 通过引用从值创建值/常量,然后有什么区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37411694/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com