This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
我們只在乎function回傳的結果是 The code inside the module could build up the same shape in a variety of ways, and other code outside the module that uses the shape shouldn’t have to account for the implementation details
例如:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Generic type: Let caller pick the type for that function’s parameters and return value Opaque type: The function implementation decides the return value’s type
Example of Generic type let caller decide the type of function’s parameters and return value:
func max<T>(_ x: T, _ y: T) -> T where T: Comparable { ... }
Example of Opaque type decided by function implementation:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Opaque type: 在opaque type array內的每個element都是相同的type,且這個type遵守指定的protocol
Opaque type array example:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
boxed protocol type: 在boxed protocol type array內的每個element可以是不同type,但每個element的type都遵守指定的protocol。
boxed protocol type array example:
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Contrast the three types you could use for shapes:
Using generics, by writing struct VerticalShapes and var shapes: [S], makes an array whose elements are some specific shape type, and where the identity of that specific type is visible to any code that interacts with the array.
Using an opaque type, by writing var shapes: [some Shape], makes an array whose elements are some specific shape type, and where that specific type’s identity is hidden.
Using a boxed protocol type, by writing var shapes: [any Shape], makes an array that can store elements of different types, and where those types’ identities are hidden.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters