Что не так с моим удобным инициализатором, когда я пытаюсь вызвать self.init? - PullRequest
0 голосов
/ 27 апреля 2018

Я написал код ниже. Ошибка, которую я получаю, в конце моего удобного инициализатора, когда я пытаюсь вызвать self.init. Что не так с моей логикой или синтаксисом? Или как мне отладить это? Xcode дает ошибку: «не может вызвать со списком аргументов типа».

Спасибо за любую помощь в этом

import Foundation
import UIKit

class Item: NSObject {

    var name: String
    var valueInDollars: Int
    var serialNumber: String?
    let dateCreated: NSDate
    var stolen: Bool?

    init(name: String, valueInDollars: Int, serialNumber: String?, dateCreated: NSDate, stolen: Bool?) {
        self.name = name
        self.valueInDollars = valueInDollars
        self.serialNumber = serialNumber
        self.dateCreated = NSDate()
        self.stolen = stolen

        //below why did I have to call super.init for this custom class that inherits from NSObject? Doesn't it automatically get called anyway once the custom object is initialized since it inherits from NSObject?  It just seems like more work on my behalf which isn't fair.  it should do it automatically.  Why wouldn't it do it automatically if it inherits from NSObject?
        super.init()
    }

    convenience init(random: Bool = false) {
        if random {
            let adjectives = ["Fluffy", "Rusty", "Shiny"]
            let nouns = ["MacBook Pro", "Red Tribe Bike", "Vegan Pizzas"]
            //take a variable that's random; the highest value for this random number will be the number of ojbects in the adjectives array
            var idx = arc4random_uniform(UInt32(adjectives.count))
            //now use this random variable and let it be the index of the adjectives array...so basically it'll be a random object from the adjectives array
            let randomAdjective = adjectives[Int(idx)]

            //AWESOME!! Now that the random adjective is stored in the randomAdjective constant, let's re-use the idx variable...Ayyyyeeeee re-use!

            //we'll re-use it by doing the same process or close to the same process for nouns
            idx = arc4random_uniform(UInt32(nouns.count))
            let randomNoun = nouns[Int(idx)]

            //now let's concatenate these two clever words, shall we!!
            let randomName = "\(randomAdjective) \(randomNoun)"

            //yayyy we're programmmminnngg!

            //now let's ....whad de fuk....
            let randomValue = Int(arc4random_uniform(100))
            let randomSerialNumber = NSUUID().uuidString.components(separatedBy: "-").first!

            let betterNotBeStolen: Bool = false

            self.init(name: randomName, valueInDollars: randomValue, serialNumber: randomSerialNumber, stolen: betterNotBeStolen)


        }
    }
}

1 Ответ

0 голосов
/ 27 апреля 2018

Вы получили ошибку

"Невозможно вызвать Item.init со списком аргументов типа" (имя: String, valueInDollars: Int, serialNumber: String, украденный: Bool) '"

потому что вы пропустили параметр dateCreated в self.init (params ...).

Так что вам нужно заменить эту строку

self.init(name: randomName, valueInDollars: randomValue, serialNumber: randomSerialNumber, stolen: betterNotBeStolen)

с этим

self.init(name: randomName, valueInDollars: randomValue, serialNumber: randomSerialNumber,dateCreated: NSDate(), stolen: betterNotBeStolen)

Следующая ошибка, которую вы увидите после:

Self.init не вызывается на всех путях перед возвратом из инициализатора

Так что вам нужно добавить оператор else, потому что инициализатор не знает, что делать, когда случайный параметр имеет значение false.

convenience init(random: Bool = false) {
        if random {
            let adjectives = ["Fluffy", "Rusty", "Shiny"]
            let nouns = ["MacBook Pro", "Red Tribe Bike", "Vegan Pizzas"]
            //take a variable that's random; the highest value for this random number will be the number of ojbects in the adjectives array
            var idx = arc4random_uniform(UInt32(adjectives.count))
            //now use this random variable and let it be the index of the adjectives array...so basically it'll be a random object from the adjectives array
            let randomAdjective = adjectives[Int(idx)]

            //AWESOME!! Now that the random adjective is stored in the randomAdjective constant, let's re-use the idx variable...Ayyyyeeeee re-use!

            //we'll re-use it by doing the same process or close to the same process for nouns
            idx = arc4random_uniform(UInt32(nouns.count))
            let randomNoun = nouns[Int(idx)]

            //now let's concatenate these two clever words, shall we!!
            let randomName = "\(randomAdjective) \(randomNoun)"

            //yayyy we're programmmminnngg!

            //now let's ....whad de fuk....
            let randomValue = Int(arc4random_uniform(100))
            let randomSerialNumber = NSUUID().uuidString.components(separatedBy: "-").first!

            let betterNotBeStolen: Bool = false

            self.init(name: randomName, valueInDollars: randomValue, serialNumber: randomSerialNumber,dateCreated: NSDate(), stolen: betterNotBeStolen)


        } else {

           self.init(name: "SomeName", valueInDollars: 3, serialNumber: "123", dateCreated: NSDate(), stolen: true)
        }
    }
...