用于定义类型、函数或变量别名的 Swift 宏。
可以附加到类型、函数或变量的宏。
您可以按如下方式定义变量的别名
class SomeClass {
@Alias("title")
var text: String = "hello"
}
/* ↓↓↓↓↓ */
let someClass = SomeClass()
print(text) // => "hello"
print(title) // => "hello"
您可以按如下方式定义函数的别名。 这样,您既可以调用 hello("aaa", at: Date())
,也可以调用 こんにちは("aaa", at: Date())
。
class SomeClass {
@Alias("こんにちは")
func hello(_ text: String, at date: Date) {
/* --- */
print(text)
}
}
/* ↓↓↓↓↓ */
let someClass = SomeClass()
someClass.hello("aaa", at: Date()) // => "aaa"
someClass.こんにちは("aaa", at: Date()) // => "aaa"
参数标签也可以通过用“:”分隔来自定义。
class SomeClass {
@Alias("こんにちは::いつ")
func hello(_ text: String, at date: Date) {
/* --- */
print(text)
}
@Alias("こんにちは2:_:_") // Omit argument labels
func hello2(_ text: String, at date: Date) {
/* --- */
print(text)
}
@Alias("こんにちは3::宛") // The first argument label is inherited. The second is customized
func hello3(_ text: String, at date: Date, to: String) {
/* --- */
print(text)
}
}
/* ↓↓↓↓↓ */
let someClass = SomeClass()
someClass.hello("aaa", at: Date()) // => "aaa"
someClass.こんにちは("aaa", いつ: Date()) // => "aaa"
someClass.hello2("aaa", at: Date()) // => "aaa"
someClass.こんにちは2("aaa", Date()) // => "aaa"
someClass.hello3("aaa", at: Date(), to: "you") // => "aaa"
someClass.こんにちは3("aaa", at: Date(), 宛: "あなた") // => "aaa"
您可以为枚举案例定义别名。
例如,假设我们定义如下内容。
enum Difficulty {
@Alias("beginner")
case easy
@Alias("normal")
case medium
@Alias("challenge")
case hard
@Alias("extreme")
case expert
@Alias("ultimate")
case master(level: Int)
}
此时,宏会扩展如下。
enum Difficulty {
case easy
case medium
case hard
case expert
case master(level: Int)
static let beginner: Self = .easy
static let normal: Self = .medium
static let challenge: Self = .hard
static let extreme: Self = .expert
static func ultimate(level: Int) -> Self {
.master(level)
}
}
protocol APIRequest {
@Alias("Reply")
associatedtype Response
}
↓↓↓
protocol APIRequest {
associatedtype Response
typealias Reply = Response
}
例如,通过编写以下内容,ViewController
也可以被引用为 VC
。(如果此宏用于类型,则会在内部简单地使用 typealias
定义。)
警告 在全局作用域中不能使用在
names
中任意指定的PeerMacro
。 任意名称的限制
@Alias("VC")
class ViewContoroller: UIViewController {
/* --- */
}
/* ↓↓↓↓↓ */
print(ViewContoroller.self) // => "ViewController"
print(VC.self) // => "ViewController"
可以通过添加多个宏来定义多个别名,如下所示
@Alias("hello")
@Alias("こんにちは")
var text: String = "Hello"
您可以按如下方式指定别名访问修饰符。
@Alias("hello", access: .public)
private var text: String = "Hello"
如果设置为“inherit”,它将从原始定义继承。
@Alias("hello", access: .inherit)
private var text: String = "Hello"
AliasMacro 根据 MIT 许可证发布。 请参阅 LICENSE