swift 协议约定

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

我有一个名为

NetworkInterface
的类 - 我想让这个类可测试。快速执行此操作的方法意味着我应该从中提取协议?我的困惑是,我该如何称呼这个协议?我不想称它为
NetworkInterface
,因为这样就为协议起了一个“好名字”,然后我该怎么称呼我的
NetworkInterface
类呢?我见过一种模式,人们给协议起了一个好听的名字,然后把这个类称为可怕的东西,比如
DefaultNetworkInterface
但我也不喜欢这样。

我应该调用协议

NetworkInterfaceProtocol
然后调用类
NetworkInterface
吗?这里什么是传统的?

这是我到目前为止的代码,但我不相信我的名字是传统的,帮助!

protocol NetworkInterfaceProtocol {
    func ip4() -> String?
}

struct NetworkInterface: NetworkInterfaceProtocol {
    let interfaceName: String

    func ip4() -> String? {
    ....
    }
}

swift unit-testing naming swift-protocols
1个回答
0
投票

Swift.org 协议命名的唯一约定是在适用的情况下使用名词、

able
ible
ing
参考这里

因此,一种做法是将实体分解为较小的可描述部分,并将它们命名为:

protocol IP4Representable {
    func ip4() -> String?
}


protocol IP6Representable {
    func ip6() -> String?
}

然后像这样使用它:

extension NetworkInterface: IP4Representable & IP6Representable { ... }

您还可以按照

Codable
的方式合并它们:

typealias IPRepresentable = IP4Representable & IP6Representable

extension NetworkInterface: IPRepresentable { ... }

事实上,您可以根据需要拥有更大的块,并且它不必是每个协议中的单个函数。

我希望你明白了。

© www.soinside.com 2019 - 2024. All rights reserved.