如何从纯 Swift 项目访问纯 Swift 静态库?

How to access pure Swift Static Library from pure Swift project?

我在 Swift 中有一个静态库,我想从另一个 Swift 项目访问这个库 class。无法正确引用库中的class。

我的名为 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
    }
}

我完成的步骤 -

  1. 在 Xcode 项目导航器中单击项目
  2. 点击+添加新目标
  3. Select 框架与库 > 静态库 > 下一步
  4. 输入姓名StaticLib(在Swift)>完成
  5. 打开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)")
        }
    }
  1. Select StaticLib 架构,构建 > 确定
  2. libStaticLib.a 复制到名为 HostApp/Libs/
  3. 的新文件夹中
  4. Select Project Navigator 中的项目 > 单击主应用程序目标 > select 常规
  5. 框架、库和嵌入式内容 部分中,单击我看到 libStaticLib.a 已由 Xcode 智能
  6. 添加
  7. Select 主应用架构 > 构建 > 确定
  8. Select AppDelegate.swift > 添加 import StaticLib
  9. 添加
    StaticLib.test("How do you do?")
  1. 尝试构建

编译错误:

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
    }
}

更新:这是我的步骤-

  1. 单击 Xcode 项目导航器中的项目
  2. 点击+添加新目标
  3. Select 框架和库 > 静态库 > 下一步
  4. 输入名称StaticLib(在Swift)>完成
  5. 打开StaticLib.swift并输入
    public class StaticLib {
        public class func printme() {
            print("I'm swfit static lib!")
        }
    }
  1. Select StaticLib 架构,构建 > 确定
  2. Select Project Navigator 中的项目 > 单击主应用程序目标 > select 常规
  3. 框架、库和嵌入内容 部分中,单击 + 和 select libStaticLib.a > 添加
  4. Select 主应用架构 > 构建 > 确定
  5. Select AppDelegate.swift > 添加 import StaticLib
  6. 在代码的任意位置添加
    StaticLib.printme()
  1. 构建 > 确定 > 运行 ... 查看输出

Update2: 用于外部 Lib 项目

+1 需要复制StaticLib.swiftmodule(和libStaticLib.a在同一个地方创建)到目标项目文件夹(我放在.xcodeproj文件层)

+2 在主应用程序目标 Build Settings 中设置 SWIFT_INCLUDE_PATHS = ${SRCROOT}

+3 清理 > 构建

注意:模块加载的指标是导入自动完成 - 它应该显示 StaticLib