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.😃
579 PHP ssh2_scp_send fails to send files as intended
602 GDB gets version error when attempting to debug with the Presense SDK (IDE)
576 Understanding How to Configure Google API Key
900 When building Fast API+Uvicorn environment with PyInstaller, console=False results in an error
614 Uncaught (inpromise) Error on Electron: An object could not be cloned
© 2024 OneMinuteCode. All rights reserved.