Swift中的偏僻知识

102 阅读1分钟

可以使用模式匹配语法匹配errorcode

oleb.net/2023/catch-…

模式匹配语法操作符是 ~=。Swift中switch语法、if case let语法等都是使用的~=操作符进行匹配

Foundation框架重载了~=,从而让我们可以在catch语句中直接匹配错误的code码

do {
    let fileURL = URL(filePath: "/abc") // non-existent file
    let data = try Data(contentsOf: fileURL)
// 这里的这句代码完全可以写成👇🏻那样。简短了不少
// } catch let error as CocoaError where error.code == .fileReadNoSuchFile {
} catch CocoaError.fileReadNoSuchFile {
    print("File doesn't exist")
} catch {
    print("Other error: (error)")
}

static 修饰的变量默认是lazy的,只有使用的时候才初始化

www.swiftwithvincent.com/blog/hidden…

import Foundation
class EventsViewModel {
    static var dateFormatter: DateFormatter = {
        print("static var dateFormatter is initialized")
        let formatter = DateFormatter()
        formatter.dateStyle = .medium
        formatter.timeStyle = .short
        return formatter
    }()

    static let name: String = {
        print("static let name is initialized")
        return "my name"
    }()

    init() {
        print("EventsViewModel is initizlied")
    }
}

  1. 初始化实例,仅输出init中的print内容
private let model = EventsViewModel()
// EventsViewModel is initizlied
  1. 使用static的var和let变量,才会输出对应懒加载的print。不使用则不输出
_ = EventsViewModel.dateFormatter
// static var dateFormatter is initialized

_ = EventsViewModel.name
// static let name is initialized

类方法默认是动态派发,但函数的默认参数是编译期静态决定

class A {
    func f(value: Int = 10) {
        print("A: \(value)")
    }
}

class B: A {
    override func f(value: Int = 100) {
        print("B: \(value)")
    }
}

let b: A = B()
b.f()

如上代码,最终的输出是 B: 10,调用了B类的方法,但是默认值时A类中f方法的默认值10