简体   繁体   English

如何使用Typealias或Closure快速定义带有参数的常量?

[英]How to use a Typealias or Closure to define a constant with a parameter for name in swift?

In Objective CI used to define constants using #defines as a way to quickly and explicitly define strings for localization and keep the code a little more clean. 在Objective CI中,使用#defines定义常量是一种快速而明确地定义本地化字符串并使代码保持清晰的方式。

For example: 例如:

#define DefineStringKey(x) static NSString *const x = @#x

This would let me define in constants that are named the same as the string so DefineStringKey(@"IntroTitle"); 这样,我就可以在与字符串相同的名称中定义常量,因此DefineStringKey(@"IntroTitle"); would create a constnat called IntroTitle with the value IntroTitle that I could refer to within my code (autocomplete and all). 将创建一个名为IntroTitle与价值IntroTitle,我可以参考我的代码中(自动完成和所有)constnat。

I had an idea that I might be able to do the same in Swift but I can't seem to get the syntax correct using typealias or closures. 我有个想法,我也许可以在Swift中做同样的事情,但是我似乎无法使用Typealias或Closures获得正确的语法。

Type Alias 类型别名

typealias DefineStringKey:(x:String) = let x:String = x 

Closure 关闭

let DefineStringKey:(String) = (String) -> () {
   (x:String) in
   let x:(String) = x
}

Clearly both examples I gave are incorrect. 显然,我给出的两个例子都是错误的。 Is this something I can do in Swift via another method or is my syntax just off. 这是我可以通过另一种方法在Swift中完成的事情还是我的语法刚刚结束。

Edited to add a use case. 编辑以添加用例。

Unfortunately, Swift does not have macros, so you cannot define a constant (or variable) without writing out let myConstant = ... . 不幸的是, Swift没有宏,因此您必须先定义let myConstant = ...才能定义一个常量(或变量)。 What you can do is use a closure to define a constant that you can use within the closure's inner scope: 您可以做的是使用闭包定义一个常量,您可以在闭包的内部范围内使用它:

func defineStringKey(_ key: String, handler: (String) -> Void) {
    handler(key)
}

Put that anywhere in the global scope, and you can use it like this: 将其放在全局范围内的任何地方,就可以像这样使用它:

defineStringKey("IntroTitle") { IntroTitle in
    print(IntroTitle)
}

That prints out IntroTitle . 那会打印出IntroTitle This isn't very useful though, and I do not recommend using it. 不过,这不是很有用,我不建议您使用它。 In swift, you have to explicitly type out your variable definitions. 快速地,您必须明确输入变量定义。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM