I am trying to figure out how to define a Swift type with the use of syntactic sugar. Like apple has given to the Array struct the ability to define it both ways: Array<String>
and [String]
, how can I do the same for MyStruct?
You kind of can and can’t do this.
You cannot define a type with a shorthand like [String]
. You can’t, for example, define a new linked list and give it the a shorthand of ‹String›
.
What you can do is implement ArrayLiteralConvertible
, so that you can create your list like this:
let mylist: List = ["Elsa","Anna"]
by implementing ArrayLiteralConvertible
:
struct List<T> {
// your List implementation
}
extension List: ArrayLiteralConvertible {
init(arrayLiteral: T...) {
// populate list from from arrayLiteral
}
}
Set
is an example of a type that does this. Arrays are the default, but you can create sets with let myset: Set = [1,2,3]
.
Likewise you can implement StringLiteralConvertible
(let r: Regex = "^abc.*def$"
), but you can’t create a shorthand let r = /^abc.*def$/
, only the language designers can do that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With