gpt4 book ai didi

class - swift 类 : reference cycle

转载 作者:可可西里 更新时间:2023-11-01 00:53:31 25 4
gpt4 key购买 nike

当我运行下面的程序时,它会产生段错误。你能帮我弄清楚为什么吗?谢谢

class Animal:NSObject{
var name:String!
var age:UInt!

weak var spouse:Animal?
init(name:String,age:UInt){
self.name=name
self.age=age
}

func description() ->String{ //to become printable
return "name= \(name) and age=\(age) spouse=\(spouse)"
}
}


let dog=Animal(name:"Lucky",age:3)
let cat=Animal(name:"Branson",age:4)
dog.spouse=cat
cat.spouse=dog //It doesnt crash if I comment this line out
println(dog)

最佳答案

问题是打印中的无限递归。一旦你设置了完整的循环,打印一个动物,你打印它的配偶,打印它的配偶,打印它的配偶等等直到你用完堆栈空间并崩溃。

您需要通过打印出动物的配偶而不调用该动物的完整打印来打破这一点,如下所示:

class Animal: NSObject {
// you should avoid using implicitly unwrapped optionals
// unless you absolutely have to for a specific reason that
// doesn’t appear to apply here (so remove the !s)
var name: String
var age: UInt
weak var spouse: Animal?

init(name: String, age: UInt) {
self.name = name
self.age = age
}
}

// to make something printable, you need to conform
// to the Printable protocol
extension Animal: Printable {
// And make description is a var rather than a function
override var description: String {
let spousal_status = spouse?.name ?? "None"
return "name=\(name) and age=\(age), spouse=\(spousal_status)"
}
}


let dog = Animal(name: "Lucky", age: 3)
let cat = Animal(name: "Branson", age: 4)
dog.spouse = cat
dog.description
cat.spouse = dog
println(dog) // Prints name=Lucky and age=3, spouse=Branson

请注意,您必须使用协议(protocol)和 var 完全实现 Printable 以避免此问题,否则您将获得默认实现,但仍会遇到此问题。

顺便说一句,Swift 风格约定是在 =-> 之间、{ 等之间放置空格(实际上你如果不这样做,偶尔会导致编译问题)。 a:b 还是 a:b 还没有定论,不过我发现后者有点难读。

关于class - swift 类 : reference cycle,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27753502/

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