Fast initialization of constants in the protocol

In Java, you can initialize the final static lines in an interface.

Is there a method in Swift?

For instance:

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" } 
+9
source share
2 answers

Update This answer is no longer accurate. See rghome answer instead


No Swift supports this. My advice is to define the structure along with your protocol and define all constants as immutable static stored properties. For instance:

 protocol MyProtocol { } struct MyProtocolConstants { static let myConstant = 10 } 

Note that structures are preferable to classes for at least one reason: classes do not support static stored properties (for now)

+5
source

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

Create a protocol and define the desired variable using getter:

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

Define the protocol extension:

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

The advantage of this is that you do not need a protocol name prefix, as usual, with Swift and statics.

The only problems are that you can only access the variable from the class that implements the protocol (this is probably the most common case).

+12
source

Source: https://habr.com/ru/post/1206398/


All Articles