โญOpaque Types

Swift โŸฉ Type โŸฉ

Swift 5.1 feature

If a function with an opaque return type returns from multiple places, all of the possible return values must have the same type. For a generic function, that return type can use the functionโ€™s generic type parameters, but it must still be a single type. ๐Ÿ‘‰ Swift

  • the function body determines its concrete return type (including the concrete type of any associated type) at compile time. (๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 5)

  • use PAT (protocol with associated types) as return types. (๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 5)

  • preserve type identity (always return the same type). (๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 2, 5)

  • the body of a SwiftUI view returns some View. (View is a PAT)

Opaque Type vs. Generic Type

  • opaque return type: its concrete type is determined by function body ("inside"). - ๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 2, 5

  • generic type: its placeholders (type parameters) & return type are determined by caller (call site) & type declaration ("outside"). - ๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 1

Opaque Type vs. Protocol Type

  • opaque type : always refers to ONE specific, concrete type. - ๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 2, 5

  • protocol type: can refer to MANY (conformaning) concrete types. - ๐Ÿ’ˆ็ฏ„ไพ‹ โญ๏ธ 3

Last updated