如何快速声明可用于目标c的常量 [英] how to declare a constant in swift that can be used in objective c

查看:89
本文介绍了如何快速声明可用于目标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:

  1. 泛型
  2. 故事
  3. 在Swift中定义的枚举
  4. 在Swift中定义的结构
  5. 在Swift中定义的顶级功能
  6. 在Swift中定义的全局变量
  7. 在Swift中定义的类型别名
  8. 快速样式的变数
  9. 嵌套类型
  10. 当前功能
  1. Generics
  2. Tuples
  3. Enumerations defined in Swift
  4. Structures defined in Swift
  5. Top-level functions defined in Swift
  6. Global variables defined in Swift
  7. Typealiases defined in Swift
  8. Swift-style variadics
  9. Nested types
  10. Curried functions

因此无法访问Swift中定义的全局变量(常量)或全局函数.

Therefore its not possible to access global variables(Constants) or global functions defined in Swift.

可能的解决方案:

  1. 从Apple文档

  1. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆