Tôi có giao thức sau đây và mở rộng của nógiao thức Swift với kiểu gắn liền - loại có thể không tham khảo chính nó như là một yêu cầu
public protocol RESEndpointReachable: CustomDebugStringConvertible
{
associatedtype EndpointType: RESEndpointReachable
// MARK: - Properties
/// The name of the endpoint as defined in the REST URI.
var name: String { get }
/// An array of possible next endpoints that this endpoint can reach. E.g account's next endpoints would be authenticate and unauthenticate.
var nextPossibleEndpoints: [EndpointType] { get }
// MARK: - Ability
/// Used to process the endpoint.
func processRequest(request: RERequest)
/// Processes the next endpoint that matches the name `name`. Expects an endpoint with the name `name` to exist in `nextPossibleEndpoints`.
func processNextEndpointWithName(name: String, request: RERequest)
}
public extension RESEndpointReachable
{
// MARK: - CustomDebugStringConvertible
public var debugDescription: String {
return name
}
// MARK: - RESEndpointReachable
var nextPossibleEndpoints: [EndpointType] {
return []
}
public func processRequest(request: RERequest)
{
// Check all possible endpoints are being processed
if let nextEndpoint = nextPossibleEndpoints.first
{
fatalError("Unhandled endpoint \(nextEndpoint).")
}
}
public func processNextEndpointWithName(name: String, request: RERequest)
{
// Get the next endpoint that matches the specified name
let nextEndpoints = nextPossibleEndpoints.filter { $0.name == name }
if nextEndpoints.count > 1
{
fatalError("Multiple next endpoints found with the name '\(name)'.")
}
guard let nextEndpoint = nextEndpoints.first else
{
fatalError("No next endpoint with the name '\(name)'.")
}
// Process the next endpoint
nextEndpoint.processRequest(request)
}
}
On xây dựng, dòng associatedtype EndpointType: RESEndpointReachable
có các lỗi sau: Type may not reference itself as a requirement
. Nhưng như tôi đã hiểu, đây là cách bạn sử dụng các kiểu liên kết trong Swift.
Như bạn có thể đã đoán, tôi luôn muốn bất cứ điều gì EndpointType
kết thúc được đặt làm loại được kế thừa từ RESEndpointReachable
.
Tôi không sử dụng tính năng này ble ngay bây giờ! Tham khảo: https://gist.github.com/curtclifton/1923a47774a94e904bf0 https://forums.developer.apple.com/thread/15256. Nó sẽ làm cho trình biên dịch chạy trong vòng lặp đệ quy – sargeras
Cảm ơn :) Tôi nghĩ rằng có thể là trường hợp ... Có lẽ tháng sau ... –