Save pointers in Swift
The initializer for my class Field
gets an inout String.
class Field: NSObject {
var placeHolder: String?
var text: String?
init(placeHolder : String, inout text: String) {
self.placeHolder = placeHolder
self.text = &text
}
}
I want to be able to store a pointer to a variable text
so that I can change its value later. What's the best way to do this?
source to share
It is recognized NSMutableString
instead of Swift String
because it NSMutableString
is a class and thus passed by reference.
edit: try messing around with the following on the playground.
import Foundation
class Field: NSObject {
var placeHolder: String?
var text: NSMutableString?
init(placeHolder : String, text: NSMutableString) {
self.placeHolder = placeHolder
self.text = text
super.init()
}
func mutateIt() {
text?.appendString("mutated")
}
}
var mutStr = NSMutableString(string: "Hello")
mutStr.appendString("Why")
var aField = Field(placeHolder: "", text: mutStr)
aField.mutateIt()
println(mutStr)
source to share
What you are trying to do would be very dangerous. How can you guarantee that your "pointer to string" will point to something later? Consider this code:
func stringChanger(inout s : String) {
}
func f() {
var s = "howdy"
stringChanger(&s)
}
If stringChanger
can store a pointer to s
for use "later", all hell breaks down when it tries to set s
"later" through that pointer, because the original s
, the thing pointed to, is a temporary variable and won't exist "later" at all!
This is why Swift makes it difficult: it tries to protect you from itself (and succeeds). Rethink your goal!
It would be better if you asked a question that describes your ultimate goal, whatever they may be, rather than a question limited by narrow means that are not really available to you.
source to share
I think you should probably check out how to use the Protocol . I have not seen anyone use a keyword inout
like this before. They usually use it in methods to change a passed parameter within the same scope, not an initializer. Right now, you have passed the class level and I'm not sure about that. Also, readability will be improved if you use the Protocol .
source to share