Swift笔记-下标脚本

语法

定义下标脚本使用subscript关键字,显式声明入参(一个或多个)和返回类型。

1
2
3
4
5
6
7
8
9
subscript(index: Int) -> Int {
get {
// 用于下标脚本值的声明
}
set(newValue) {
// 执行赋值操作
}
}

Swift笔记-方法

实例方法

在 Swift 语言中,实例方法是属于某个特定类、结构体或者枚举类型实例的方法。
实例方法提供以下方法:

  • 可以访问和修改实例属性
  • 提供与实例目的相关的功能

实例方法要写在它所属的类型的前后大括号({})之间。
实例方法能够隐式访问它所属类型的所有的其他实例方法和属性。
实例方法只能被它所属的类的某个特定实例调用。
实例方法不能脱离于现存的实例而被调用。

Swift笔记-属性

存储属性

1
2
3
4
5
6
7
8
9
10
11
12
13
import Cocoa

struct Number
{
var digits: Int
let pi = 3.1415
}

var n = Number(digits: 12345)
n.digits = 67

print("\(n.digits)")
print("\(n.pi)")

Swift笔记-枚举

Swift 的枚举类似于 Objective C 和 C 的结构,枚举的功能为:

  • 它声明在类中,可以通过实例化类来访问它的值。
  • 枚举也可以定义构造函数(initializers)来提供一个初始成员值;可以在原始的实现基础上扩展它们的功能。
  • 可以遵守协议(protocols)来提供标准的功能。

语法

1
2
3
enum enumname {
// 枚举定义放在这里
}

Swift笔记-闭包

sorted 方法

排序闭包函数类型需为(String, String) -> Bool。

1
2
3
4
5
6
7
8
9
10
11
import Cocoa

let names = ["AT", "AE", "D", "S", "BE"]

// 使用普通函数(或内嵌函数)提供排序功能,闭包函数类型需为(String, String) -> Bool。
func backwards(s1: String, s2: String) -> Bool {
return s1 > s2
}
var reversed = names.sorted(by: backwards)

print(reversed)

Swift笔记-函数

函数的定义与调用

1
2
3
4
5
6
func sayHelloAgain(personName: String) -> String {
return "Hello again, " + personName + "!"
}

print(sayHelloAgain(personName: "Anna"))
// prints "Hello again, Anna!"

函数参数与返回值

无参函数

1
2
3
4
5
func sayHelloWorld() -> String {
return "hello, world"
}
print(sayHelloWorld())
// prints "hello, world"

Swift笔记-控制流

For循环

For-In

你可以使用for-in循环来遍历一个集合里面的所有元素

1
2
3
4
5
6
7
8
for index in 1...5 {
print("\(index) times 5 is \(index * 5)")
}
// 1 times 5 is 5
// 2 times 5 is 10
// 3 times 5 is 15
// 4 times 5 is 20
// 5 times 5 is 25

如果你不需要知道区间序列内每一项的值,你可以使用下划线(_)替代变量名来忽略对值的访问:

1
2
3
4
5
6
7
8
let base = 3
let power = 10
var answer = 1
for _ in 1...power {
answer *= base
}
print("\(base) to the power of \(power) is \(answer)")
// 输出 "3 to the power of 10 is 59049"

Swift笔记-集合类型

Swift 语言提供Arrays、Sets和Dictionaries三种基本的集合类型用来存储集合数据。

数组

创建一个空数组

1
2
3
var someInts = [Int]()
print("someInts is of type [Int] with \(someInts.count) items.")
// 打印 "someInts is of type [Int] with 0 items."

创建一个带有默认值的数组

1
2
var threeDoubles = [Double](count: 3, repeatedValue:0.0)
// threeDoubles 是一种 [Double] 数组,等价于 [0.0, 0.0, 0.0]