加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift – 如何在if条件下使用尾随闭包?

发布时间:2020-12-14 05:43:33 所属栏目:百科 来源:网络整理
导读:这是代码: class Person {}func lastNameForPerson(person: Person,caseFolding: ((String)-(String))? = nil) - String { if let folder = caseFolding { return folder("Smith") } return "Smith"}print(lastNameForPerson(Person())) // Prints "Smith"p
这是代码:
class Person {
}

func lastNameForPerson(person: Person,caseFolding: ((String)->(String))? = nil) -> String {
    if let folder = caseFolding {
        return folder("Smith")
    }
    return "Smith"
}

print(lastNameForPerson(Person())) // Prints "Smith"
print(lastNameForPerson(Person()) {$0.uppercaseString}) // Prints "SMITH"

if "SMITH" == lastNameForPerson(Person()) {$0.uppercaseString} {
    print("It's bob")
}

期待得到“它的鲍勃”.但反而得到了错误:

Consecutive statements must be separated by a new line

你必须在函数调用周围加上括号:
if "SMITH" == (lastNameForPerson(Person()) {$0.uppercaseString}) {
    print("It's bob")
}

或者你以C风格的方式将它们放在==比较(在if条件周围):

if ("SMITH" == lastNameForPerson(Person()) {$0.uppercaseString}) {
    print("It's bob")
}

或者,您可以在参数列表中移动闭包(尽管这需要您明确命名参数):

if "SMITH" == lastNameForPerson(Person(),caseFolding: {$0.uppercaseString}) {
    print("It's bob")
}

出现此问题的原因是if语句’声明'{}块,即它不再属于lastNameForPerson调用.对于编译器,第二个代码块现在看起来像是一个与前一个(if)语句没有正确分开的普通块.

你应该考虑避免使用这样的结构,因为它可能很难阅读(起初).相反,您可以将函数调用的结果存储在变量中,并将其进行比较:

let lastName = lastNameForPerson(Person()) {$0.uppercaseString}
if "SMITH" == lastName {
    print("It's bob")
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读