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

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.

主站蜘蛛池模板: 武邑县| 秀山| 安陆市| 丽江市| 房产| 汉中市| 仁寿县| 凌云县| 长岛县| 盘锦市| 油尖旺区| 龙里县| 余干县| 凤冈县| 阳西县| 衡水市| 德格县| 横峰县| 南郑县| 沙田区| 沁水县| 洪湖市| 文昌市| 广西| 虎林市| 沂南县| 桐梓县| 永平县| 乡城县| 施甸县| 定边县| 塘沽区| 平潭县| 永康市| 宁化县| 巴林右旗| 南汇区| 密山市| 怀仁县| 旺苍县| 延长县|