Search code examples
xcodetry-catchswift5xcode12

How to use try with data.withUnsafeBytes() in Swift 5, Swift5?


If I option click on withUnsafeBytes in my code, the declaration states that the function throws:

func withUnsafeBytes<R>(_ body: (UnsafeRawBufferPointer) throws -> R) rethrows -> R

When I put in do try catch in my code (see below) I get a warning for the try:

No calls to throwing functions occur within 'try' expression

and a matching warning for the catch:

'catch' block is unreachable because no errors are thrown in 'do' block

Is my code incorrect or is this a problem with Xcode?

func getIntValue(data:Data)->Int
{
    var d = -1
    
    do {
        d = try data.withUnsafeBytes {
            $0.load(as: Int.self)
        }
        
    } catch {
        return d
    }
    return d
}

Your input is appreciated.


Solution

  • The throws -> rethrows syntax does the following:

    • If the code in the closure body contains a throwing function the error is rethrown and you have to add try
    • If there is no throwing function nothing happens and you must not use try.

    In your example the second case occurs so remove try and the do - catch block