Swift 协议扩展对于实现类不可见

问题描述 投票:0回答:1

我的类上有一个函数曾经采用默认参数,但因为我正在制定一个协议 - 为了方便模拟网络调用 - 我的函数不能再采用默认参数。因此,我想我应该使用几个函数来扩展我的函数,这些函数提供与以前使用的相同的函数调用签名,这样我就不必更改在许多应用程序中进行的调用。 (此类是 Swift 包的一部分)。问题是调用我的实现类中的函数的类无法看到这些协议扩展函数。这是我的协议:

protocol WebService<EndPointType> {
    
    associatedtype EndPointType
    
    func request<ResponseType: Decodable>(_ endPoint: EndPointType, _ params: Parameters?, _ moreParams: Parameters?, codable: Codable?) async throws -> ResponseType 
    
}

extension WebService {
    public func request<ResponseType: Decodable>(_ endPoint: EndPointType) async throws -> ResponseType {
        return try await request(endPoint, nil, nil, codable: nil)
    }
}

(如果可行的话,最终将会有更多这样的扩展功能)。

这是我的实现类的相关部分:

public class Router<EndPointType: EndPoint>: WebService {
    public func request<ResponseType>(_ endPoint: EndPointType, _ params: Parameters?, _ moreParams: Parameters?, codable: Codable?) async throws -> ResponseType where ResponseType : Decodable {
...

这是调用失败的扩展函数的尝试:

let appStatusResponses: [AppStatusResponse] = try await router.request(.getStatus)

编译失败,并显示以下消息:“调用中缺少#2、#3、'可编码'的参数”。

如果我将扩展函数移动到我的实现类中,它就会编译。

为什么协议扩展函数对调用类不可见?它在实现类中可见,但在调用实现类的类中不可见。我已经通过 Xcode 中的自动建议验证了其中一个的不可见性和另一个的可见性。

任何提示,我们将不胜感激。

谢谢你。

swift swift-protocols
1个回答
0
投票

Rob 提到的 public 修饰符是最需要的。回想起来,这应该是显而易见的,但由于同一代码库中的另一个包正在使用该协议,我认为它已经可以访问了。另外,我很早就犯了一个错误,将 public 修饰符应用于协议而不是扩展。这是带有扩展名的最终协议:

public protocol WebService<EndPointType> {
    
    associatedtype EndPointType
    
    func request<ResponseType: Decodable>(_ endPoint: EndPointType, _ params: Parameters?, _ moreParams: Parameters?, codable: Codable?) async throws -> ResponseType
    
}

public extension WebService {
    func request<ResponseType: Decodable>(_ endPoint: EndPointType) async throws -> ResponseType {
        return try await request(endPoint, nil, nil, codable: nil)
    }
    
    func request<ResponseType: Decodable>(_ endPoint: EndPointType, codable: Codable?) async throws -> ResponseType {
        return try await request(endPoint, nil, nil, codable: codable)
    }
    
    
    func request<ResponseType: Decodable>(_ endPoint: EndPointType, _ params: Parameters?) async throws -> ResponseType {
        return try await request(endPoint, params, nil, codable: nil)
    }
    
    
    func request<ResponseType: Decodable>(_ endPoint: EndPointType, _ params: Parameters?, codable: Codable?) async throws -> ResponseType  {
        return try await request(endPoint, params, nil, codable: codable)
    }
    
}
© www.soinside.com 2019 - 2024. All rights reserved.