Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
274 views
in Technique[技术] by (71.8m points)

ios - Optional binding with try? and as? still produces an optional type

I have code for executing an NSFetchRequest and casting its result to an array of my custom data model type. Fetching may throw but I don't want to care about the error so I use try?, and I also use as? in casting. In Swift 2, this used to be just fine, but Swift 3 produces a double optional:

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 will simply be an array [Expense]? I think it looks absurd that in the following boolean condition (which used to be a where clause), the array is still optional.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You must wrap your try? call within parenthesis like this?:

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

That's because as? has a higher precedence than try? (probably because try? can be applied to the whole expression).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...