Objective-C调用Swift函数 [英] Objective-C call Swift function
问题描述
在 MySwift.swift中定义的Swift函数
文件:
func SomeSwift()
{
}
SomeSwift()
未在任何Swift类中定义,它只是一个纯函数。
CMD + B 来构建项目,打开 Project-Swift.h
, SomeSwift()
没有显示在那里。
是否必须在某些Swift类中定义Swift中的函数?并使用 @objc
标记?
如下所示:
@objc class SomeSwift:NSObject {
func SomeSwift()
{
}
}
参考
< blockquote>
@objc只能在课程成员,@ objc协议,
和课程的具体扩展时使用。
,建议删除 @objc
。
Swift function defined in MySwift.swift
File:
func SomeSwift()
{
}
SomeSwift()
is not defined in any Swift class, it is just a pure function.
After CMD + B to build the project, open Project-Swift.h
, the SomeSwift()
isn't show in there.
Does the function in Swift have to be defined in some Swift class? and with @objc
marked?
like the following:
@objc class SomeSwift: NSObject {
func SomeSwift()
{
}
}
Referring to Apple Documentation about Using Swift from Objective-C:
A Swift class must be a descendant of an Objective-C class to be accessible and usable in Objective-C
Means that your class should be @objc class SomeSwift: NSObject
(You're right!), but you CANNOT access the whole thing in Swift file:
When you create a Swift class that descends from an Objective-C class, the class and its members—properties, methods, subscripts, and initializers—that are compatible with Objective-C are automatically available from Objective-C. This excludes Swift-only features, such as those listed here:
Generics
Tuples
Enumerations defined in Swift without Int raw value type
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
So, you cannot use the SomeSwift
top-level function.
Even if you tried to add @objc
before its declaration, the compiler will tell that:
@objc can only used when with memebers of classes, @objc protocols, and concrete extensions of classes.
with a suggestion to remove @objc
.
这篇关于Objective-C调用Swift函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!