String 读取plist数据并将其转换为字符串(Swift)

String 读取plist数据并将其转换为字符串(Swift),string,swift,plist,String,Swift,Plist,我意识到已经有其他问题了。但我试图返回一个从plist读取的字符串值,它说: 'AnyObject' is not convertible to 'String' 以下是我所拥有的: func getWord () -> String { let wordList = NSDictionary(contentsOfFile: "mylist.plist") return wordList.objectForKey("team") } plist文件 <?xml v

我意识到已经有其他问题了。但我试图返回一个从plist读取的字符串值,它说:

'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>

团队
外野手
投掷者
游击手
教练

尝试在末尾添加字符串:

wordList.objectForKey("team").string

尝试在末尾添加字符串:

wordList.objectForKey("team").string

把它扔到绳子上

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

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

只需将其转换为字符串即可

func getWord () -> String {
    let wordList = NSDictionary(contentsOfFile: "mylist.plist")
    return wordList.objectForKey("team") as String
}
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

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

plist中“team”键的值是数组,而不是字符串。这一点很好。我发现了我的问题plist中“team”键的值是一个数组,而不是一个字符串。这一点很好。我发现我的问题如果我问对了这将是最好的答案如果我问对了这将是最好的答案
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