Swift在协议中初始化常量变量

时间:2022-07-21 17:03:02

In Java you can initialize final static Strings in an interface. Is there also a method in Swift?

在Java中,您可以在接口中初始化最终的静态字符串。 Swift中还有一个方法吗?

2 个解决方案

#1


3  

No swift doesn't support that. My advice is to define a struct alongside your protocol and define all constants as immutable static stored properties. For example:

没有swift不支持。我的建议是在协议旁边定义一个结构,并将所有常量定义为不可变的静态存储属性。例如:

protocol MyProtocol {
}

struct MyProtocolConstants {
    static let myConstant = 10
}

Note that structs are preferred to classes, for at least one reason: classes don't support static stored properties (yet)

请注意,结构首选于类,至少有一个原因:类不支持静态存储属性(尚)

#2


5  

Actually, you can do this in Swift using protocol extensions:

实际上,您可以使用协议扩展在Swift中执行此操作:

Create a protocol and define the variable you want with a getter:

创建协议并使用getter定义所需的变量:

protocol Order {
    var MAX_ORDER_ITEMS: Int { get }
    func getItem(item: Int) -> OrderItem
    // etc
}

Define a protocol extension:

定义协议扩展:

extension Order {
    var MAX_ORDER_ITEMS: Int { return 1000 }
}

An advantage of this is that you don't have to prefix the protocol name as is usual with Swift and statics.

这样做的一个优点是您不必像Swift和静态一样使用协议名称前缀。

The only problems is that you can only access the variable from within a class implementing the protocol (which is probably the most common case anyway).

唯一的问题是你只能从实现协议的类中访问变量(这可能是最常见的情况)。

#1


3  

No swift doesn't support that. My advice is to define a struct alongside your protocol and define all constants as immutable static stored properties. For example:

没有swift不支持。我的建议是在协议旁边定义一个结构,并将所有常量定义为不可变的静态存储属性。例如:

protocol MyProtocol {
}

struct MyProtocolConstants {
    static let myConstant = 10
}

Note that structs are preferred to classes, for at least one reason: classes don't support static stored properties (yet)

请注意,结构首选于类,至少有一个原因:类不支持静态存储属性(尚)

#2


5  

Actually, you can do this in Swift using protocol extensions:

实际上,您可以使用协议扩展在Swift中执行此操作:

Create a protocol and define the variable you want with a getter:

创建协议并使用getter定义所需的变量:

protocol Order {
    var MAX_ORDER_ITEMS: Int { get }
    func getItem(item: Int) -> OrderItem
    // etc
}

Define a protocol extension:

定义协议扩展:

extension Order {
    var MAX_ORDER_ITEMS: Int { return 1000 }
}

An advantage of this is that you don't have to prefix the protocol name as is usual with Swift and statics.

这样做的一个优点是您不必像Swift和静态一样使用协议名称前缀。

The only problems is that you can only access the variable from within a class implementing the protocol (which is probably the most common case anyway).

唯一的问题是你只能从实现协议的类中访问变量(这可能是最常见的情况)。