I found answers to my question in Objective C but couldnt find it in Swift. How can I make the code below work in terms of adding a String value to an NSMutableString? It throws "length only defined for abstract class" error.
This code is aimed to parse an xml feed and write it to a NSMutableDictionary()
var ftitle = NSMutableString?()
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
if element.isEqualToString("title") {
ftitle?.appendString(string)
}
}
Edit: Here is more context;
element is NSString which is assigned to elementName in parser during DidStartElement. in this code, i catch the "title" of the feed content via element.
i have an NSMutableDictionary() which includes different NSMutableString() such as ftitle. this piece of code is to add the string to the ftitle, which is NSMutableString, then it will be part of NSMutableDictionary, and finally i will read it to write in my tableviewcells
here is didStartElement method:
func parser(parser: NSXMLParser!, didStartElement elementName: String!, namespaceURI: String!, qualifiedName qName: String!, attributes attributeDict: [NSObject : AnyObject]!) {
element = elementName
if (element as NSString).isEqualToString("item"){
elements = NSMutableDictionary.alloc()
elements = [:]
ftitle = NSMutableString.alloc()
link = ""
fdescription = NSMutableString.alloc()
fdescription = ""
}
}
ftitle = NSMutableString.alloc()
is not a correct way to assign an empty string. It allocates the
NSMutableString
without initializing it. NSMutableString
is a class
cluster, so this can cause all kinds of strange errors.
In Swift, you just would do
ftitle = NSMutableString()
or simply
ftitle = ""
For the same reason,
elements = NSMutableDictionary.alloc()
is wrong and should be
elements = NSMutableDictionary()
Unless I totally misunderstood what you are attempting to do, the following code is probably a cleaner Swift implementation.
A string declared with a var
is mutable. A string declared with `let' is immutable. Not sure when it is appropriate to use NSMutableString. Perhaps when you have a mixed Swift / Obj-C project.
var ftitle = "" // declare ftitle as an empty string
var element = "" // this is coming from some other function
func parser(parser: NSXMLParser!, foundCharacters myString: String!) {
if element == "title" {
ftitle += myString // appends element to ftitle
}
}
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