Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Appending a String to NSMutableString in Swift

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 = ""
    }
}
like image 572
johncoffey Avatar asked Feb 11 '23 23:02

johncoffey


2 Answers

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()
like image 66
Martin R Avatar answered Feb 13 '23 20:02

Martin R


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
    }
}
like image 21
Syed Tariq Avatar answered Feb 13 '23 21:02

Syed Tariq