chalup / advent-swift

Advent of Code in Swift

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Avoid force-unwrapped optionals

ayoy opened this issue · comments

Apologies if that's stating the obvious, and it probably is, but you asked for it :)

return input.map { Int($0)! }

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) }

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?

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.