且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

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

更新时间:2023-10-31 18:04:34

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

The old Swift 1 syntax is based on the way you deal with option sets in C and Objective-C: you store an option set in an integer type and use bitwise operators (| and & and ~) to manipulate them. So .UsernameAndPassword | .LogInButton means an option set in which both the .UsernameAndPassword and the .LogInButton options are included. In the old syntax, you use nil to represent an empty option set (in which no options are included), which is not obvious based on the syntax for a non-empty set.

克里斯·拉特纳(Chris Lattner)在 WWDC 2015会话106:Swift的新增功能href ="https://developer.apple.com/videos/play/wwdc2015-106"一个>.首先,他描述了旧语法的问题:

Chris Lattner described the changed syntax in WWDC 2015 Session 106: What's New in Swift. First he describes the problems with the old syntax:

问题是,当您使用最终使用的其他语法时,它会不太好用.用nil创建一个空选项集-这没有意义,因为选项集和可选选项是完全不同的概念,并且将它们组合在一起.您可以通过按位操作来提取它们,这是一个痛苦且容易出错的操作,并且很容易出错.

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.

然后他描述了新方法:

但是Swift 2解决了这个问题.它使选项集像集合一样.这意味着选项集和选项集现在都带有方括号.这意味着您将获得带有空方括号的空集,并获得可与选项集一起使用的全套标准集API.

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协议(通过间接符合SetAlgebraType).该协议允许具有init的元素列表,从而使用数组文字初始化符合条件的对象.

The reason the new syntax works is because OptionSetType conforms to the ArrayLiteralConvertible protocol (indirectly, by conforming to SetAlgebraType). This protocol allows a conforming object to be initialized using an array literal, by having an init that takes a list of elements.

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

In the new Swift 2 syntax, [ .UsernameAndPassword, .LogInButton ] represents an option set containing both the .UsernameAndPassword and the .LogInButton options. Note that it looks just like the syntax by which you can initialize a plain old Set: let intSet: Set<Int> = [ 17, 45 ]. The new syntax makes it obvious that you specify an empty option set as [].