读取并将plist数据转换为String(Swift)

时间:2014-08-13 21:03:36

标签: string swift plist

我已经意识到还有其他问题。但是我试图将我从plist中读取的值作为String返回,它说:

'AnyObject' is not convertible to 'String'

这就是我所拥有的:

func getWord () -> String {
    let wordList = NSDictionary(contentsOfFile: "mylist.plist")
    return wordList.objectForKey("team")
}

plist文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>team</key>
    <array>
        <string>outfielder</string>
        <string>pitcher</string>
        <string>shortstop</string>
        <string>coach</string>
    </array>
</dict>
</plist>

3 个答案:

答案 0 :(得分:3)

将它强制转换为String。

func getWord () -> String {
    let wordList = NSDictionary(contentsOfFile: "mylist.plist")
    return wordList.objectForKey("team") as String
}

但要小心。您将返回隐式解包的可选项。如果您没有“团队”键的价值,您的应用程序将崩溃。如果该键的值不是String,它也会崩溃,因为我们在这里使用强制转换。

答案 1 :(得分:1)

尝试在最后添加字符串:

wordList.objectForKey("team").string

答案 2 :(得分:1)

var path: NSString = NSBundle.mainBundle().pathForResource("bhsCustom", ofType: "plist")!

// Get host link from plist
let wordList = NSDictionary(contentsOfFile: path)
var webLink: NSString = wordList.objectForKey("about_bhs") as NSString