literals
Swift has a couple of literals that can be used to initialize different types without explicitly invoking their initializer. For instance,
let x = 5
automatically outputs xto type Int. But if we specify the type of the variable as something else
let x: UInt = 5
the compiler automatically understands what is 5now an unsigned integer, so instead of the initializer, you Intshould call the corresponding initializer UInt.
Protocol ExpressibleByIntegerLiteral
This is possible for all types that implement the protocol ExpressibleByIntegerLiteral. Now I add the correspondence of this protocol to my own type:
struct TextRange: ExpressibleByIntegerLiteral {
let range: CountableClosedRange<Int>
var lowerBound: Int {
return range.lowerBound
}
var upperBound: Int {
return range.upperBound
}
init(_ range: CountableClosedRange<Int>) {
self.range = range
}
init(integerLiteral value: Int) {
self.range = value...value
}
}
With this definition, I can write:
let x: TextRange = 5
However
let x = 5
still indicates x as Int. So far so good.
...
TextRange ... :
let y: TextRange = 5...10
... TextRange s:
extension TextRange {
static func ...(lowerRange: TextRange, upperRange: TextRange) -> TextRange {
let lowerBound = lowerRange.lowerBound
let upperBound = max(lowerRange.upperBound, upperRange.upperBound)
assert(lowerBound <= upperBound, "Cannot create a TextRange because lowerBound > upperBound.")
return TextRange(lowerBound...upperBound)
}
}
. ( : !)
TextRange , , TextRange:
let y = 5...10
, :
, "", x y x...y TextRange s?
, , ?