Ric*_*hiy 5 extension-methods module ios swift
开发应用程序时,我使用扩展来隐藏代码中对特定库的依赖关系。我希望方法名称与库中的方法名称完全相同。
这种方法有助于大大减少对外部库的依赖(要将其与其他库交换,我只需要重写桥中的函数)。但是,在扩展的情况下有点棘手,因为我使用此代码得到无限循环:
// Library implementation, File1.swift
import Foundation
extension Date {
func test(otherDate: Date) -> String {
return String()
}
}
// App reference to the library, different module, File2.swift
import Foundation
import Library
extension Date {
func test(otherDate: Date) -> String {
// How to reference "Library" here?
return test(otherDate: otherDate)
}
}
Run Code Online (Sandbox Code Playgroud)
添加前缀时,该方法工作正常:
// Works correctly:
import Foundation
import Library
extension Date {
func prefix_test(otherDate: Date) -> String {
return test(otherDate: otherDate)
}
}
Run Code Online (Sandbox Code Playgroud)
Swift 中有什么方法可以从特定模块调用扩展方法,类似于选择一个类:
// Selecting a class:
let a = Module1.CustomClass()
let b = Module2.CustomClass()
let date = Date()
// Can I select an extension method?
date.Module1.func1()
date.Module2.func1()
Run Code Online (Sandbox Code Playgroud)
这个问题与“重复”有何不同: 对于类函数,可以执行以下操作:
Module1.Class1.classFunction()
Module2.Class1.classFunction()
Run Code Online (Sandbox Code Playgroud)
在上述情况下,这样的调用是不可能的,因此出现了问题。