Swift Structures
Structures are essentially a way to group together information to represent something in our app. A model of data or a function.
Structures are named with capital letters (
MenuItem,SpongeBob).New structure → add a new file. Define your structure in that new file.
Empty structure
struct MenuItem {
}Structure with variables
struct MenuItem {
var name:String // Properties of the Structure
var price:String
var image:String
}
// This creates a custom data type.
// For example, var array:[MenuItem]
struct MenuItem {
var name:String
var price:String = "$2.99"
var image:String
}
// If you pre-define the values, then don't need to define during an instance.Structure with functions (methods)
struct MenuItem {
func printHello() { // Methods of the Structure
print("Hello World!")
}
}Identifiable protocol
Original page had a screenshot here.
Identifiable is a protocol that a structure needs to conform to in order to be used in a List. It gives the system a way to ID each item so it can differentiate one from another.
// We have to make our structure conform to Identifiable Protocol
// Create a new id property, and set a UUID instance
// UUID is our special data type
// UUID() is an instance that creates a UUID with RFC 4412 version 4 random bytes
struct MenuItem: Identifiable {
var id: UUID = UUID() // Creates a random ID that is assigned to the menu item
}Instances
Instances are the different things you can create from the blueprint (structure).
// Create a new instance
// Start with the name of the structure that you want to create an instance of
MenuItem(name: "Onigiri", price: "$1.99", imageName: "onigiri")
// Assign the instance to a variable
var firstItem: MenuItem(name: "Onigiri", price: "$1.99", imageName: "onigiri")Accessing instances (dot notation)
Dot notation accesses information. Dot just means self.
// Taking variable information
print(firstItem.name)
>> "Onigiri"
// Taking function information
firstItem.printHelloSee next
- SwiftUI-Layout — Lists iterate over arrays of Identifiable structures