Optional binding with try? and in quality? still producing an optional type

I have code to execute NSFetchRequest and output its result to an array of my custom data model type. An extraction may throw, but I don't want to take care of the error, so am I using try? , and also use as? when casting. In Swift 2, this was just fine, but Swift 3 creates a double option:

 var expenses: [Expense]? { let request = NSFetchRequest<NSFetchRequestResult>(entityName: Expense.entityName) request.predicate = NSPredicate(format: "dateSpent >= %@ AND dateSpent <= %@", [self.startDate, self.endDate]) // Returns [Expense]? because right side is [Expense]?? if let expenses = try? App.mainQueueContext.fetch(request) as? [Expense], expenses?.isEmpty == false { return expenses } return nil } 

How can I rephrase the right side of my optional binding in if let , so that its type is just an [Expense] array? I think it is absurd that in the following logical condition (which used to be a where clause), the array is still optional.

+5
source share
2 answers

Do you have to make your try? call try? in parentheses as follows:

 if let expenses = (try? App.mainQueueContext.fetch(request)) as? [Expense] 

Is it because as? has higher priority than try? (perhaps because try? can be applied to the whole expression).

+7
source

@Fantattitude's answer gives what you want. But I need to go through the document to find out why. To be a comment for a long time, here is the link:


According to Swift Programming (Swift 3) Expressions Chapter

When the expression is on the left side of the binary operator tagged with try, try ?, or try !, this statement refers to a binary integer expression.

First, I thought that as might not be a binary operator, but in Swift Standard Library Statements

as , as? and as! are Infix operators

and operator declaration chapter

Infix operator is a binary operator that is written between its two operands, such as the familiar addition operator (+) in the expression 1 + 2.

+5
source

Source: https://habr.com/ru/post/1257725/


All Articles