在Swift中将字符串追加到NSMutableString

在Swift中将字符串追加到NSMutableString,swift,nsmutablestring,Swift,Nsmutablestring,我在目标C中找到了问题的答案,但在Swift中找不到答案。如何使下面的代码在向NSMutableString添加字符串值方面起作用?它抛出“仅为抽象类定义长度”错误 此代码旨在解析xml提要并将其写入NSMutableDictionary() 编辑:这里有更多的上下文 元素是NSString,它在DidStartElement期间分配给解析器中的elementName。在这段代码中,我通过元素捕捉提要内容的“标题” 我有一个NSMutableDictionary(),其中包括不同的NSMutab

我在目标C中找到了问题的答案,但在Swift中找不到答案。如何使下面的代码在向NSMutableString添加字符串值方面起作用?它抛出“仅为抽象类定义长度”错误

此代码旨在解析xml提要并将其写入NSMutableDictionary()

编辑:这里有更多的上下文

元素是NSString,它在DidStartElement期间分配给解析器中的elementName。在这段代码中,我通过元素捕捉提要内容的“标题”

我有一个NSMutableDictionary(),其中包括不同的NSMutableString(),例如ftitle。这段代码将把字符串添加到ftitle中,它是NSMutableString,然后它将成为NSMutableDictionary的一部分,最后我将在我的tableviewcells中阅读并编写它

以下是didStartElement方法:

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 = ""
    }
}
不是分配空字符串的正确方法。它分配
NSMutableString
不初始化它
NSMutableString
是一个类 群集,因此这可能会导致各种奇怪的错误

在斯威夫特,你会做的

ftitle = NSMutableString()
或者干脆

ftitle = ""
出于同样的原因

elements = NSMutableDictionary.alloc()
这是错误的,应该是错误的

elements = NSMutableDictionary()

除非我完全误解了您的意图,否则下面的代码可能是一个更干净的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
    }
}

你的问题中缺少了一些东西,例如:什么是“元素”?。你还说你想把texto附加到一个字符串上,但是你还说你想写一本字典?。我不得不说,我们需要更多的信息,因为你可以简单地用+运算符concat string和NSString。很抱歉,缺少上下文,这里还有更多:元素是NSString,它在DidStartElement期间分配给解析器中的elementName。在这段代码中,我通过元素捕捉提要内容的“标题”。我有一个NSMutableDictionary(),其中包括不同的NSMutableString(),例如ftitle。这段代码将把字符串添加到ftitle中,它是NSMutableString,然后它将成为NSMutableDictionary的一部分,最后我将阅读它并在我的TableViewCells中写入
var ftitle=NSMutableString?()
的目的是什么?我从未在Swift中见过这样的结构。如果将其替换为
var ftitle=NSMutableString()
@MatthiasBauch,会发生什么情况:我需要检查来自xml的值在diEndElement中是否为零。要做到这一点,我需要使用?这表示该值也可能为零。谢谢!只要简单地使用
ftitle=“
就行了!说真的,这么奇怪的错误:)
elements = NSMutableDictionary()
    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
    }
}