Tips
Swift 并不强制要求你在每条语句的结尾处使用分号
变量常量声明
var myVariable:Int;
myVariable = 13;
let myConstant:Int = 13;
let emptyArray = [String]()
let emptyDictionary = [String: Float]()
控制流
1.使用if
和switch
来进行条件操作,使用for in
、for
、while
和repeat while
来进行循环
2.swift使用..<
来表示范围,..<
的意思是<
,...
的意思是<=
比如
var firstForLoop = 0
for i in 0..<4 {
firstForLoop += i
}
print(firstForLoop)
函数和闭包
函数:使用func
来声明一个函数,使用名字和参数来调用函数。使用->
来指定函数返回值的类型
普通例子:
func greet(name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
greet("Bob", day: "Tuesday")
返回类型为元组
(函数返回多个值):
func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0
for score in scores {
if score > max {
max = score
} else if score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics([5, 3, 100, 3, 9])
print("statistics.sum:\(statistics.sum)")//120
print("statistics.1(max):\(statistics.1)")//100
print("statistics.0(min):\(statistics.0)")//3
函数可以带有可变个数的参数,这些参数在函数内表现为数组的形式:
func sumOf(numbers: Int...) -> Int {
var sum = 0
for number in numbers {
sum += number
}
return sum
}
sumOf()
sumOf(42, 597, 12)
函数可以作为返回值(return Int -> Int不理解,不是return func?
)
func makeIncrementer() -> (Int -> Int) {
func addOne(number: Int) -> Int {
return 1 + number
}
return addOne
}
var increment = makeIncrementer()
increment(7)
函数实际上是一种特殊的闭包:它是一段能之后被调取的代码。闭包中的代码能访问闭包所建作用域中能得到的变量和函数,即使闭包是在一个不同的作用域被执行的 - 你已经在嵌套函数例子中所看到。你可以使用{}来创建一个匿名闭包。使用in将参数和返回值类型声明与闭包函数体进行分离。
numbers.map({
(number: Int) -> Int in
let result = 3 * number
return result
})
更简洁的写法(单个语句闭包会把它语句的值当做结果返回)
let mappedNumbers = numbers.map({ number in 3 * number })
print(mappedNumbers)
类(Class)
1.类的声明
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
2.类的实例化
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
3.类的构造方法
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
1.用
self
关键字来区别实例变量
2.如果你需要在删除对象之前进行一些清理工作,使用deinit
创建一个析构函数
子类的定义方法是在它们的类名后面加上父类的名字,用冒号分割,比如
class Square: NamedShape
子类如果要重写父类的方法的话,需要用override
标记
4.类属性的getter
跟setter
class EquilateralTriangle: NamedShape {
var sideLength: Double = 0.0
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides = 3
}
var perimeter: Double {
get {
return 3.0 * sideLength
}
set {
sideLength = newValue / 3.0
}
}
override func simpleDescription() -> String {
return "An equilateral triagle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
在perimeter的
setter
中,新值的名字是newValue
。你可以在set
之后显式的设置一个名字,诸如set(_perimeter:Double) { sideLength = newValue / 3.0}
枚举跟结构体
1.初始化枚举
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.rawValue)
}
}
}
let ace = Rank.Ace
print(ace)//Ace
let aceRawValue = ace.rawValue
print(aceRawValue)//1
let aceDescription = ace.simpleDescription()
print(aceDescription)//ace
2.使用struct来创建一个结构体。结构体和类有很多相同的地方,比如方法和构造器。它们之间最大的一个区别就是结构体是传值,类是传引用
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
//.Three代表的是 Rank.Three Spades代表的是 Suit.Spades
let threeOfSpades = Card(rank: .Three, suit: .Spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
协议和扩展
1.使用protocol
来声明一个协议
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
2.类、枚举和结构体都可以实现协议
class SimpleClass: ExampleProtocol {
var simpleDescription: String = "A very simple class."
var anotherProperty: Int = 69105
func adjust() {
simpleDescription += " Now 100% adjusted."
}
}
var a = SimpleClass()
a.adjust()
let aDescription = a.simpleDescription
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
3.使用extension来为现有的类型添加功能
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)//The number 7