以这种方式构造结构实例是否正确?
public struct Barometer { public var pressure: Int public init(pressure: Int) { self.pressure = pressure } } var barometer: Barometer = 80
还是我需要采用协议?
您可以通过采用以下IntegerLiteralConvertible 协议来完成这项工作:
IntegerLiteralConvertible
extension Barometer: IntegerLiteralConvertible { public init(integerLiteral value: Int) { self.init(pressure: value) } }
现在Barometer可以从文字整数实例化一个值:
Barometer
let barometer: Barometer = 80 print(barometer) // Barometer(pressure: 80)
但是请注意,这仅适用于文字,不适用于任意整数值:
let p = 80 let barometer: Barometer = p // error: cannot convert value of type 'Int' to specified type 'Barometer' // You have to use: let barometer = Barometer(pressure: p)
对于 Swift 3,请 替换IntegerLiteralConvertible为 ExpressibleByIntegerLiteral。
ExpressibleByIntegerLiteral