Swift:如果让语句条件,则不能使用数组过滤器 [英] Swift: Can not use array filter in if let statement condition

查看:107
本文介绍了Swift:如果让语句条件,则不能使用数组过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个用户名数组

Suppose I have an array of user's names

let users = ["Hello", "1212", "12", "Bob", "Rob"]

我想获得第一个名称长度为2的用户,所以我过滤了数组并得到了第一个用户

I want to get the first user whose name length is 2, so I filtered the array and got the first user

if let selected = users.filter{$0.characters.count == 2}.first {
   print(selected)
}

此代码在swift 2.2下引发编译错误

This code is throwing a compilation error under swift 2.2

Consecutive statements on a line must be separated by ';'

但是,这仍然可以正常工作

However, this is working fine though

let selected = users.filter{$0.characters.count == 2}.first
if let selected = selected {
   print(selected)
}

谁能解释为什么我需要首先将过滤器结果存储在一个单独的变量中?任何帮助将不胜感激.

Can anyone explain why do I need to store filter result in a separate variable first? Any help would be really appreciated.

推荐答案

您可以通过在要传递给filter的闭包周围加上括号来完成这项工作:

You can make this work by putting parentheses around the closure that you're passing to filter:

if let selected = users.filter({$0.characters.count == 2}).first {
    print(selected)
}

那是正确的方法.尾随的闭合语法有时在带有额外元素的行上效果不佳.您还可以在整个语句周围加上括号:

That is the right way to do it. The trailing closure syntax doesn't work very well sometimes on lines with extra elements. You could also put parentheses around the whole statement:

if let selected = (users.filter {$0.characters.count == 2}.first) {
    print(selected)
}

Swift在解析您的语句时遇到了麻烦.括号可帮助您解析该行.您应该首选第一种方法,因为闭包确实是filter的参数,因此将其括在括号中可以使Swift清楚地知道将其传递给filter.

Swift is just having trouble parsing your statement. The parentheses give it help in how to parse the line. You should prefer the first way since the closure is indeed a parameter of filter, so enclosing it in parentheses makes it clear to Swift that you are passing it to filter.

这篇关于Swift:如果让语句条件,则不能使用数组过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆