如何快速声明可用于目标c的常量 [英] how to declare a constant in swift that can be used in objective c
问题描述
如果我将swift常量声明为全局常量,例如:
if I declare the swift constant as a global constant like:
let a = "123"
,但是在目标c 中找不到a
.
如何解决这个问题?
推荐答案
来自Apple Doc:
From Apple Doc:
只要与Objective-C兼容,您就可以访问标有@objc属性的类或协议中的任何内容.这不包括仅Swift的功能,例如此处列出的功能:
You’ll have access to anything within a class or protocol that’s marked with the @objc attribute as long as it’s compatible with Objective-C. This excludes Swift-only features such as those listed here:
- 泛型
- 故事
- 在Swift中定义的枚举
- 在Swift中定义的结构
- 在Swift中定义的顶级功能
- 在Swift中定义的全局变量
- 在Swift中定义的类型别名
- 快速样式的变数
- 嵌套类型
- 当前功能
- Generics
- Tuples
- Enumerations defined in Swift
- Structures defined in Swift
- Top-level functions defined in Swift
- Global variables defined in Swift
- Typealiases defined in Swift
- Swift-style variadics
- Nested types
- Curried functions
因此无法访问Swift中定义的全局变量(常量)或全局函数.
Therefore its not possible to access global variables(Constants) or global functions defined in Swift.
可能的解决方案:
From the Apple Document Swift programming language, You can Declare Type Properties as
class var constant: Int = {
return 10
}()
但是目前在Swift(beta-3)中,不支持 类型属性 .
But currently in Swift(beta-3) Type properties are not supported.
您可以声明一个Class函数以获得一个常量值:
You can declare a Class function to get a constant value:
在Swift中:
class func myConst() -> String {
return "Your constant"
}
从Objective-C访问:
NSString *constantValue = [ClassName myConst];
NSLog(@"%@", constantValue);
这篇关于如何快速声明可用于目标c的常量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!