• Swift.Operator-and-Items-in-Swift(1)


    Operator and Item

    1. ..<

    for-in loop and the half-open range operator (..<)

    1         // Check each pair of items to see if they are equivalent.
    2         for i in 0..<someContainer.count {
    3             if someContainer[i] != anotherContainer[i] {
    4                 return false
    5             }
    6         }

    2. Generic Where Clauses

    1 extension Promise where T: Collection { // From PromiseKit library
    2       // .......  
    3 }

    Ref: Generic Where Clauses

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html

    3. trailing closure

     1 /**
     2  If you need to pass a closure expression to a function as the function’s final argument 
     3  and the closure expression is long, it can be useful to write it as a trailing closure 
     4  instead. A trailing closure is written after the function call’s parentheses, even though 
     5  it is still an argument to the function.
     6  */
     7 
     8 func someFunctionThatTakesClosure(a :Int, closure: () -> Void) {
     9     closure()
    10 }
    11 
    12 // Here's how you call this function without using a trailing closure:
    13 
    14 someFunctionThatTakesClosure(a: 3, closure: {
    15     // closure's body goes here
    16     print("closure as a parameter.")
    17 })
    18 
    19 // Here's how you call this function with a trailing closure instead:
    20 
    21 someFunctionThatTakesClosure(a: 4) {
    22     // trailing closure's body goes here
    23     print("trailing closure.")
    24 }
    25 
    26 
    27 extension Int {
    28     func repetitions(task: (_ th: Int) -> Void) {
    29         for i in 0 ..< self { // "for _ in a..<b" ??
    30             task(i)
    31         }
    32     }
    33 }
    34 
    35 let iExtension: Int = 5
    36 iExtension.repetitions { (th:Int) in  // arguments for Closure
    37     print("(th)th loop.")
    38 }
    39 print("+++++")
    40 iExtension.repetitions { th in      // arguments for Closure
    41     print("(th)th loop.")
    42 }
    1 print("2. +++++++++")
    2 iExtension.repetitions( task: { th in  // arguments
    3     print("without trailing closure (th)")
    4 })

    Ref:

    What is trailing closure syntax?

    https://www.hackingwithswift.com/example-code/language/what-is-trailing-closure-syntax

    4. Closure Expression Syntax

    { (parameters) -> return type in

      statements

    }

    4.1 Shorthand Argument Names {$0, $1, $2}

     1 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
     2     return s1 > s2
     3 })
     4 
     5 
     6 // Inferring Type From Context
     7 reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
     8 
     9 // Implicit Returns from Single-Expression Closures
    10 // Single-expression closures can implicitly return the result of their single 
    11 // expression by omitting the return keyword from their declaration
    12 reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
    13 
    14 
    15 // Swift automatically provides shorthand argument names to inline closures, 
    16 // which can be used to refer to the values of the closure’s 
    17 // arguments by the names $0, $1, $2
    18 reversedNames = names.sorted(by: { $0 > $1 } )

    5. guard statement

    guard statement is used to transfer program control out of a scope if one or more conditions aren’t met.

    guard statement has the following form:

    guard condition else {

      statements

    }

     

     1 func test_guard(_ i: Int) /* -> Void */ {
     2     
     3     guard i > 5 else {
     4         print("In test_guard() else clause.")
     5         return
     6     }
     7     
     8     print("In test_guard() the lastest statement.")
     9 }
    10 
    11 test_guard(4)
    12 
    13 // Output:
    14 In test_guard() else clause.

    Ref: 

    1. Guard Statement

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Statements.html

    6. ? and ! [*]

    6.1 "?"

    如下所示, 类型后的"?"表示什么:

    1 func handleLocation(city: String?, state: String?,
    2                     latitude: CLLocationDegrees, longitude: CLLocationDegrees) { 
    3 //......
    4 }

    6.2 "!"

    如下所示, "!"表示什么: 

    1 let urlString = "http://api.openweathermap.org/data/2.5/weather?lat=" + "(latitude)&lon=(longitude)&appid=(appID)"
    2 let url = URL(string: urlString)!
    3 let request = URLRequest(url: url)

    7. backtick(`) in identifier

    下面的代码中 "final func `catch` (" 为什么需要"`"符号:

     1     final func `catch`(on q: DispatchQueue, policy: CatchPolicy, else resolve: @escaping (Resolution<T>) -> Void, execute body: @escaping (Error) throws -> Void) {
     2         pipe { resolution in
     3             switch (resolution, policy) {
     4             case (.fulfilled, _):
     5                 resolve(resolution)
     6             case (.rejected(let error, _), .allErrorsExceptCancellation) where error.isCancelledError:
     7                 resolve(resolution)
     8             case (let .rejected(error, token), _):
     9                 contain_zalgo(q, rejecter: resolve) {
    10                     token.consumed = true
    11                     try body(error)
    12                 }
    13             }
    14         }
    15     }

      

    "To use a reserved word as an identifier, put a backtick (`) before and after it. For example, 

    class is not a valid identifier, but `class` is valid. The backticks are not considered part of the

    identifier; `x` and x have the same meaning."

    Ref: Identifiers

    https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/LexicalStructure.html

    8. "default" keyword in Swift parameter

    有这种情况,在Xcode中查看一些系统library的"头文件"(Swift中并没有Header File的概念)时,会遇到下面的情况:

    1 extension DispatchQueue {
    2 // ......
    3     public func async(group: DispatchGroup? = default, qos: DispatchQoS = default, flags: DispatchWorkItemFlags = default, execute work: @escaping @convention(block) () -> Swift.Void)
    4 // ......
    5 }

    "flags: DispatchWorkItemFlags = default"中有default keyword。

    "This is not a valid Swift code, it's generated on the fly." Ref[1]

    "You only see this when you're looking at what is effectively closed-source Swift – you're probably using Xcode to look

    at generated headers." Ref[2]

    "The default is produced by Xcode and means "there's a default value specified, but you can't see what it is because

    you don't have the source code." It's not syntactically valid to write this yourself. " Ref[2]

    Ref

    1. "default" keyword in function declarations?

    https://www.reddit.com/r/swift/comments/4im0jb/default_keyword_in_function_declarations/

    2. Default keyword in Swift parameter

    http://stackoverflow.com/questions/24991791/default-keyword-in-swift-parameter

    9. Variadic Parameters 

    可变的参数 

    "Variadic parameters are simply a more readable version of passing in an array of elements. In fact,

    if you were to look at the type of the internal parameter names in the below example, you’d see

    that it is of type [String] (array of strings):"

     1 func helloWithNames(names: String...) { // A: names's type is [String]
     2     for name in names {
     3         println("Hello, (name)")
     4     }
     5 }
     6 
     7 // 2 names
     8 helloWithNames("Mr. Robot", "Mr. Potato")
     9 // Hello, Mr. Robot
    10 // Hello, Mr. Potato
    11 
    12 // 4 names
    13 helloWithNames("Batman", "Superman", "Wonder Woman", "Catwoman")
    14 // Hello, Batman
    15 // Hello, Superman
    16 // Hello, Wonder Woman
    17 // Hello, Catwoman

    Ref

    1. The Many Faces of Swift Functions

    https://www.objc.io/issues/16-swift/swift-functions/#variadic-parameters

  • 相关阅读:
    JQUERY
    五分钟技术演讲
    T-SQL基础--chp10可编程对象学习笔记[下]
    SQL中用SET赋值和用SELECT赋值的区别。
    Can't find file: './mysql/plugin.frm' (errno: 13)[mysql数据目录迁移错位]错误解决
    jetty属性
    JRebel 5.3.2
    vue+mongoodb+node连接数据库
    css样式
    超出文本显示一行文字
  • 原文地址:https://www.cnblogs.com/cwgk/p/6296883.html
Copyright © 2020-2023  润新知