Avoid force-unwrapped optionals
ayoy opened this issue · comments
Dominik Kapusta commented
Apologies if that's stating the obvious, and it probably is, but you asked for it :)
The alternative that wouldn't crash when given rubbish input is to use compactMap
that takes a closure returning an optional, and filters nil values:
return input.compactMap { Int($0) }
Jerzy Chałupski commented
OK, but in this case I'm parsing the input from file, so crashing is probably preferable to silently dropping the problematic input lines. What would be the idiomatic way of handling such scenario?
Dominik Kapusta commented
In that case you could use guard
statement:
return input.map { stringValue in
guard let intValue = Int(stringValue) else {
fatalError("oh well")
}
return intValue
}
Note that $0
-notation is generally discouraged for closures longer than 1 line.