ios 在Swift上定义带有接口的包

svmlkihl  于 2023-01-06  发布在  iOS
关注(0)|答案(1)|浏览(126)

我在C#和Java等语言方面有更多的经验,所以也许我问错了问题,但我试图用接口定义Swift包,因此任何实现该接口包例如,在数据访问包上,我想用CRUD方法定义一个接口,这样如果我用另一种类型更改DB,其余的代码不会受到影响。如果这是可能的?如果答案是“是”,哪种方法是实现这一目标的最佳方法?

xzabzqsa

xzabzqsa1#

你可以创建两个单独的swift包。一个包只是协议(接口),另一个包是符合协议的结构或类(实现)。例如...
接口包

public protocol SomeInterface {
     func doSomething()
}

和实施包

public struct SomeImplementation: SomeInterface {
     func doSomething() {
          //stuff happens here
     }
}

实现程序包必须将接口程序包作为依赖项包含在Package.swift文件中

dependencies: [
    // Dependencies declare other packages that this package depends on.
    .package(url: "https://example.com/some-interface.git", from: "1.2.3"),
 ],
 targets: [
    // Targets are the basic building blocks of a package. A target can define a module or a test suite.
    // Targets can depend on other targets in this package, and on products in packages this package depends on.
    .target(
        name: "SomeImplementation",
        dependencies: ["SomeInterface"]),
    .testTarget(
        name: "SomeImplementation Tests",
        dependencies: ["SomeImplementation"]),
 ]

然后,您可以注入符合协议的实现,而只需要将协议包添加到模块中。

init(dependency: SomeInterface) {
     dependency.doSomething()
}

这样,只要接口包没有任何重大更改,您的实现包就可以随着版本更新而发展,而不必更新项目中依赖于接口的模块。

相关问题