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

前端之家收集整理的这篇文章主要介绍了目标c – 目标c中的Swift全局变量和全局函数前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
文件说:

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];
原文链接:https://www.f2er.com/c/112446.html

猜你在找的C&C++相关文章