Chris Mikkelsen Chris Mikkelsen - 3 months ago 21
Swift Question

Return from initializer without initializing all stored properties Error in a Regex class

I get this error message that says "Return from initializer without initializing all stored properties"

class Regex {
let internalExpression: NSRegularExpression
let pattern: String

init(_ pattern: String) {
self.pattern = pattern
var error: NSError?

do {
self.internalExpression = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
} catch {
print(error)
}
}//Error Message Goes Here

func test(input: String) -> Bool {
let matches = self.internalExpression.matchesInString(input, options: [], range:NSMakeRange(0, input.characters.count))
return matches.count > 0
}


}

Answer

If the pattern is invalid then NSRegularExpression(pattern: pattern, ...) fails and throws an error, so that self.internalExpression is not initialized. You cannot create an object without initializing all its properties.

So you have to decide how to handle that situation. One option would be to make the initializer failable:

init?(_ pattern: String) {
    self.pattern = pattern
    do {
        self.internalExpression = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
    } catch let error as NSError {
        print(error.localizedDescription)
        return nil
    }
}

Then the caller has to check if the initialization was successful:

if let regex = Regex("...") {
    // ...
} else {
    print("could not create Regex")
}

You can also make the initializer throwing and forward the error:

init(_ pattern: String) throws {
    self.pattern = pattern
    self.internalExpression = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
}

Then the caller has to catch the error:

do {
    let regex = try Regex("...")
    // ...
} catch let error as NSError {
    print("could not create regex:", error.localizedDescription)
}

Finally, if an invalid pattern is considered as a programming error in your program, then abort the execution for an invalid pattern:

init(_ pattern: String) {
    self.pattern = pattern
    do {
        self.internalExpression = try NSRegularExpression(pattern: pattern, options: .CaseInsensitive)
    } catch let error as NSError {
        fatalError("could not create regex: " + error.localizedDescription)
    }
}
Comments