官术网_书友最值得收藏!

Type aliases

Type aliases are a simple addition to the language; they let you reference simple or complex types by an alias. They support all declarations that you can imagine, from the simplest to the most complex.

The following block contains declarations for aliasing the following:

  • A string class into a MyString
  • A function declaration into a Block
  • A block that takes any argument and returns any value
  • A block that takes no argument and returns any value

Let's see the code block; they let you:

typealias MyString = String
typealias Block = () -> Void
typealias TypedBlock<T, U> = (T) -> U
typealias ReturningBlock<U> = () -> U

We could have also defined Block in the function of ReturningBlock:

typealias Block = ReturningBlock<()>

You can also use type aliases for protocol compositions and complex types, as follows:

  • You can declare a type that conforms to a protocol and is of a particular class
  • You can delete a type that conforms to multiple protocols

Let's see an example, as follows:

protocol SomeProtocol {}
protocol OtherProtocol {}

typealias ViewControllerProtocol = NSViewController & SomeProtocol
typealias BothProtocols = SomeProtocol & OtherProtocol

You will often find yourself using type aliases, in order to make your code more readable and more expressive. They are a powerful tool for hiding away some of the implementation complexity or verbosity when declaring long conformances. With type aliases, you can be encouraged to craft many protocols, each with a very small requirement list; then, you can compose all of those protocols when you need them, expressed as those types.

主站蜘蛛池模板: 松潘县| 扎鲁特旗| 凤翔县| 龙海市| 井研县| 义乌市| 阿巴嘎旗| 乌恰县| 壶关县| 崇义县| 昭平县| 扶沟县| 文水县| 南陵县| 潜江市| 绍兴市| 庆元县| 通榆县| 和静县| 旬阳县| 永州市| 饶平县| 旅游| 卓资县| 临西县| 穆棱市| 临汾市| 陇南市| 宜都市| 蒙阴县| 汾阳市| 商洛市| 梁山县| 马尔康县| 淮安市| 若尔盖县| 涿鹿县| 岫岩| 茌平县| 大竹县| 罗城|