gpt4 book ai didi

swift - 在 Swift 中,这个特定的语法是什么意思?

转载 作者:搜寻专家 更新时间:2023-10-30 22:09:42 24 4
gpt4 key购买 nike

我一直在尝试按照一些 iOS Swift 教程连接到 Parse.com

codementor.io tutorial :

  loginViewController.fields = .UsernameAndPassword | .LogInButton | .PasswordForgotten | .SignUpButton | .Facebook | .Twitter

makeschool tutorial

  loginViewController.fields = [.UsernameAndPassword, .LogInButton, .SignUpButton, .PasswordForgotten, .Facebook]

我假设前者是 Switch 1.x,后者是 Swift 2。从上下文来看,它们似乎在做同样的事情,但我还没有找到语法变化的语言引用。很难搜索点、竖线和逗号……有人可以解释每个片段中的语法吗? (我正在努力阅读语言规范,但实际让应用程序运行会很有趣!)

最佳答案

旧的 Swift 1 语法基于您在 C 和 Objective-C 中处理选项集的方式:您以整数类型存储选项集并使用按位运算符(|&~ ) 来操纵它们。所以.UsernameAndPassword | .LogInButton表示一个选项集,其中 .UsernameAndPassword.LogInButton包括选项。在旧语法中,您使用 nil表示空选项集(其中不包含任何选项),根据非空集的语法,这并不明显。

Chris Lattner 在 WWDC 2015 Session 106: What's New in Swift 中描述了更改后的语法.首先,他描述了旧语法的问题:

The problem is, when you get to the other syntaxes you end up using, it is a bit less nice. You create an empty-option set with nil -- it doesn't make sense because option sets and optionals are completely different concepts and they're conflated together. You extract them with bitwise operations, which is a pain and super error-prone, and you can get it wrong easily.

然后他描述了新方法:

But Swift 2 solves this. It makes option sets set-like. That means option sets and sets are now formed with square brackets. That means you get empty sets with an empty set of square brackets, and you get the full set of standard set API to work with option sets.

新语法起作用的原因是因为 OptionSetType符合 ArrayLiteralConvertible协议(protocol)(间接地,通过遵守 SetAlgebraType )。该协议(protocol)允许使用数组字面量初始化符合条件的对象,方法是使用 init。它需要一个元素列表。

在新的 Swift 2 语法中,[ .UsernameAndPassword, .LogInButton ]表示包含 .UsernameAndPassword 的选项集和 .LogInButton选项。请注意,它看起来就像您可以用来初始化普通旧式 Set 的语法。 : let intSet: Set<Int> = [ 17, 45 ] .新语法明确表示您将一个空选项集指定为 []。 .

关于swift - 在 Swift 中,这个特定的语法是什么意思?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33863236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com