Swift4笔记-Tour

  • 之前版本
  • Swift4
  • 代码地址
    的Markdown怎样实现页内跳转???
    日常笔记,仅供参考

Simple Values

  • var
  • let
    常量
  • 声明类型
let explicitDouble: Double = 70
  • 类型转换1
let label = "The width is"
let width = 94
let widthLabel = label + String(width)
  • 类型转换2
let apples = 3
let oranges = 5
let appleSummary = "I have \(apples) apples."
let fruitSummary = "I have \(apples + oranges) pieces of fruit."
  • 数组和字典
var shoppingList = ["catfish", "water", "tulips", "blue paint"]
shoppingList[1] = "bottle of water"
     
var occupations = [
        "Malcolm": "Captain",
        "Kaylee": "Mechanic",
]
occupations["Jayne"] = "Public Relations"
  • 空数组、空字典
let emptyArray = [String]()
let emptyDictionary = [String: Float]()

Control Flow

  • ?
    在一个值的类型之后写一个问号?,以将值标记为可选,一个可选值包含一个值,或者包含一个nil
  • if let
    处理可能为空的值
var optionalName: String? = "John Appleseed"
var greeting = "Hello!"
if let name = optionalName {
    greeting = "Hello,\(name)"
}
else {
    print(greeting)
}
  • ??
    处理可选值,如果前面的值缺失则使用后面的值
let nickName: String? = nil
let fullName: String? = "John Appleseed"
let informalGreeting = "Hi \(nickName ?? fullName)"
  • switch语法
    支持任何类型的数据和各种比较操作
let vegetable = "red pepper"
switch vegetable {
case "celery":
    print("Add some raisins and make ants on a log.")
case "cucumber", "watercress":
    print("That would make a good tea sandwich.")
case let x where x.hasSuffix("pepper"):
    print("Is it a spicy \(x)?")
default:
    print("Everything tastes good in soup")
}
  • for-in迭代字典
let interestingNumbers = [
    "Prime" : [2, 3, 5, 7, 11, 13,],
    "Fibonacci" : [1, 1, 2, 3, 5, 8],
    "Square" : [1, 4, 9, 16, 25]
]

var largest = 0

for (kind, numbers) in interestingNumbers {
    for number in numbers {
        if number > largest {
            largest = number
        }
    }
}
print(largest)
  • while、repeat-while
    repeat-while确保循环至少执行一次
var n = 2
while n < 2 {
    n *= 2
}
print(n)

var m = 2
repeat {
    m *= 2
}while m < 2
print(m)
  • ..<和...
    ..<不包含最大值,...包含最大值
for i in 0..<4 {
    print(i)
}

for i in 0...4 {
    print(i)
}

Functions and Closures

  • 函数
func greet(person: String, day: String) -> String {
    return "Hello \(person), today is \(day)"
}
greet(person: "Bob", day: "Tuesday")
  • 函数-- 参数标签
    默认情况下,函数使用其参数名称作为参数的标签。 在参数名称之前编写自定义参数标签,或者写_不使用参数标签。
func greet2(_ person: String, on day: String) -> String {
    return "Hi \(person), today is \(day)"
}
greet2("John", on: "Wednesday")
  • 返回值为元组的函数
    元组的元素可以通过名称或数字来引用
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(scores: [5, 3, 100, 3, 9])
print(statistics.sum)
print(statistics.2)
  • 嵌套函数
    可以使用嵌套函数在长或复杂的函数中组织代码。
func returnFifteen() -> Int {
    var y = 10
    func add() {
        y += 5
    }
    add()
    return y
}
returnFifteen()
  • 返回值类型为函数的函数
func makeIncrementer() -> ((Int) -> Int) {
    func addOne(number: Int) -> Int {
        return 1 + number
    }
    return addOne(number:)
}
var increment = makeIncrementer()
increment(7)
  • 参数类型为函数的函数
//第一个参数为数组类型,第二个参数为函数类型
func hasAnyMatches(list: [Int], condition: (Int) -> Bool) -> Bool {
    for item in list {
        if condition(item) {
            return true
        }
    }
    return false
}

func lessThanTen(number: Int) -> Bool {
    return number < 10
}
var numbers = [20, 19, 7, 12]

//检测数组中是否有小于10的数字
hasAnyMatches(list: numbers, condition: lessThanTen(number:))

  • 闭包
    使用in将参数和返回类型与正文分开
let myNumbers = numbers.map({ (number: Int) -> Int in
    let result = 3 * number
    return result
})
print(myNumbers)
  • 闭包缩写
    省略参数或返回类型
let mappedNumbers = numbers.map({ number in 3 * number})
print(mappedNumbers)
  • 闭包缩写-- $0
    通过数字来引用参数,而不需要起名称,同时也可以省略外层括号()
let mappedNumbers2 = numbers.map({ 3 * $0})
print(mappedNumbers2)

//排序
let sortedNumbers = numbers.sorted {$0 > $1}
print(sortedNumbers)

Objects and Classes

  • 创建类
    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方法
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 namedShape = NamedShape(name: "tom")
namedShape.simpleDescription()
  • 类继承
  • 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 quare")
test.area()
test.simpleDescription()
  • 属性的get与set方法
    set之后新的属性值的隐含名称为newValue
class EqualateralTriangle: 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 = EqualateralTriangle(sideLength: 3.1, name: "a triangle")
print(triangle.perimeter)
triangle.perimeter = 9.9
print(triangle.sideLength)

也可以自己给新的值命名

class EqualateralTriangle: 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(myValue) {
            sideLength = myValue / 3.0
        }
    }
    
    override func simpleDescription() -> String {
        return "An equilateral triangle with sides of length \(sideLength)"
    }
}
  • willSet与didSet
    监视属性的除初始化之外的属性值变化
class TriangleAndSquare {
    var triangle: EqualateralTriangle {
        willSet {
            square.sideLength = newValue.sideLength
        }
    }
    var square: Square {
        willSet {
            triangle.sideLength = newValue.sideLength
        }
    }
    init(size: Double, name: String) {
        square = Square(sideLength: size, name: name)
        triangle = EqualateralTriangle(sideLength: size, name: name)
    }
    
}

var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")
print(triangleAndSquare.square.sideLength)
print(triangleAndSquare.triangle.sideLength)
triangleAndSquare.square = Square(sideLength: 50, name: "larger square")
print(triangleAndSquare.triangle.sideLength)
  • 可选值类型的对象
    点语法调用属性或方法
let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square")
let sideLength = optionalSquare?.sideLength

Enumerations and Structures

  • 枚举 (enum 枚举名: 枚举类型)
    Int类型枚举的默认原始值为0,可以通过显式指定值来更改
    如果不指定枚举类型,是不能使用rawValue属性的
enum Rank: Int {
    case ace = 3
    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.five
let aceRawValue = ace.rawValue
print(ace.simpleDescription())

enum rank {
    case one
    case two
}
let one = rank.one
//不指定类型的话 引用会报错
//let oneValue = one.rawValue
  • 枚举初始化 : 通过值 if let
    它返回与原始值匹配的枚举大小,如果没有匹配的等级,则返回nil。
if let convertedRank = Rank(rawValue: 4) {
    let threeDescription = convertedRank.simpleDescription()
    
}

if let convertedRank2 = Rank(rawValue: 15) {
    let threeDescription = convertedRank2.simpleDescription()
}
else {
    print("nil")
}
  • 可以不给枚举赋初始值
enum Suit {
    //黑桃 红桃 方块 梅花
    case spades, hearts, diamonds, clubs
    func simpleDescription() -> String {
        switch self {
        case .spades:
            return "spades"
        case .hearts:
            return "hearts"
        case .diamonds:
            return "diamonds"
        case .clubs:
            return "clubs"
        }
    }
    func color() -> String {
        switch self {
        case .spades, .clubs:
            return "blackColor"
        case .hearts, .diamonds:
            return "redColor"
        }
    }
}
let hearts = Suit.hearts
let heartDescription = hearts.simpleDescription()
let heartsColor = hearts.color()
  • 根据实际需求来确定枚举值的类型
    需要用到的时候提取数据
enum ServerResponse {
    case result(String, String)
    case failure(String)
    case disconnect(String)
}

let success = ServerResponse.result("6:00 am", "8:09 pm")
let failure = ServerResponse.failure("Out of cheese.")
let network = ServerResponse.disconnect("404")

switch network {
case let .result(sunrise, sunset):
    print("Sunrise is at \(sunrise) and sunset is at \(sunset).")
case let .failure(message):
    print("Failure... \(message)")
case let .disconnect(cause):
    print("Network failure \(cause)")
}
  • 结构体
    与类相似,不同点是当代码中传递结构时,始终会复制,而类是通过引用的方式传递。
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()

Protocols and Extensions

  • 协议
    类、结构体、枚举 都可以遵守
    mutating机构体遵守协议时使用
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

//结构体
struct SimpleStructure: ExampleProtocol {
    var simpleDescription: String = "A simple struture"
    mutating func adjust() {
        simpleDescription += "(adjusted)"
    }
}
var b = SimpleStructure()
b.adjust()
let bDescription = b.simpleDescription

//枚举
enum SimpleEnum: ExampleProtocol {
    mutating func adjust() {
        switch self {
        case let .Result(text):
            self = .Result(text + "(first case adjusted)")
        case let .Failure(text):
            self = .Failure(text + "(second case adjusted)")
        }
    }

    case Result(String)
    case Failure(String)
    
    var simpleDescription: String {
        get {
            switch self {
            case .Result("123"):
                return "13"
            case .Failure("李"):
                return "李"
            default:
                return "get error"
            }
        }
        set {
            switch self {
            case .Result("123"):
                self = .Result("12")
            case .Failure("李"):
                self = .Failure("312")
            default:
                self = .Failure("3333")
            }
        }
    }
}

var enumConformToProtocolTest = SimpleEnum.Failure("李")
enumConformToProtocolTest.adjust()
print("\(enumConformToProtocolTest)")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.simpleDescription = "test"

enumConformToProtocolTest = SimpleEnum.Result("ThirdVal")
enumConformToProtocolTest.simpleDescription
enumConformToProtocolTest.adjust()
enumConformToProtocolTest.simpleDescription
  • 扩展
    可以使现有的类型遵守协议,实现功能,包括系统类
extension Int: ExampleProtocol {
    var simpleDescription: String {
        return "The number \(self)"
    }
    mutating func adjust() {
        self += 42
    }
}
var textExtension = 7
textExtension.simpleDescription
textExtension.adjust()
textExtension.simpleDescription
  • 当使用类型为协议类型的值时,协议定义之外的方法不可用。会报错
let protocolValue: ExampleProtocol = a
print(protocolValue.simpleDescription)
//print(protocolValue.anotherProperty)

Error Handling

  • Error协议
    通过继承该协议来创建处理异常的枚举
enum PrinterError: Error {
   case outOfPaper
   case noToner
   case onFire
}
  • throws
    构建可能抛出异常的函数时使用
  • throw
    可以抛出异常
func mySend(job: Int, toPrinter printerName: String) throws -> String {
    if printerName == "Never Has Toner" {
        throw PrinterError.noToner
    }
    else if printerName == "Gutenberg" {
        throw PrinterError.outOfPaper
    }
    else if printerName == "Dongdong" {
        throw PrinterError.onFire
    }
    return "Job sent"
}
  • try
    标记可能抛出异常的代码
  • do-catch语句
    do块:写try语句
    catch块:异常处理
do {
    try mySend(job: 5, toPrinter: "Never Has Toner")
} catch {
    print(error)
}

do {
    try mySend(job: 5, toPrinter: "Bi sheng")
} catch {
    print(error)
}
  • 多个catch块
    与switch类似,处理错误
do {
    try mySend(job: 15, toPrinter: "Gutenberg")
} catch PrinterError.outOfPaper {
    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?
    将结果转换为可选项。 如果函数抛出错误,则特定的错误被丢弃,结果为nil。否则,结果是可选的。
let printerSuccess = try? mySend(job: 1884, toPrinter: "Mergenthaler")
let printerFailure = try? mySend(job: 1885, toPrinter: "Never Has Toner")
  • defer
    延缓执行,调用顺序为自下往上
func lookforSomething(name: String) throws {
    print("1-1")
    
    if name == "" {
        print("2-1")
        defer {
            print("2-2")
        }
        print("2-3")
    }
    print("1-2")
    defer {
        print("1-3")
    }
    print("1-4")
    
    if name == "hello" {
        print("3-1")
        defer {
            print("3-2")
        }
        print("3-3")
        defer {
            print("3-4")
        }
    }
    
    defer {
        print("5-1")
    }
}
print("--------")
try? lookforSomething(name: "")
print("--------")
try? lookforSomething(name: "hello")

Generics

  • <>
  • 泛型参数
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
    文档中的代码没理解

你可能感兴趣的:(Swift4笔记-Tour)