Objective-C call Swift function

北战南征 提交于 2019-12-06 05:12:17

问题


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()
  {

  }
}

回答1:


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

Reference.

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.



来源:https://stackoverflow.com/questions/40904250/objective-c-call-swift-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!