对象和类
使用class关键字,加类名
class Shape {
var numberOfSides = 0
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
创建对象的引用,并调用类的参数和方法。
var shape = Shape()
shape.numberOfSides = 7
var shapeDescription = shape.simpleDescription()
带init()的类,self.name表示类自身的属性。
class NamedShape {
var numberOfSides: Int = 0
var name: String
init(name: String) {
self.name = name
}
func simpleDescription() -> String {
return "A shape with \(numberOfSides) sides."
}
}
实例化是必须要为参数赋值。
var nameShape = NamedShape(name:"zhang")
print(nameShape.name)
实现子类,用override关键字覆盖父类方法。
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")
print(test.area())
print(test.simpleDescription())
定义参数的getter和setter方法,setter时的newValue为隐式参数。
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 triangle with sides of length \(sideLength)."
}
}
var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)
willSet执行setter前调用 ,didSet执行setter后调用,oldValue为setter之前的值。
class TriangleAndSquare {
var square: Square {
willSet {
triangle.sideLength = newValue.sideLength
}
didSet{
print("\(oldValue.sideLength);\( triangle.sideLength)")
}
}
init(size: Double, name: String) {
square = Square(sideLength: size, name: name)
triangle = EquilateralTriangle(sideLength: size, name: name)
}
}
var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
可选值类,如果?前面是nil,后面的就不执行
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength
print(sideLength!)
枚举和数据结构
使用enum定义枚举,rawValue默认从0开始,然后依次加1.但是在这里第一个枚举的rawValue被指定为1,因此从1开始依次加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
let aceRawValue = ace.rawValue
print(aceRawValue)
print(Rank.two.simpleDescription())
使用 init?(rawValue:) 初始化枚举
Rank(rawValue: 3)?.simpleDescription()
可自定义value的枚举
enum ServerResponse {
case result(String, String)
case failure(String)
}
let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
switch success {
case let .result(sunrise, sunset):
print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
print("Failure... \(message)")
}
数据结构
用struct关键字创建数据结构,数据结构支持很多类似类的行为,如方法,初始构造器。数据结构和类的最大不同之处是,在代码中传递时,类传的时引用,而数据结构时拷贝。
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
}
let threeOfSpades = Card(rank: .three, suit: .spades)
let threeOfSpadesDescription = threeOfSpades.simpleDescription()
协议和扩展
协议
使用protocol关键字声明一个协议
protocol ExampleProtocol {
var simpleDescription: String { get }
mutating func adjust()
}
类,枚举,数据结构都可以适配协议
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
print(aDescription)
struct SimpleStructure: ExampleProtocol {
var simpleDescription: String = "A simple structure"
mutating func adjust() {
simpleDescription += " (adjusted)"
}
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription
print(bDescription)
enum cDescription:ExampleProtocol{
case First(String),Second(String)
var simpleDescription: String{
set{
switch self {
case let .First(text):
self = .First(newValue)
case let .Second(text):
self = .Second(newValue)
}
}
get{
switch self {
case let .First(text):
return text
case let .Second(text):
return text
}
}
}
mutating func adjust() {
switch self {
case let .First(text):
self = .First(text+" enum (adjust)")
case let .Second(text):
self = .Second(text+" enum (adjust)")
}
}
}
var c = cDescription.First("zhang")
c.adjust()
print(c)
注意:mutating关键字,让方法可以修改数据结构和枚举自身。类不需要声明mutating,是因为类的方法可以修改类。
扩展
使用extension关键字,可以给已有的类型加上函数
extension Int: ExampleProtocol {
var simpleDescription: String {
return "The number \(self)"
}
mutating func adjust() {
self += 42
}
}
print(7.simpleDescription)
错误处理
继承Error协议的任何类型
enum PrinterError: Error {
case outOfPaper
case noToner
case onFire
}
用throw抛出异常,throws 让函数可以抛出异常
func send(job: Int, toPrinter printerName: String) throws -> String {
if printerName == "Never Has Toner" {
throw PrinterError.noToner
}
return "Job sent"
}
错误处理
使用do-catch 抛出异常。在代码前用try抛出代码的异常
do{
print(try send(job:1, toPrinter:"Never Has Toner"))
}catch{
print(error)
}
多个catch块
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.")
} catch let printerError as PrinterError {
print("Printer error: \(printerError).")
} catch {
print(error)
}
使用try? 把结果转换为Optional。如果抛出异常就返回nil
let printerSuccess = try? send(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? send(job: 1885, toPrinter: "Never Has Toner")
defer
在函数中使用defer代码块,当函数的其他代码执行完后再执行。defer可以用来做每次代码执行的清理或设置
var fridgeIsOpen = false
let fridgeContent = ["milk", "eggs", "leftovers"]
func fridgeContains(_ food: String) -> Bool {
fridgeIsOpen = true
defer {
fridgeIsOpen = false
}
let result = fridgeContent.contains(food)
return result
}
fridgeContains("banana")
print(fridgeIsOpen)
范型
定义一个范型函数
func makeArray- (repeating item: Item, numberOfTimes: Int) -> [Item] {
var result = [Item]()
for _ in 0..
可以用相同的形式定义一个枚举,类,数据结构。
enum OptionalValue {
case none
case some(Wrapped)
}
var possibleInteger: OptionalValue = .none
possibleInteger = .some(100)
在函数体的右边使用where,指定一个需求列表。如指定实现协议的类型,两个枚举的类型是相同的,或有指定的父类。
func anyCommonElements(_ lhs: T, _ rhs: U) -> Bool
where T.Iterator.Element: Equatable, T.Iterator.Element == U.Iterator.Element {
for lhsItem in lhs {
for rhsItem in rhs {
if lhsItem == rhsItem {
return true
}
}
}
return false
}
anyCommonElements([1, 2, 3], [3])
无戒365挑战营 49