0

I'm facing a kinda stupid problem trying to code my first swift classes. I'm writing an init method for my class, and I want to (raise an exception)/(do something in some way) to report an error when the parameters that have been passed to the initializer are wrong. My class is simple as that:

class Phrase: NSObject {
    let name : String
    let voices : Array<Voice>
    init(name: String, voices: Array<Voice>){
        if (name == "" || voices.count == 0){
          //do something!
        }
        self.name = name
        self.voices = voices
    }
}

Thank you in advance!

tmnd91
  • 449
  • 1
  • 6
  • 23
  • possible duplicate of [Proper way to handle a fail to init](http://stackoverflow.com/questions/24295740/proper-way-to-handle-a-fail-to-init) – Martin R Sep 02 '14 at 07:39
  • possible duplicate af [How should I handle parameter validation Swift](http://stackoverflow.com/questions/24250363/how-should-i-handle-parameter-validation-swift) – Martin R Sep 02 '14 at 07:39

2 Answers2

2

Don't use init for this - use a class function that can return nil if the parameters are invalid:

class Phrase: NSObject {
    var name : String
    var voices : Array<Voice>

    init() {
        self.name = "something safe"
        self.voices = [Voice]()
    }

    class func phraseOrNil(name: String, voices: Array<Voice>) -> Phrase? {
        if (name == "" || voices.count == 0){
            let p = Phrase()
            p.name = name
            p.voices = voices
            return p
        } else {
            return nil
        }
    }
}

...then you can fail gracefully (or throw an exception if you really want to, as shown above) in the main code. See also How should I handle parameter validation Swift, though that doesn't deal with your exception question.

Note also that I changed your let declarations to var as we need to change their values.

Community
  • 1
  • 1
Grimxn
  • 22,115
  • 10
  • 72
  • 85
  • 1
    On top of that I would suggest using NSError, to provide additional info to the user of your code. – Atomix Sep 02 '14 at 07:43
0

Here's my favorite option:

fatalError("This is an overreaction.")

You can also do:

NSException(name: "Invalid Arguments", reason: "Arguments are empty", userInfo: nil).raise()

More on this over here

Community
  • 1
  • 1
michaelsnowden
  • 6,031
  • 2
  • 38
  • 83
  • The first one is so BRUTAL ;) The second one is an exception but I cannot manage it in Swift, and because this wants to be a full swift project it seems kinda useless! I'll go for the first one! Thank you very much! – tmnd91 Sep 02 '14 at 07:38