Swift 表达式

原文链接:http://www.cocoachina.com/newbie/basic/2014/0612/8797.html


本页包括内容:
前缀表达式(Prefix Expressions)
二元表达式(Binary Expressions)
赋值表达式(Assignment Operator)
三元条件运算符(Ternary Conditional Operator)
类型转换运算符(Type-Casting Operators)
主要表达式(Primary Expressions)
后缀表达式(Postfix Expressions)
 
Swift 中存在四种表达式: 前缀(prefix)表达式,二元(binary)表达式,主要(primary)表达式和后缀(postfix)表达式。表达式能够返回一个值,以及执行某些逻辑(causes a side effect)。
 
前缀表达式和二元表达式就是对某些表达式使用各种运算符(operators)。 主要表达式是最短小的表达式,它提供了获取(变量的)值的一种途径。 后缀表达式则同意你建立复杂的表达式。比如配合函数调用和成员訪问。 每种表达式都在以下有具体论述~
 
表达式的语法:

expression  prefix-expression­binary-expressions­opt­

expression-list  expression­  expression­expression-list­

 
前缀表达式(Prefix Expressions)

前缀表达式由 前缀符号和表达式组成。(这个前缀符号仅仅能接收一个參数)
 
Swift 标准库支持例如以下的前缀操作符:
++ 自增1 (increment)
-- 自减1 (decrement)
! 逻辑否 (Logical NOT )
~ 按位否 (Bitwise NOT )
+ 加(Unary plus)
- 减(Unary minus)
 
对于这些操作符的使用,请參见: Basic OperatorsAdvanced Operators
 
作为对上面标准库运算符的补充,你也能够对 某个函数的參数使用 '&'运算符。

很多其它信息,请參见: "In-Out parameters".

 
前缀表达式的语法:

prefix-expression  prefix-operator­opt­postfix-expression­

prefix-expression  in-out-expression­

in-out-expression  identifier­

 
二元表达式(Binary Expressions)

二元表达式由 "左边參数" + "二元运算符" + "右边參数" 组成, 它有例如以下的形式:
Swift 标准库提供了例如以下的二元运算符:
 
求幂相关(无结合,优先级160)
    << 按位左移(Bitwise left shift)
    >> 按位右移(Bitwise right shift)
 
乘除法相关(左结合,优先级150)
    * 乘
    / 除
    % 求余
    &* 乘法。忽略溢出( Multiply, ignoring overflow)
    &/ 除法。忽略溢出(Divide, ignoring overflow)
    &% 求余, 忽略溢出( Remainder, ignoring overflow)
    & 位与( Bitwise AND)
 
加减法相关(左结合, 优先级140)
    + 加
    - 减
    &+ Add with overflow
    &- Subtract with overflow
    | 按位或(Bitwise OR )
    ^ 按位异或(Bitwise XOR)
 
Range (无结合,优先级 135)
    .. 半闭值域 Half-closed range
    ... 全闭值域 Closed range
 
类型转换 (无结合,优先级 132)
    is 类型检查( type check)
    as 类型转换( type cast)
 
Comparative (无结合,优先级 130)
    < 小于
    <= 小于等于
    >大于
    >= 大于等于
    == 等于
    != 不等
    === 恒等于
    !== 不恒等
    ~= 模式匹配( Pattern match)
 
合取( Conjunctive) (左结合,优先级 120)
    && 逻辑与(Logical AND)
 
析取(Disjunctive) (左结合,优先级 110)
    || 逻辑或( Logical OR)
 
三元条件(Ternary Conditional )(右结合,优先级 100)
    ?: 三元条件 Ternary conditional
 
赋值 (Assignment) (右结合, 优先级 90)
    = 赋值(Assign)
    *= Multiply and assign
    /= Divide and assign
    %= Remainder and assign
    += Add and assign
    -= Subtract and assign
    <<= Left bit shift and assign
    = Right bit shift and assign
    &= Bitwise AND and assign
    ^= Bitwise XOR and assign
    |= Bitwise OR and assign
    &&= Logical AND and assign
    ||= Logical OR and assign
 
关于这些运算符(operators)的很多其它信息,请參见:Basic OperatorsAdvanced Operators.
 
注意:在解析时, 一个二元表达式表示为一个一级数组(a flat list), 这个数组(List)依据运算符的先后顺序。被转换成了一个tree. 比如: 2 + 3 5 首先被觉得是: 2, + , 3, , 5. 随后它被转换成 tree (2 + (3 * 5))
 
二元表达式的语法

binary-expression  binary-operator­prefix-expression­

binary-expression  assignment-operator­prefix-expression­

binary-expression  conditional-operator­prefix-expression­

binary-expression  type-casting-operator­

binary-expressions  binary-expression­binary-expressions­opt­

赋值表达式(Assignment Operator)

赋值表达式会对某个给定的表达式赋值。 它有例如以下的形式;
就是把右边的 value 赋值给左边的 expression. 假设左边的expression 须要接收多个參数(是一个tuple ),那么右边必须也是一个具有相同数量參数的tuple. (同意嵌套的tuple)
  1. (a, _, (b, c)) = ("test", 9.45, (12, 3)) 
  2. // a is "test", b is 12, c is 3, and 9.45 is ignored 
赋值运算符不返回不论什么值。

 
赋值表达式的语法:assignment-operator → =­
 
三元条件运算符(Ternary Conditional Operator)

三元条件运算符 是依据条件来获取值。

形式例如以下:

假设 condition 是true, 那么返回 第一个表达式的值(此时不会调用第二个表达式), 否则返回第二个表达式的值(此时不会调用第一个表达式)。

 
想看三元条件运算符的样例。请參见: Ternary Conditional Operator.
 
三元条件表达式:conditional-operator  expression­
 
类型转换运算符(Type-Casting Operators)

有两种类型转换操作符: as 和 is. 它们有例如以下的形式:
as 运算符会把目标表达式转换成指定的类型(specified type),步骤例如以下:
 
1.假设类型转换成功。 那么目标表达式就会返回指定类型的实例(instance). 比如:把子类(subclass)变成父类(superclass)时.
2.假设转换失败,则会抛出编译错误( compile-time error)。
3.假设上述两个情况都不是(也就是说。编译器在编译时期无法确定转换是否能成功,) 那么目标表达式就会变成指定的类型的optional. (is an optional of the specified type ) 然后在执行时,假设转换成功, 目标表达式就会作为 optional的一部分来返回。 否则,目标表达式返回nil. 相应的样例是: 把一个 superclass 转换成一个 subclass.
  1. class SomeSuperType {} 
  2. class SomeType: SomeSuperType {} 
  3. class SomeChildType: SomeType {} 
  4. let s = SomeType() 
  5.   
  6. let x = s as SomeSuperType  // known to succeed; type is SomeSuperType 
  7. let y = s as Int            // known to fail; compile-time error 
  8. let z = s as SomeChildType  // might fail at runtime; type is SomeChildType? 
 
使用'as'做类型转换跟正常的类型声明,对于编译器来说是一样的。比如:
  1. let y1 = x as SomeType  // Type information from 'as' 
  2. let y2: SomeType = x    // Type information from an annotation 
 
'is' 运算符在“执行时(runtime)”会做检查。 成功会返回true, 否则 false
 
上述检查在“编译时(compile time)”不能使用。 比如以下的使用是错误的:
  1. "hello" is String 
  2. "hello" is Int 
关于类型转换的很多其它内容和样例,请參见:Type Casting.
 
类型转换的语法:type-casting-operator  is­type­  as­?­opt­type­
 
主要表达式(Primary Expressions)

主要表达式是最主要的表达式。 它们能够跟 前缀表达式,二元表达式,后缀表达式以及其它主要表达式组合使用。
 
主要表达式的语法

primary-expression  identifier­generic-argument-clause­opt­

primary-expression  literal-expression­

primary-expression  self-expression­

primary-expression  superclass-expression­

primary-expression  closure-expression­

primary-expression  parenthesized-expression­

primary-expression  implicit-member-expression­

primary-expression  wildcard-expression

 
字符型表达式(Literal Expression)
由这些内容组成:普通的字符(string, number) , 一个字符的字典或者数组。或者以下列表中的特殊字符。
 
在某个函数(function)中,__FUNCTION__ 会返回当前函数的名字。 在某个方法(method)中。它会返回当前方法的名字。 在某个property 的getter/setter中会返回这个属性的名字。

在init/subscript中 仅仅有的特殊成员(member)中会返回这个keyword的名字,在某个文件的顶端(the top level of a file),它返回的是当前module的名字。

 
一个array literal,是一个有序的值的集合。 它的形式是:
数组中的最后一个表达式能够紧跟一个逗号(','). []表示空数组 。 array literal的type是 T[], 这个T就是数组中元素的type. 假设该数组中有多种type, T则是跟这些type的公共supertype最接近的type.(closest common supertype)
 
一个dictionary literal 是一个包括无序的键值对(key-value pairs)的集合,它的形式是:
dictionary 的最后一个表达式能够是一个逗号(','). [:] 表示一个空的dictionary. 它的type是 Dictionary (这里KeyType表示 key的type, ValueType表示 value的type) 假设这个dictionary 中包括多种 types, 那么KeyType, Value 则相应着它们的公共supertype最接近的type( closest common supertype).
 
字符型表达式的语法:

literal-expression  literal­

literal-expression  array-literal­  dictionary-literal­

literal-expression  __FILE__­  __LINE__­  __COLUMN__­  __FUNCTION__­

array-literal  array-literal-items­opt­

array-literal-items  array-literal-item­opt­  array-literal-item­array-literal-items­

array-literal-item  expression­

dictionary-literal  dictionary-literal-items­  [­:­]­

dictionary-literal-items  dictionary-literal-item­opt­  dictionary-literal-item­dictionary-literal-items­

dictionary-literal-item  expression­expression­

 
self表达式(Self Expression)
self表达式是对 当前type 或者当前instance的引用。

它的形式例如以下:

 
假设在 initializer, subscript, instance method中,self等同于当前type的instance. 在一个静态方法(static method), 类方法(class method)中, self等同于当前的type.
 
当訪问 member(成员变量时)。 self 用来区分重名变量(比如函数的參数). 比如, (以下的 self.greeting 指的是 var greeting: String, 而不是 init(greeting: String) )
  1. class SomeClass { 
  2.     var greeting: String 
  3.     init(greeting: String) { 
  4.         self.greeting = greeting 
  5.     } 
 
在mutating 方法中, 你能够使用self 对 该instance进行赋值。

  1. struct Point { 
  2.     var x = 0.0, y = 0.0 
  3.     mutating func moveByX(deltaX: Double, y deltaY: Double) { 
  4.         self = Point(x: x + deltaX, y: y + deltaY) 
  5.     } 
self表达式的语法:

self-expression  self­

self-expression  self­.­identifier­

self-expression  self­[­expression­

self-expression  self­.­init­

超类表达式(Superclass Expression)
超类表达式能够使我们在某个class中訪问它的超类. 它有例如以下形式:
形式1 用来訪问超类的某个成员(member). 形式2 用来訪问该超类的 subscript 实现。 形式3 用来訪问该超类的 initializer.
 
子类(subclass)能够通过超类(superclass)表达式在它们的 member, subscripting 和 initializers 中来利用它们超类中的某些实现(既有的方法或者逻辑)。

 
超类表达式语法:

superclass-expression  superclass-method-expression­  superclass-subscript-expression­ superclass-initializer-expression­

superclass-method-expression  super­.­identifier­

superclass-subscript-expression  super­[­expression­

superclass-initializer-expression  super­.­init

 
闭包表达式(Closure Expression)
闭包(closure) 表达式能够建立一个闭包(在其它语言中也叫 lambda, 或者 匿名函数(anonymous function)). 跟函数(function)的声明一样, 闭包(closure)包括了可运行的代码(跟方法主体(statement)类似) 以及接收(capture)的參数。

它的形式例如以下:

闭包的參数声明形式跟方法中的声明一样, 请參见:Function Declaration.
 
闭包还有几种特殊的形式, 让使用更加简洁:
1.闭包能够省略 它的參数的type 和返回值的type. 假设省略了參数和參数类型,就也要省略 'in'keyword。 假设被省略的type 无法被编译器获知(inferred) ,那么就会抛出编译错误。
2.闭包能够省略參数,转而在方法体(statement)中使用 0,1, $2 来引用出现的第一个。第二个,第三个參数。

3.假设闭包中仅仅包括了一个表达式,那么该表达式就会自己主动成为该闭包的返回值。 在运行 'type inference '时,该表达式也会返回。
 
以下几个 闭包表达式是 等价的:
  1. myFunction { 
  2.     (x: Int, y: Int) -> Int in 
  3.     return x + y 
  4.   
  5. myFunction { 
  6.     (x, y) in 
  7.     return x + y 
  8.   
  9. myFunction { return $0 + $1 } 
  10.   
  11. myFunction { $0 + $1 } 
关于 向闭包中传递參数的内容。參见: Function Call Expression.
 
闭包表达式能够通过一个參数列表(capture list) 来显式指定它须要的參数。 參数列表 由中括号 [] 括起来。里面的參数由逗号','分隔。一旦使用了參数列表,就必须使用'in'keyword(在不论什么情况下都得这样做。包含忽略參数的名字,type, 返回值时等等)。
 
在闭包的參数列表( capture list)中, 參数能够声明为 'weak' 或者 'unowned' .
  1. myFunction { print(self.title) }                    // strong capture 
  2. myFunction { [weak self] in print(self!.title) }    // weak capture 
  3. myFunction { [unowned self] in print(self.title) }  // unowned capture 
 
在參数列表中。也能够使用随意表达式来赋值. 该表达式会在 闭包被运行时赋值,然后依照不同的力度来获取(这句话请谨慎理解)。 比如:
  1. // Weak capture of "self.parent" as "parent" 
  2. myFunction { [weak parent = self.parent] in print(parent!.title) } 
关于闭包表达式的很多其它信息和样例,请參见: Closure Expressions.
 
闭包表达式的语法:

closure-expression  closure-signature­opt­statements­

closure-signature  parameter-clause­function-result­opt­in­

closure-signature  identifier-list­function-result­opt­in­

closure-signature  capture-list­parameter-clause­function-result­opt­in­

closure-signature  capture-list­identifier-list­function-result­opt­in­

closure-signature  capture-list­in­

capture-list  capture-specifier­expression­

capture-specifier  weak|unowned­ | unowned(safe)­|  unowned(unsafe)­

 
隐式成员表达式(Implicit Member Expression)
在能够推断出类型(type)的上下文(context)中,隐式成员表达式是訪问某个type的member( 比如 class method, enumeration case) 的简洁方法。 它的形式是:
样例:
  1. var x = MyEnumeration.SomeValue 
  2. x = .AnotherValue 
隐式成员表达式的语法:implicit-member-expression  identifier­

 
圆括号表达式(Parenthesized Expression)
圆括号表达式由多个子表达式和逗号','组成。 每一个子表达式前面能够有 identifier x: 这种可选前缀。

形式例如以下:

圆括号表达式用来建立tuples , 然后把它做为參数传递给 function. 假设某个圆括号表达式中仅仅有一个 子表达式,那么它的type就是 子表达式的type。

比如: (1)的 type是Int, 而不是(Int)

 
圆括号表达式的语法:

parenthesized-expression  expression-element-list­opt­

expression-element-list  expression-element­ | expression-element­expression-element-list­

expression-element  expression­ | identifier­expression­

通配符表达式(Wildcard Expression)
通配符表达式用来忽略传递进来的某个參数。

比如:以下的代码中,10被传递给x, 20被忽略(译注:好奇葩的语法。。。)

  1. (x, _) = (10, 20) 
  2. // x is 10, 20 is ignored 
通配符表达式的语法:wildcard-expression  

 
后缀表达式(Postfix Expressions)

后缀表达式就是在某个表达式的后面加上 操作符。

严格的讲,每一个主要表达式(primary expression)都是一个后缀表达式。

 
Swift 标准库提供了下列后缀表达式:
    ++ Increment
    -- Decrement
 
对于这些操作符的使用,请參见:Basic Operators 和Advanced Operators
 
后缀表达式的语法:

postfix-expression  primary-expression­

postfix-expression  postfix-expression­postfix-operator­

postfix-expression  function-call-expression­

postfix-expression  initializer-expression­

postfix-expression  explicit-member-expression­

postfix-expression  postfix-self-expression­

postfix-expression  dynamic-type-expression­

postfix-expression  subscript-expression­

postfix-expression  forced-value-expression­

postfix-expression  optional-chaining-expression

 
函数调用表达式(Function Call Expression)
函数调用表达式由函数名和參数列表组成。它的形式例如以下:
假设该function 的声明中指定了參数的名字。那么在调用的时候也必须得写出来. 比如:
 
能够在 函数调用表达式的尾部(最后一个參数之后)加上 一个闭包(closure) , 该闭包会被目标函数理解并运行。它具有例如以下两种写法:
  1. // someFunction takes an integer and a closure as its arguments 
  2. someFunction(x, {$0 == 13}) 
  3. someFunction(x) {$0 == 13} 
 
假设闭包是该函数的唯一參数,那么圆括号能够省略。

  1. // someFunction takes a closure as its only argument 
  2. myData.someMethod() {$0 == 13} 
  3. myData.someMethod {$0 == 13} 
 
函数调用表达式语法:

function-call-expression  postfix-expression­parenthesized-expression­

function-call-expression  postfix-expression­parenthesized-expression­opt­trailing-closure­

trailing-closure  closure-expression

 
初始化函数表达式(Initializer Expression)
Initializer表达式用来给某个Type初始化。

它的形式例如以下:

 
(Initializer表达式用来给某个Type初始化。) 跟函数(function)不同。 initializer 不能返回值。
  1. var x = SomeClass.someClassFunction // ok 
  2. var y = SomeClass.init              // error 
你也能够使用初始化函数表达式来托付给父类的initializer
  1. class SomeSubClass: SomeSuperClass { 
  2.     init() { 
  3.         // subclass initialization goes here 
  4.         super.init() 
  5.     } 
initializer表达式的语法initializer-expression  postfix-expression­.­init
 
显式成员表达式(Explicit Member Expression)
显示成员表达式同意我们訪问type, tuple, module的成员变量。它的形式例如以下:
该member 就是某个type在声明时候所定义(declaration or extension) 的变量, 比如:
  1. class SomeClass { 
  2.     var someProperty = 42 
  3. let c = SomeClass() 
  4. let y = c.someProperty  // Member access 
对于tuple, 要依据它们出现的顺序(0, 1, 2...)来使用:
  1. var t = (10, 20, 30) 
  2. t.0 = t.1 
  3. // Now t is (20, 20, 30) 
显示成员表达式的语法:

explicit-member-expression  postfix-expression­decimal-digit­

explicit-member-expression  postfix-expression­identifier­generic-argument-clause­opt

 
后缀self表达式(Postfix Self Expression)
后缀表达式由 某个表达式 + '.self' 组成. 形式例如以下:
形式1 表示会返回 expression 的值。比如: x.self 返回 x
 
形式2返回相应的type。我们能够用它来动态的获取某个instance的type。
 
后缀self表达式的语法:postfix-self-expression  postfix-expression­.­self
 
Dynamic Type表达式(Dynamic Type Expression)
(由于dynamicType是一个独有的方法,所以这里保留了英文单词,未作翻译, --- 类似与self expression)
 
Dynamic Type表达式由 某个表达式 + '.dynamicType' 组成。

 
上面的形式中, expression 不能是某type的名字(当然了,假设我都知道它的名字了还须要动态来获取它吗)。动态类型表达式会返回"执行时"某个instance的type, 详细请看以下的列子:
  1. class SomeBaseClass { 
  2.     class func printClassName() { 
  3.         println("SomeBaseClass"
  4.     } 
  5. class SomeSubClass: SomeBaseClass { 
  6.     override class func printClassName() { 
  7.         println("SomeSubClass"
  8.     } 
  9. let someInstance: SomeBaseClass = SomeSubClass() 
  10. // someInstance is of type SomeBaseClass at compile time, but 
  11. // someInstance is of type SomeSubClass at runtime 
  12. someInstance.dynamicType.printClassName() 
  13. // prints "SomeSubClass" 
Dynamic Type表达式语法:dynamic-type-expression  postfix-expression­.­dynamicType­

附属脚本表达式(Subscript Expression)
附属脚本表达式提供了通过附属脚本訪问getter/setter 的方法。

它的形式是:

能够通过附属脚本表达式通过getter获取某个值,或者通过setter赋予某个值.
 
关于subscript的声明,请參见:Protocol Subscript Declaration.
 
附属脚本表达式的语法:subscript-expression  postfix-expression­expression-list­]
 
强制取值表达式(Forced-Value Expression)
强制取值表达式用来获取某个目标表达式的值(该目标表达式的值必须不是nil )。它的形式例如以下:
假设该表达式的值不是nil, 则返回相应的值。 否则,抛出执行时错误(runtime error)。
 
强制取值表达式的语法:forced-value-expression  postfix-expression­
 
可选链表达式(Optional-Chaining Expression)
可选链表达式由目标表达式 + '?

' 组成,形式例如以下:

后缀'?

' 返回目标表达式的值。把它做为可选的參数传递给兴许的表达式

 
假设某个后缀表达式包括了可选链表达式,那么它的运行过程就比較特殊: 首先先推断该可选链表达式的值,假设是 nil, 整个后缀表达式都返回 nil, 假设该可选链的值不是nil, 则正常返回该后缀表达式的值(依次运行它的各个子表达式)。在这两种情况下。该后缀表达式仍然是一个optional type(In either case, the value of the postfix expression is still of an optional type)
 
假设某个"后缀表达式"的"子表达式"中包括了"可选链表达式",那么仅仅有最外层的表达式返回的才是一个optional type. 比如。在以下的样例中。 假设c 不是nil, 那么 c?

.property.performAction() 这句代码在运行时,就会先获得c 的property方法。然后调用 performAction()方法。

然后对于 "c?.property.performAction()" 这个总体,它的返回值是一个optional type.

  1. var c: SomeClass?

     

  2. var result: Bool?

     = c?.property.performAction() 

 
假设不使用可选链表达式。那么 上面样例的代码跟以下样例等价:
  1. if let unwrappedC = c { 
  2.     result = unwrappedC.property.performAction() 
可选链表达式的语法:optional-chaining-expression  postfix-expression­?

原文地址:https://www.cnblogs.com/wzjhoutai/p/6738545.html