Chapter 19: Custom Operators, Subscripts, Keypaths

在Ch16學到如何使用operator overloading,例如實作Equatable 和Comparable的protocol,並針對這些標準operator加上客製化的行為。但有時候只是為標準operator加上新行為可能還不夠,我們想要自己的客製化operator。

大綱

Custom operators

  • 首先,如何定義exponentiation operator ?

Types of operators

  • Unary operators work with only one operand and are defined either as postfix, if they appear after the operand, or prefix, if they appear before the operand. The logical not operator is a unary prefix operator and the forced unwrapping operator is a unary postfix one. You learned about them in Chapter 3, “Basic Control Flow” and Chapter 6, “Optionals”.

  • Binary operators work with two operands and are infix because they appear between the operands. All the arithmetic operators (+, -, *, /, %), comparison operators (==, !=, <, >, <=, >=) and most of the logical ones (&&, ||) are binary infix.

  • Ternary operators work with three operands. You’ve learned about the conditional operator in Chapter 3, “Basic Control Flow”. This is the only ternary operator in Swift.

Exponentiation operator

  • Swift是不允許有自己客製化Ternary operators。

Compound assignment operator

  • 大部分內建的operator都有自己對應的Compound assignment operator。

Generic operator

  • 利用BinaryInteger來限制可以使用generic type類型。

Precedence and associativity

  • 如果把我們客製化的operator用在複雜的表達式上

  • 如果不想要用括號,那就要替客製化的operator加上額外的宣告

Subscripts

  • Arrays, Dictionaries, Sets都具有Subscripts的功能,透過[ ]來取值。

  • 也可以對自己的type加上Subscripts的功能。

Subscript parameters

  • 利用external parameter names讓Subscript更加清楚

Dynamic member lookup

  • 利用dynamic member lookup來替自己的type增加任意的dot syntax。

“Unlike computed properties and functions, subscripts have no name to make their intentions clear. Subscripts are almost exclusively used to access the elements of a collection, so don’t confuse the readers of your code by using them for something unrelated and unintuitive!”

Keypaths

  • 用keypath其實比用properties更加複雜,必須先宣告keypath才來進行讀取。

“The benefit is that it you can parameterize the properties you use in your code. Instead of hard coding them, you can store them in variables as keypaths. You could even leave it up to your users to decide which properties to use!”

Key points

  • Remember the custom operators mantra when creating brand new operators from scratch: With great power comes great responsibility. Make sure the additional cognitive overhead of a custom operator introduces pays for itself.

  • Choose the appropriate type for custom operators: postfix, prefix or infix.

  • Don’t forget to define any related operators, such as compound assignment operators, for custom operators.

  • Use subscripts to overload the square brackets operator for classes, structures and enumerations.

  • Use dynamic member lookup to provide dot syntax for subscripts.

  • Use keypaths to create dynamic references to properties

Last updated