我在 Swift 中有一个静态库,我想从另一个 Swift 项目访问这个库类。无法正确引用库中的类。
我的名为 StaticLib
的静态库包含层次结构,
静态库项目 - 层次结构
StaticLib (project)
StaticLib
StaticLib.swift
Products
libStaticLib.a
静态库项目 - StaticLib.swift
public class StaticLib {
public class func test(string: String) {
Printer().printMe(string: string)
}
}
class Printer {
func printMe(string: String){
print("This is test tring: \(string)")
}
}
宿主应用程序 - AppDelegate.swift
import StaticLib
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
StaticLib.test("How do you do?") // error
return true
}
}
我已经完成的步骤-
- 在 Xcode Project Navigator 中单击项目
- 点击+添加新目标
- 选择框架和库>静态库>下一步
- 输入名称
StaticLib
(在 Swift 中)> 完成 - 打开 StaticLib.swift 并输入
public class StaticLib {
public class func test(string: String) {
Printer().printMe(string: string)
}
}
class Printer {
func printMe(string: String){
print("This is test tring: \(string)")
}
}
- 选择
StaticLib
架构,Build > OK - 将
libStaticLib.a
复制到名为HostApp/Libs/
的新文件夹中 - 在 Project Navigator 中选择项目 > 点击 main application target > 选择 General
- 在Framework, Libraries, and Embedded Content部分点击我看到
libStaticLib.a
is already added by Xcode intelligence - 选择主应用架构 > 构建 > 确定
- 选择 AppDelegate.swift > 添加
import StaticLib
- 添加
StaticLib.test("How do you do?")
- 尝试构建
编译错误:
Use of unresolved identifier 'StaticLib'
我该如何解决这个问题?我需要在库中创建任何头文件吗?
注意:我已经成功嵌入了 libStaticLib.a
,它出现在主机应用程序 General -> Frameworks, Libraries and Embedded contents
选项卡中.
最佳答案
我已经通过了您的步骤和所有工作,至少在 Xcode 11.3.1/iOS 13.3 上是这样。唯一……好像……看评论
import StaticLib // << looks like you've forgot this one !!!
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
StaticLib.test("How do you do?") // error
return true
}
}
更新:这是我的步骤-
- 在 Xcode Project Navigator 中单击项目
- 点击+添加新目标
- 选择框架和库>静态库>下一步
- 输入名称
StaticLib
(在 Swift 中)> 完成 - 打开 StaticLib.swift 并输入
public class StaticLib {
public class func printme() {
print("I'm swfit static lib!")
}
}
- 选择
StaticLib
架构,Build > OK - 在 Project Navigator 中选择项目 > 点击 main application target > 选择 General
- 在框架、库和嵌入内容部分点击+并选择
libStaticLib.a
> 添加 - 选择主应用架构 > 构建 > 确定
- 选择 AppDelegate.swift > 添加
import StaticLib
- 在代码的任意位置添加
StaticLib.printme()
- 构建 > 确定 > 运行 ... 查看输出
Update2: 用于外部 Lib 项目
+1 需要将StaticLib.swiftmodule
(它和libStaticLib.a创建在同一个地方)复制到目标项目文件夹中(我把它放在.xcodeproj级别
文件)
+2 在主应用程序目标 Build Settings
中设置 SWIFT_INCLUDE_PATHS = ${SRCROOT}
+3 清洁 > 构建
注意:模块加载的指示器是导入的自动完成 - 它应该显示 StaticLib
关于ios - 如何从纯 Swift 项目访问纯 Swift 静态库?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59875615/