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是苹果公司出的编程工具,类似于微软 ...
随机推荐
- DevExpress 折线图和柱状图的绘制与数据绑定
DevExpress 组件是一个非常丰富和强大的组件,适合各种可视化图形的绘制与展示,在数据分析展示中是个很有帮助的,网上也有很多关于这方面的文章,关于折线图或柱状图的画法,以下是自己在工作中接触到的 ...
- 关于使用echarts走过的坑(同grid多图、多轴系列)
相信大家在工作中,经常会用到echarts,今天我说下我在工作中浪费时间较长的坑 先来看看我的终极需要实现的图吧: 相信以上效果对于常用的小伙伴来说并不困难, 在此我只说option的配置,关于数据, ...
- python 匿名函数&内置函数
匿名函数:为了解决那些功能很简单的需求而设计的一句话函数怎么定义匿名函数: cal = lambda x : x*x # cal是函数名,lambda是定义匿名函数的关键字 冒号前面的额x是参数即函数 ...
- Android短信过滤项目中的观察者模式
观察者模式: 观察者模式定义了对象之间的一对多依赖,当一个对象改变状态时,它的所有依赖者都会收到通知并自动更新. 观察者模式提供了一种对象设计, 让主题和观察者之间松耦合.主题只知道观察者实现了某个接 ...
- POIUtils 导出 poi Test 100w 600w 条数据
依赖: <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-l ...
- jvm(一)类加载器
1.jvm的生命周期结束的几种情况 a.执行了System.exit()方法 b.程序正常执行结束 c.程序在执行过程中遇到了异常或错误而异常终止 d.操作系统出现错误 2.类加载过程 加载:查找并加 ...
- LevelDB源码分析-Write
Write LevelDB提供了write和put两个接口进行插入操作,但是put实际上是调用write实现的,所以我在这里只分析write函数: Status DBImpl::Write(const ...
- Linux网络编程学习(九) ----- 消息队列(第四章)
1.System V IPC System V中引入的几种新的进程间通信方式,消息队列,信号量和共享内存,统称为System V IPC,其具体实例在内核中是以对象的形式出现的,称为IPC 对象,每个 ...
- C#生成树形结构泛型类
C#生成树形结构泛型类,使用方法: ToTree<ShowMessageUpdatesTableTreeViewModel>.ToDo(models) public class ToTre ...
- 虚拟机JVM
虚拟机组成:类加载器,运行时数据区,执行引擎 运行时数据区:堆,栈,方法区,程序计数器,本地方法栈 堆:对象实例 栈:入栈出栈,线程的执行 栈帧:一个方法一个 栈的结构:放 局部变量表,操作数栈,动态 ...