Operator and Item

1. ..<

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

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

2. Generic Where Clauses

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

Ref: Generic Where Clauses

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

3. trailing closure

 /**
If you need to pass a closure expression to a function as the function’s final argument
and the closure expression is long, it can be useful to write it as a trailing closure
instead. A trailing closure is written after the function call’s parentheses, even though
it is still an argument to the function.
*/ func someFunctionThatTakesClosure(a :Int, closure: () -> Void) {
closure()
} // Here's how you call this function without using a trailing closure: someFunctionThatTakesClosure(a: , closure: {
// closure's body goes here
print("closure as a parameter.")
}) // Here's how you call this function with a trailing closure instead: someFunctionThatTakesClosure(a: ) {
// trailing closure's body goes here
print("trailing closure.")
} extension Int {
func repetitions(task: (_ th: Int) -> Void) {
for i in ..< self { // "for _ in a..<b" ??
task(i)
}
}
} let iExtension: Int =
iExtension.repetitions { (th:Int) in // arguments for Closure
print("\(th)th loop.")
}
print("+++++")
iExtension.repetitions { th in     // arguments for Closure
print("\(th)th loop.")
}
 print("2. +++++++++")
iExtension.repetitions( task: { th in // arguments
print("without trailing closure \(th)")
})

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}

 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in
return s1 > s2
}) // Inferring Type From Context
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } ) // Implicit Returns from Single-Expression Closures
// Single-expression closures can implicitly return the result of their single
// expression by omitting the return keyword from their declaration
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } ) // Swift automatically provides shorthand argument names to inline closures,
// which can be used to refer to the values of the closure’s
// arguments by the names $0, $1, $2
reversedNames = names.sorted(by: { $ > $ } )

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

}

 func test_guard(_ i: Int) /* -> Void */ {

     guard i >  else {
print("In test_guard() else clause.")
return
} print("In test_guard() the lastest statement.")
} test_guard() // Output:
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 "?"

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

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

6.2 "!"

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

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

7. backtick(`) in identifier

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

     final func `catch`(on q: DispatchQueue, policy: CatchPolicy, else resolve: @escaping (Resolution<T>) -> Void, execute body: @escaping (Error) throws -> Void) {
pipe { resolution in
switch (resolution, policy) {
case (.fulfilled, _):
resolve(resolution)
case (.rejected(let error, _), .allErrorsExceptCancellation) where error.isCancelledError:
resolve(resolution)
case (let .rejected(error, token), _):
contain_zalgo(q, rejecter: resolve) {
token.consumed = true
try body(error)
}
}
}
}

"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的概念)时,会遇到下面的情况:

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

"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):"

 func helloWithNames(names: String...) { // A: names's type is [String]
for name in names {
println("Hello, \(name)")
}
} // 2 names
helloWithNames("Mr. Robot", "Mr. Potato")
// Hello, Mr. Robot
// Hello, Mr. Potato // 4 names
helloWithNames("Batman", "Superman", "Wonder Woman", "Catwoman")
// Hello, Batman
// Hello, Superman
// Hello, Wonder Woman
// Hello, Catwoman

Ref

1. The Many Faces of Swift Functions

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

Swift.Operator-and-Items-in-Swift(1)的更多相关文章

  1. Swift 正式开源, 包括 Swift 核心库和包管理器

    Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章.自从苹果发布 Swfit 编程语言,就成为了历史上发展最快的编程语言之一.Swift 通过设计使得软件编写更加快速更加安全 ...

  2. swift:Optional Type 、Swift和Objective-C混编的讲解

    ❤️❤️❤️swift中的Optional Type的?和!含义:其实就是一个装包和拆包的过程 optional的含义: Optional事实上是一个枚举类型,Optional包含None和Some两 ...

  3. swift-01-简述swift与OC区别

    swift语言 Swift是Apple在WWDC2014所发布的一门编程语言,用来撰写OS X和iOS应用程序[1].在设计Swift时.就有意和Objective-C共存,Objective-C是A ...

  4. swift学习:第一个swift程序

    原文:swift学习:第一个swift程序 最近swift有点火,赶紧跟上学习.于是,个人第一个swift程序诞生了... 新建项目

  5. Swift 与 Object-C 交互 (Swift版本为:1.2)

    这篇文章主要是介绍 Swift 与 Object-C 之间进行交互的代码,主要分为两个部分.一个是 Swift 项目调用 Object-C 的类,另一个是 Object-C 项目调用 Swift 类. ...

  6. swift学习第二天:swift中的基本数据类型

    一:swift基本数据类型 Swift中的数据类型也有:整型/浮点型/对象类型/结构体类型等等 先了解整型和浮点型 整型 有符号 Int8 : 有符号8位整型 Int16 : 有符号16位整型 Int ...

  7. 【swift学习笔记】四.swift使用Alamofire和swiftyJson

    Alamofire是AFNetworking的swift版本,功能灰常强大. github:https://github.com/Alamofire/Alamofire SwiftyJSON是操作js ...

  8. iOS开发--Swift 如何完成工程中Swift和OC的混编桥接(Cocoapods同样适用)

    由于SDK现在大部分都是OC版本, 所以假如你是一名主要以Swift语言进行开发的开发者, 就要面临如何让OC和Swift兼容在一个工程中, 如果你没有进行过这样的操作, 会感觉异常的茫然, 不用担心 ...

  9. 一步一步学习Swift之(一):关于swift与开发环境配置

    一.什么是Swift? 1.Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用. 2.Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制. 3.Sw ...

  10. swift语言实战晋级-1 Swift开发环境的搭建

    想要进行Swift的学习,必须要有个开发环境.简单的说就是装好了Xcode的Mac系统.那么接下来我们就简单了解一下这方面的内容. 1.1 下载Xcode Xcode是苹果公司出的编程工具,类似于微软 ...

随机推荐

  1. 缓存--Redis

    Redis redis是一个key-value存储系统.和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(链表).set(集合).zset(sorte ...

  2. #include 相关问题

    #include <> 和 #include “”的区别是#include <>先从系统默认的搜索路径开始搜索,#include “”是从当前目录开始搜索,如果未搜索到,都会继 ...

  3. PHP截取特定字符串前后

    $email   =  '13366540193@163.com' ;$domain  =  strstr ( $email ,  '@' );echo  $domain ;  // 打印 @163. ...

  4. Spring 整合WebSocket, Error during WebSocket handshake: Unexpected response code: 302 还有200的错误

    springboot 集成websocket 及其简单,,,但是管理端使用的是Spring,原生配置,发生这个错误,,,302 被重定向了...我起的是本地locallhost,把ip换成 local ...

  5. python学习 生成随机函数 random模块的用法

    random模块是用于生成随机数 常用函数 函数 含义 random() 生成一个[0,1.0)之间的随机浮点数 uniform(a,b) 生成一个a到b之间的随机浮点数 randint(a,b) 生 ...

  6. spark报错:warn util.utils::service 'sparkUI' can not bind on part 4040.Attempting port 4041.

    转载自:https://blog.csdn.net/weixin_41629917/article/details/83190258

  7. Linux seq_printf输出内容不完整的问题

    Linux seq_printf输出内容不完整的问题 写在前面的话:这是多年前在项目中遇到的问题,作为博客的开篇之作,有不足之处,请各位大侠斧正!谢谢! seq_file接口介绍 有许多种方法能够实现 ...

  8. NBU显示备份成功,但实际是无备份成功

    从3月18日开始到4月3日是备份失败的 GROUPSIZE 7 OPERATION BACKUPDATABASE "DBADB" SQLHOST "yicatong&qu ...

  9. MySQL添加用户并授权

    一. 创建用户 命令: CREATE USER 'username'@'host' IDENTIFIED BY 'password'; 说明: username:你将创建的用户名 host:指定该用户 ...

  10. python--第二十四天总结

    CMDB介绍 CMDB --Configuration Management Database 配置管理数据库, CMDB存储与管理企业IT架构中设备的各种配置信息,它与所有服务支持和服务交付流程都紧 ...