最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

swift - What is this custom initializer required for my code to work? - Stack Overflow

programmeradmin0浏览0评论

I was doing one of the tests in 100 days of Swift UI, and I tried running this code in the playground. I was wondering, what is the point of the custom initializer in lines 4-7?

Why do I need these lines in a class? Why won't the code work if I delete these lines? I still provided all of the variables needed.

class TIE {
    var name: String
    var speed: Int
    init(name: String, speed: Int) {
        self.name = name
        self.speed = speed
    }
}
let fighter = TIE(name: "wow", speed: 50)
let interceptor = TIE(name: "cool", speed: 70)

If I try to delete the custom initializer, the code breaks. Why?

I was doing one of the tests in 100 days of Swift UI, and I tried running this code in the playground. I was wondering, what is the point of the custom initializer in lines 4-7?

Why do I need these lines in a class? Why won't the code work if I delete these lines? I still provided all of the variables needed.

class TIE {
    var name: String
    var speed: Int
    init(name: String, speed: Int) {
        self.name = name
        self.speed = speed
    }
}
let fighter = TIE(name: "wow", speed: 50)
let interceptor = TIE(name: "cool", speed: 70)

If I try to delete the custom initializer, the code breaks. Why?

Share Improve this question edited Feb 6 at 19:27 TylerH 21.1k77 gold badges79 silver badges112 bronze badges asked Feb 5 at 16:38 Brody KavanaghBrody Kavanagh 391 silver badge8 bronze badges 3
  • name and speed can not be nil. So you need to have an initialization that will give them values. If you do var fighter = TIE(), nothing say that you would give really a value to name and speed afterwards. Hence the initialization needed. – Larme Commented Feb 5 at 16:43
  • Apple just forcing you to use structs. (but you will still need write public initialisers in modules for structs
发布评论

评论列表(0)

  1. 暂无评论