gpt4 book ai didi

ios - Swift 如何获取对象的 "pass by value"

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

我是 Swift 的新手。我创建了一个类(例如):

class Fraction{
var a: Int
init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
}

我还在其他类函数中构建了一个:

class func A_plusplus(f:Fraction){
f.a++
}

然后在执行类中我写:

var object = Fraction(a:10)
print("before run func = " + object.toString())
XXXclass.A_plusplus(object)
print("after ran func =" + object.toString() )

所以控制台输出是

before run func = 10; after ran func =11

问题是我怎样才能发送“对象”的副本以保持它的值等于 10

如果函数总是按引用传递,为什么我们还需要关键字:"inout"

A_plusplus(&object)//[if I make the parameter to be a inout parameter]A_plusplus(object)

有什么区别

Universally, I don't want to use struct. Although this will solve my problem exactly, I do pass-by-value rarely.So I don't want program's copying processes slow my user's phone down :(

And It seems conforming the NSCopying protocol is a good option.But I don't know how to implement the function: func copyWithZone(zone:
NSZone)-> AnyObject?
correctly

最佳答案

如果你的类是 NSObject 的子类,最好使用 NSCopying

class Fraction:NSObject,NSCopying{
var a:Int
var b:NSString?
required init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
func copyWithZone(zone: NSZone) -> AnyObject {
let theCopy=self.dynamicType.init(a: self.a)
theCopy.b = self.b?.copy() as? NSString
return theCopy
}
}
class XXXclass{
class func A_plusplus(f:Fraction){
f.a++
f.b = "after"
}

var object = Fraction(a:10)
object.b = "before"
print("before run func = " + object.toString())
print(object.b!) //“Before”

XXXclass.A_plusplus(object.copy() as! Fraction)
print("after ran func =" + object.toString() )
print(object.b!)//“Before”

如果只是一个普通的swift类,就得创建一个copy方法

class Fraction{
var a: Int
init(a:Int){
self.a = a
}
func toString() -> String{
return "\(self.a)"
}
func copy()->Fraction{
return Fraction(a: self.a)
}
}
class XXXclass{
class func A_plusplus(f:Fraction){
f.a++
}
}
var object = Fraction(a:10)
print("before run func = " + object.toString())
XXXclass.A_plusplus(object.copy())
print("after ran func =" + object.toString() )

要说清楚,你要知道swift中主要有两种类型

  1. 引用类型。比如类实例,函数类型
  2. 值类型,如结构等(不是类实例或函数类型)

如果你传入一个引用类型,你传入的是引用的副本,它仍然指向原始对象。

如果你传入一个Copy类型,你传入的是值的副本,所以它与原始值无关

说说inout,如果你用它,它会传入相同的对象或值。它对值类型有影响

func add(inout input:Int){
input++
}

var a = 10
print(a)//10
add(&a)
print(a)//11

关于ios - Swift 如何获取对象的 "pass by value",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33164532/

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