加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

目标c – 目标c中的Swift全局变量和全局函数

发布时间:2020-12-16 03:07:33 所属栏目:百科 来源:网络整理
导读:文件说: Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants. 但是,它并没有说出任何其他方式.我需要定义一个全局快捷常量,并且能够看到它像目标c一样像一个全局c常
文件说:

Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants.

但是,它并没有说出任何其他方式.我需要定义一个全局快捷常量,并且能够看到它像目标c一样像一个全局c常量.喜欢在swift侧定义:

public let CARDS = ["card1","card2"]

并且看到在客观c上使用它像

NSLog(@"Cards count: %d",[CARDS count])

我该怎么办?我已经导入swift自动生成的标题,如:

#import "MyProject-Swift.h"

并且在Xcode中,如果我命令单击它,它需要我到正确的地方在swift代码,但在编译时我得到:

'User of undeclared Identifier CARDS'

在我的目标c方面.

解决方法

Here is the document关于它

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:

  • 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

全局变量(包括常量)从Objective-C无法访问.

相反,您必须声明一个具有全局常量访问器的类.

// Swift
public let CARDS = ["card1","card2"]

@objc class AppConstant {
   private init() {}
   class func cards() -> [String] { return CARDS }
}

// Objective-C
NSArray *cards = [AppConstant cards];

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读