我正在为 IOS 学习 swift ,而我在 youtube 上进行巡回演出(Swift:Using External Databases and API's by Skip Wilson )对于外部数据库,我发现了这个部分:
service = PostService()
service.getPosts {
(response) in
self.loadPosts(response["posts"]! as NSDictionary)
}
func loadPosts(posts:NSDictionary) {
for post in posts {
var id = (post["Post"]["id"] as String)
var title = post["Post"]!["title"]! as String
var author = post["Post"]!["author"]! as String
var content = post["Post"]!["content"]! as String
var postObj = Post(id: id, title: title, author: author, content: content)
postsCollection.append(postObj)
}
dispatch_async(dispatch_get_main_queue()) {
self.tableView.reloadData()
}
}
最初这里的 NSDictionary 是 NSArray,但它不起作用,因为 NSArray 现在只接受 int 作为键,并且 PostService.getPost() 返回类型 NSDictionary。所以我把它改成了 NSDictionary。
但是,所有的 var id,title,author,content 都出现错误
(key:AnyObject, value:AnyObject) does not have a member name subscript
似乎我需要将键和值声明为 < String , String> ,但我现在不确定是否要这样做。Blow 是 Postservice 的代码:
class PostService {
var settings:Settings!
init(){
self.settings = Settings()
}
func getPosts(callback:(NSDictionary)->()) {
println("get posts")
request(settings.viewPosts,callback)
}
func request(url:String,callback:(NSDictionary)->()) {
var nsURL = NSURL(string: url)
println(callback)
let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!) {
(data,response,error) in
var error:NSError?
var response = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.MutableContainers, error: &error) as NSDictionary
callback(response)
}
task.resume()
}
}
我知道这可能是一个非常简单和愚蠢的问题,但在谷歌上搜索后我仍然无法弄清楚。我应该怎么办?任何帮助将不胜感激。