Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 协议中常数的快速初始化_Swift_Interface_Initialization - Fatal编程技术网

Swift 协议中常数的快速初始化

Swift 协议中常数的快速初始化,swift,interface,initialization,Swift,Interface,Initialization,在Java中,您可以在接口中初始化最终的静态字符串 Swift中有方法吗 例如: protocol StaticStringProtocol { // ERROR: Immutable property requirement must be declared as 'var' with a '{ get }' specifier static let staticStringInProtocol = "staticStringInProtocol" } extension S

在Java中,您可以在接口中初始化最终的静态字符串

Swift中有方法吗

例如:

protocol StaticStringProtocol {
    // ERROR: Immutable property requirement must be declared as 'var' with a '{ get }' specifier
    static let staticStringInProtocol = "staticStringInProtocol"
}

extension StaticStringProtocol {
    // ERROR: Static stored properties not supported in protocol extensions
    static let staticStringInProtocolExtension = "staticStringInProtocolExtension"
}
protocol MyProtocol {
}

struct MyProtocolConstants {
    static let myConstant = 10
}

更新此答案不再准确。请参见rghome的答案


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

protocol StaticStringProtocol {
    // ERROR: Immutable property requirement must be declared as 'var' with a '{ get }' specifier
    static let staticStringInProtocol = "staticStringInProtocol"
}

extension StaticStringProtocol {
    // ERROR: Static stored properties not supported in protocol extensions
    static let staticStringInProtocolExtension = "staticStringInProtocolExtension"
}
protocol MyProtocol {
}

struct MyProtocolConstants {
    static let myConstant = 10
}

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

实际上,您可以使用协议扩展在Swift中实现这一点:

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

protocol Order {
    var MAX_ORDER_ITEMS: Int { get }
    func getItem(item: Int) -> OrderItem
    // etc
}
定义协议扩展:

extension Order {
    var MAX_ORDER_ITEMS: Int { return 1000 }
}
这样做的一个优点是,您不必像通常使用Swift和statics那样为协议名加前缀


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

为什么不简单地阅读本文?它讲述了SwiftIn中有关协议的所有内容。一般来说,在接口中声明常量不是一个好的体系结构。我知道很多Java开发人员都是这样做的,然后他们在类中使用常量实现该接口,但这确实滥用了接口的概念。接口应该提供一个公共接口,即公共方法。不是常量。在Swift中没有这样做的好方法(在这方面,Java更方便。非常感谢您的快速回答!@S.Birklin:也许您应该将接受的答案更改为rghome的答案。这会引发编译器错误:
扩展不能包含存储属性。
它在编写答案时起作用。可能是最近的Swift语言更新破坏了它。抱歉,但是我现在没有用Swift写东西,所以我无法检查。好的,明白了。Swift 4.2没有问题。谢谢。请注意,它必须是一个计算属性。您不能使用
static let foo=“foo”