I just start to learn Apple Swift language and can't understand: How to keep a reference to another object in the parameters of class?
// List - my custom class
class RecordsList: NSObject {
var listObj: List!
init (inout list: List!)
{
self.listObj = list
}
func printData()
{
println(self.listObj.name)
}
}
var listObject = List()
listObject.name = "FirstValue"
RL = RecordsList(&listObject)
listObject.name = "SecondValue"
RL.printData()
// I expect: "SecondValue"
// But result: FirstValue =(
How can I get "SecondValue"?
In Swift objects are generally passed by reference, and only stuff like strings, ints, ... are passed by value... (Also structs are passed by value too!!!)
That means you don't need to create a special pointer to your object... If you just pass an object you already have set a pointer to the object (not a copy)
class TestClass {
var name: String?
}
class SecondTestClass {
var testClass: TestClass?
}
var testClass = TestClass()
var secondTestClass = SecondTestClass()
secondTestClass.testClass = testClass
testClass.name = "Worked"
var stringInObject = secondTestClass.testClass?.name
NSLog("\(stringInObject)")
And you are done :-)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With