Swift 宏

包含了一系列对我个人项目有用的宏。

用法

Symbol (符号)

let symbol = #symbol("swift") // Macro expands to "swift"

如果提供的值不是有效的 SF Symbol,Xcode 将显示编译错误。

URL

let url = #URL("https://swiftlang.cn") // Macro expands to URL(string: "https://swiftlang.cn")!

如果提供的值不是有效的 URL,Xcode 将显示编译错误。

AssociatedValues (关联值)

添加变量以检索关联的值。

@AssociatedValues
enum Barcode {
  case upc(Int, Int, Int, Int)
  case qrCode(String)
}

// Expands to
enum Barcode {
  ...

  var upcValue: (Int, Int, Int, Int)? {
    if case let .upc(v0, v1, v2, v3) = self {
        return (v0, v1, v2, v3)
    }
    return nil
  }

  var qrCodeValue: (String)? {
    if case let .qrCode(v0) = self {
        return v0
    }
    return nil
  }
}

Singleton (单例)

为结构体和类生成单例代码。

@Singleton
struct UserStore {
}

// Expands to
struct UserStore {
  static let shared = UserStore()

  private init() {
  }
}