目标c中的Swift全局函数和全局函数 [英] Swift globals and global functions in objective c
问题描述
$ b
在C语言和Objective-C源文件中定义的全局常量由Swift编译器自动导入,作为Swift全局常量。
但它没有提到任何其他方法。我需要定义一个全局快速常量,并且能够像全局常量一样看到它的一个目标c侧。像在快捷方面定义:
public let CARDS = [card1,card2]
code>
并且看到在目标c方面使用它像
NSLog(@卡数:%d,[卡数])
<我应该怎么做?我已经导入了swift自动生成的头文件,如:
#importMyProject-Swift.h
并且在Xcode中如果我命令点击
就可以了我在swift代码中的正确位置,但在编译时我得到:
'未声明标识符卡的用户'
在我的客观c方面。
您可以访问类或协议中的任何内容b $ b用@objc属性标记,只要它与
Objective-C兼容即可。这不包括Swift-only特性,例如这里列出的
:
$ b
- 泛型
- 元组
- 在Swift中定义的枚举
- 在Swift中定义的结构
- 在Swift中定义的顶级函数
- Swift中定义的全局变量
- Swift中定义的类型别
- Swift风格的变量
- 嵌套类型
- 咖喱函数
全局变量(包括常量)无法从Objective-C访问。
相反,您必须声明一个具有全局常量访问器的类。
// Swift
public let CARDS = [card1,card2]
@objc class AppConstant {
private init(){} $ b $ class func cards() - > [String] {return CARDS}
}
// Objective-C
NSArray * cards = [AppConstant cards];
the documentation says:
Global constants defined in C and Objective-C source files are automatically imported by the Swift compiler as Swift global constants.
But it doesn't say anything about the other way around. I need to define a global swift constant and be able to see it one the objective c side like a global c constant. Like on the swift side define:
public let CARDS = ["card1", "card2"]
and see use it on the objective c side like
NSLog(@"Cards count: %d", [CARDS count])
What should I do? I've already imported the swift automatically generated header like:
#import "MyProject-Swift.h"
and in Xcode if I command-click
on it, it takes me to the correct place in the swift code, but at compile time I get:
'User of undeclared Identifier CARDS'
on my objective c side.
Here is the document about it
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
Global variables (including constants) are unaccessible from Objective-C.
Instead, you have to declare a class which has accessors for the global constants.
// Swift
public let CARDS = ["card1", "card2"]
@objc class AppConstant {
private init() {}
class func cards() -> [String] { return CARDS }
}
// Objective-C
NSArray *cards = [AppConstant cards];
这篇关于目标c中的Swift全局函数和全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!