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.
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");
would create a constnat called IntroTitle with the value IntroTitle that I could refer to within my code (autocomplete and all).
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.
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.
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 = ...
. 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
. This isn't very useful though, and I do not recommend using it. In swift, you have to explicitly type out your variable definitions.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.