How to use variables from different classes in swift class

Asked 2 years ago, Updated 2 years ago, 31 views

For example, class a{ var aa = 1 }

class b{ print(aa) // 1 aa = 2 print(aa) // 2

}

Is there a way to use the aa variable in class a in b?

swift ios

2022-09-20 19:33

1 Answers

class a {
    var aa = 1
}

class b {
    print(aa) // 1
    aa = 2
    print(aa) // 2
}

I think you wrote this code. You cannot insert an execution code such as print() within a class declaration. There is no problem with the a class, but if you define the b class like that, a compilation error will occur. Therefore, you need to modify it as below.

class a {
    var aa = 1
}

class b {
    func myMethod() {
        print(aa) // 1
        aa = 2
        print(aa) // 2
    }
}

You asked how to access the properties of a in the b class. There are two ways of doing this.

If I explain from number 1, it will be as follows.

class a {
    var aa = 1
}

class b {
    func myMethod() {
         // // MARK: - Property
        let firstObject: a = .init()
        print(firstObject.aa) // 1
        firstObject.aa = 2
        print(firstObject.aa) // 2

        let secondObject: a = .init()
        print(secondObject.aa) // 1
        secondObject.aa = 2
        print(secondObject.aa) // 2

        firstObject.aa = 3
        print(firstObject.aa) // 3
        print(secondObject.aa) // 2
    }
}

Since the objects in firstObject and secondObject have different references, the values of aaa are different.

Now let me explain number two

class a {
    var aa = 1
    static var bb = 10
}

class b {
    func myMethod() {
        // // MARK: - Property
        let firstObject: a = .init()
        print(firstObject.aa) // 1
        firstObject.aa = 2
        print(firstObject.aa) // 2

        let secondObject: a = .init()
        print(secondObject.aa) // 1
        secondObject.aa = 2
        print(secondObject.aa) // 2

        firstObject.aa = 3
        print(firstObject.aa) // 3
        print(secondObject.aa) // 2

        // // MARK: - Static Property
        print(a.bb) // 10
        a.bb = 30
        print(a.bb) // 30

        print(firstObject.aa) // 3
        print(secondObject.aa) // 2
    }
}

Static Property allows access throughout the code without init.

I hope you don't give up studying Swift and work hard.😃


2022-09-20 19:33

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.