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") } 期待得到“它的鲍勃”.但反而得到了错误:
你必须在函数调用周围加上括号:
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") } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- C#/ WPF:Toolkit DataGrid – 转置行和列
- 详解vue事件对象、冒泡、阻止默认行为
- 使用build.xml自动拷贝文件并打包成zip
- react-native模仿京东首页
- c# – 如何使用MVVM模式在Wpf应用程序上实现本地化?
- ruby-on-rails – 您使用Rails的版本控制和部署工作流程是什
- Oracle 12.2 sec_case_sensitive_logon设置为true 或者fals
- c# – EF Core 2.0 TransactionScope错误
- 使用默认命名空间绑定的XML上的XML xpath查询
- xml – 当attibute不存在时,按属性选择xpath