标签: protocol-inheritance

如何使协议关联类型需要协议继承而不是协议采用

在我的快速项目中,我有一种情况,我使用协议继承如下

protocol A : class{

}

protocol B : A{

}
Run Code Online (Sandbox Code Playgroud)

我接下来要实现的是声明另一个具有关联类型的协议,该类型必须从protocol继承A。如果我尝试将其声明为:

protocol AnotherProtocol{
    associatedtype Type : A
    weak var type : Type?{get set}
}
Run Code Online (Sandbox Code Playgroud)

它在编译时没有错误,但是AnotherProtocol在以下情况下尝试采用时:

class SomeClass : AnotherProtocol{

    typealias Type = B
    weak var type : Type?
}
Run Code Online (Sandbox Code Playgroud)

编译失败,SomeClass并声明与不一致的错误AnotherProtocol。如果我正确理解这一点,则意味着Im在尝试声明并询问如何声明从协议继承的关联类型时B 不采用?AA

我基于以下情况进行编译的事实做出了上述假设

class SomeDummyClass : B{

}

class SomeClass : AnotherProtocol{

    typealias Type = SomeDummyClass
    weak var type : Type?
}
Run Code Online (Sandbox Code Playgroud)

associated-types swift swift-protocols protocol-inheritance

5
推荐指数
1
解决办法
1288
查看次数

协议继承问题

我尝试建立各种可以协同工作的协议。不幸的是,我无法让它们按照我想要的方式工作。看下面的代码,我认为我的目标很明显:我想要求一个符合协议X的类。如果它符合协议Y,但协议Y继承自协议X,则它也应被视为一个符合性的类。 。相反,我收到以下编译错误

Unable to infer associated type 'VC' for protocol 'ViewModelType'

Inferred type 'ExampleViewControllerType' (by matching requirement 'viewController') is invalid: does not conform to 'ViewType'

当前设置:

protocol ViewModelType: class {
    associatedtype VC: ViewType
    weak var viewController: VC! { get set }
}

class ExampleViewModel: ViewModelType {
    weak var viewController: ExampleViewControllerType!
}

protocol ViewType: class { }    
protocol ExampleViewControllerType: ViewType { }

class ExampleViewController: UIViewController, ExampleViewControllerType { 

}
Run Code Online (Sandbox Code Playgroud)

protocols ios associated-types swift protocol-inheritance

5
推荐指数
1
解决办法
168
查看次数

Swift 中对数值数组求和的计算属性

书中的任务说:在不调用reduce(_: _:)方法的情况下,通过添加一个名为sum的计算属性来对数字序列求和。您应该能够像这样使用它:

[3, 7, 7].sum            // 17
[8.5, 1.1, 0.1].sum      // 9.7
Run Code Online (Sandbox Code Playgroud)

作者提示:在开发人员文档中检查 Int 和 Double 遵循哪些协议,以及这些协议继承自哪些协议。在下面的代码中,我只是结合了我找到的两个解决方案,但它仍然包含方法reduce。如果您可以帮助我了解如何解决这个问题/开发人员文档的哪一部分提供了线索。另外,如何避免当前代码中的错误/在封闭范围内应用可能的解决方案。

extension Sequence where Element: Numeric {
    var sum: Any {
        return reduce(0, +)
    }
}

[3, 7, 7].sum
[8.5, 1.1, 0.1].sum
[1...4].sum // Error: Property 'sum' requires that 'ClosedRange<Int>' conform to 'Numeric'
Run Code Online (Sandbox Code Playgroud)

arrays swift computed-properties protocol-extension protocol-inheritance

1
推荐指数
1
解决办法
148
查看次数