Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make my own syntactic sugar in swift?

Tags:

ios

swift

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?

like image 612
Marios Mourelatos Avatar asked Apr 09 '15 00:04

Marios Mourelatos


1 Answers

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.

like image 53
Airspeed Velocity Avatar answered Nov 08 '22 03:11

Airspeed Velocity