Juanma M Juanma M - 6 months ago 10
Swift Question

My app closes when "return nil", how can I fix it? | Swift

I want to use regular expressions but I can`t

class Regex {
let pattern: String
let internalExpression: NSRegularExpression

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

print(error)
}
return nil

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

Answer

Your code doesn't compile (constant 'self.pattern' used before being initialized) and you probably don't want to return nil even on success

class Regex {
    let pattern: String
    let internalExpression: NSRegularExpression

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

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