Chapter 4. Object Types
In the preceding chapter, I discussed some built-in object types. But I have not yet explained object types themselves. As I mentioned in Chapter 1, Swift object types come in three flavors: enum, struct, and class. What are the differences between them? And how would you create your own object type?
In this chapter, I’ll describe object types in general, and then each of the three flavors. Then I’ll explain three Swift ways of giving an object type greater flexibility: protocols, generics, and extensions. Finally, the survey of Swift’s built-in types will conclude with three umbrella types and three collection types.
Object Type Declarations and Features
Object types are declared with the flavor of the object type (enum
, struct
, or class
), the name of the object type (which should start with a capital letter), and curly braces:
class Manny { } struct Moe { } enum Jack { }
The visibility of an object type by other code — its scope — depends upon where its declaration appears:
-
Object types declared at the top level of a file will, by default, be visible to all files in the same module. This is the usual place for object type declarations.
-
Sometimes it’s useful to declare a type inside the declaration of another type, thus giving it a namespace. This is called a nested type.
-
An object type declared within the body of a function will exist only inside the scope of the curly braces that surround it; such declarations are legal but rare.
Declarations ...
Get iOS 12 Programming Fundamentals with Swift now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.