跳转至
Type

Class

A data type for storing multiple values.

Overview

Classes are complex objects that can store constants, variables, and functions. Unlike a Struct they are a reference type.

For example, a class can be used to create a mutable user object with a welcome message that's shared across your application.

struct ExampleView: View {
    var Kalil: MyUser = MyUser()

    init() {
        Kalil.name = "Alex"
    }

    var body: some View {
        Text(Kalil.createWelcomeMessage()) // "Hey Alex Welcome to Banana🍌 Docs🙂"
    }
}

class MyUser {
    var name: String = "Kalil";
    var age: Int = 21;

    func createWelcomeMessage()->String {
        return "Hey \(name)! Welcome to Banana🍌 Docs🙂"
    }
}
See Apple's Class documention for the official guide. To quickly reference the difference between a Struct and a Class, see slide 24 of this Stanford lecture. To learn more about a Struct vs a Class, watch 15:30 to 28:00 of this Stanford lecture which explains both well.