Adding a string to NSMutableString in Swift

I found the answers to my question in Objective-C, but could not find it in Swift. How to make the code below work in terms of adding String value to NSMutableString? It throws the error "length defined only for an abstract class".

This code is for parsing XML feed and writing it to NSMutableDictionary ()

var ftitle = NSMutableString?()
func parser(parser: NSXMLParser!, foundCharacters string: String!) {
if element.isEqualToString("title") {
        ftitle?.appendString(string)
    }
}

Edit: Here is the context:

Element

is an NSString that is assigned to elementName in the parser during DidStartElement. in this code, I will catch the "header" of the feed contents through the element.

I have an NSMutableDictionary () which includes various NSMutableString () like ftitle. this piece of code is to add a line to ftitle which is NSMutableString, then it will be part of NSMutableDictionary, and finally I will read it for writing in my table cells

here is the 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 = ""
    }
}
+4
source share
2 answers
ftitle = NSMutableString.alloc()

is not the right way to assign an empty string. It allocates NSMutableStringwithout initialization. NSMutableStringis a cluster class, so this can cause all kinds of strange errors.

In Swift, you would just do

ftitle = NSMutableString()

or simply

ftitle = ""

For the same reason

elements = NSMutableDictionary.alloc()

wrong and should be

elements = NSMutableDictionary()
+6
source

, , , , Swift. , var, . , `let ', . , NSMutableString. , Swift/Obj-C.

    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
    }
}
+2

All Articles