Swift.Operator-and-Items-in-Swift(1)
Operator and Item
1. ..<
a 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
A guard
statement is used to transfer program control out of a scope if one or more conditions aren’t met.
A 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)的更多相关文章
- Swift 正式开源, 包括 Swift 核心库和包管理器
Swift 正式开源!Swift 团队很高兴宣布 Swift 开始开源新篇章.自从苹果发布 Swfit 编程语言,就成为了历史上发展最快的编程语言之一.Swift 通过设计使得软件编写更加快速更加安全 ...
- swift:Optional Type 、Swift和Objective-C混编的讲解
❤️❤️❤️swift中的Optional Type的?和!含义:其实就是一个装包和拆包的过程 optional的含义: Optional事实上是一个枚举类型,Optional包含None和Some两 ...
- swift-01-简述swift与OC区别
swift语言 Swift是Apple在WWDC2014所发布的一门编程语言,用来撰写OS X和iOS应用程序[1].在设计Swift时.就有意和Objective-C共存,Objective-C是A ...
- swift学习:第一个swift程序
原文:swift学习:第一个swift程序 最近swift有点火,赶紧跟上学习.于是,个人第一个swift程序诞生了... 新建项目
- Swift 与 Object-C 交互 (Swift版本为:1.2)
这篇文章主要是介绍 Swift 与 Object-C 之间进行交互的代码,主要分为两个部分.一个是 Swift 项目调用 Object-C 的类,另一个是 Object-C 项目调用 Swift 类. ...
- swift学习第二天:swift中的基本数据类型
一:swift基本数据类型 Swift中的数据类型也有:整型/浮点型/对象类型/结构体类型等等 先了解整型和浮点型 整型 有符号 Int8 : 有符号8位整型 Int16 : 有符号16位整型 Int ...
- 【swift学习笔记】四.swift使用Alamofire和swiftyJson
Alamofire是AFNetworking的swift版本,功能灰常强大. github:https://github.com/Alamofire/Alamofire SwiftyJSON是操作js ...
- iOS开发--Swift 如何完成工程中Swift和OC的混编桥接(Cocoapods同样适用)
由于SDK现在大部分都是OC版本, 所以假如你是一名主要以Swift语言进行开发的开发者, 就要面临如何让OC和Swift兼容在一个工程中, 如果你没有进行过这样的操作, 会感觉异常的茫然, 不用担心 ...
- 一步一步学习Swift之(一):关于swift与开发环境配置
一.什么是Swift? 1.Swift 是一种新的编程语言,用于编写 iOS 和 OS X 应用. 2.Swift 结合了 C 和 Objective-C 的优点并且不受 C 兼容性的限制. 3.Sw ...
- swift语言实战晋级-1 Swift开发环境的搭建
想要进行Swift的学习,必须要有个开发环境.简单的说就是装好了Xcode的Mac系统.那么接下来我们就简单了解一下这方面的内容. 1.1 下载Xcode Xcode是苹果公司出的编程工具,类似于微软 ...
随机推荐
- IE8图片上传预览
$("#smallImg").attr('style', "filter:progid:DXImageTransform.Microsoft.AlphaImageLoad ...
- Postman A请求的返回值作为B请求的入参( 之‘’token‘’ ,用代码设置全局变量)
问题: 登陆接口获取token,其他接口访问时需携带token 方案: 在登陆接口访问后设置Postman的全局变量(Globals),例如设置环境变量名:token2,值(实时的不用自己手动设置的) ...
- 如何使用cloudflare的CDN加速网站隐藏网站IP
原文:http://www.safecdn.cn/contact-zh/2018/12/cloudflare-cdn/1146.html 高防CDN:https://www.safeidc.cn/cd ...
- 分组ntile
select order,ntile(3) over (order by order) from ss
- time模块的学习
time模块不在python35\lib的安装目录下,是因为该模块是用C语言编写,内置到python解释器中.各种时间格式相互转换关系: import time,datetime # print(ti ...
- idea搭建ssm框架
1.file-->new-->project-->maven.... 2.建立后的目录: 3.pom.xml依赖建立: <?xml version="1.0" ...
- XenApp6.5产品BUG
外网登录报错,手机登录报错问题解决: XenApp6.5产品BUG, 在WI服务器的两个web站点中修改defalut.ica文件中添加一行,CGPAddr=即可. 路径:C:\inetpub\www ...
- django settings多环境配置
通常我们会把本地.线上的配置拆分,django不同环境的配置可如下: 1.在settings.py同级目录添加settings文件夹 2.把settings.py移到settings文件夹内,并重命名 ...
- VB6 二维数组去重实现
关于VB6的二维数组去重算法实现 当然,这里还是有局限性,当我们的数组被填满了各个不同的值时,例如下方 700*700 = 490000 就要While49万次,这谁受得了? 所以以下仅适合小规模使用 ...
- vue中less文件全局引用
1.先安装sass-resources-loader npm install sass-resources-loader 2.然后在build->utils.js修改less配置 在less ...