func calculateStatistics(scores: [Int]) -> (min: Int, max: Int, sum: Int) {
var min = scores[0]
var max = scores[0]
var sum = 0for score in scores {
if score > max {
max = score
} elseif score < min {
min = score
}
sum += score
}
return (min, max, sum)
}
let statistics = calculateStatistics(scores:[5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
对象和类
使用 class 和类名来创建一个类。类中属性的声明和常量、变量声明一样,唯一的区别就是它们的上下文是类。同样,方法和函数声明也一样。
class Square: NamedShape {
var sideLength: Double
init(sideLength: Double, name: String) {
self.sideLength = sideLength
super.init(name: name)
numberOfSides =4
}
func area() -> Double {
return sideLength * sideLength
}
override func simpleDescription() -> String {
return"A square with sides of length \(sideLength)."
}
}
let test = Square(sideLength: 5.2, name: "my test square")
test.area()
test.simpleDescription()
枚举和结构体
使用 enum 来创建一个枚举。就像类和其他所有命名类型一样,枚举可以包含方法
enum Rank: Int {
case ace = 1casetwo, three, four, five, six, seven, eight, nine, tencase 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
let aceRawValue = ace.rawValue
协议和扩展
类、枚举和结构体都可以实现协议。
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
错误处理
do {
let printerResponse = try send(job: 1440, toPrinter: "Gutenberg")
print(printerResponse)
} catch PrinterError.onFire {
print("I'll just put this over here, with the rest of the fire.")
} catchlet printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
泛型
在尖括号里写一个名字来创建一个泛型函数或者类型。
func repeatItem<Item>(repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in0..<numberOfTimes {
result.append(item)
}
returnresult
}
repeatItem(repeating: "knock", numberOfTimes:4)