[swift]错误下标

标签: json Swift
发布时间: 2017/3/5 21:41:58
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我不久前得到了这一错误并不知道,什么是错。该职位是类型的只是类型的正常的自定义类,具有两个属性字符串和整数。

web api:http://jsonplaceholder.typicode.com/posts

PostService:

class PostService {
var settings:Settings!
init(){

    self.settings = Settings()
}

func getPosts(callback:(NSArray) ->()){
    request(settings.viewPost, callback: callback)


}
func request(url:String , callback:(NSArray) ->() ){


    let nsURL = NSURL(string: url)
    let task = NSURLSession.sharedSession().dataTaskWithURL(nsURL!){(data , repsonse , error) in
        //var error:NSError?
        do {
            let response = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! NSArray
            callback(response)


        } catch {
            print(error)
        }

    }
    task.resume()
}

}

设置:

import Foundation
class Settings {

  var viewPost = "http://jsonplaceholder.typicode.com/posts"

}

发布:

class Post {
   var _userId:Int
   var _title: String

   init(userid:Int , title:String){
     self._userId = userid
     self._title = title

   }

   func toJSON() ->String{

    return ""
   }
}

和 tableViewController:

class TableViewController: UITableViewController {
var postsCollection = [Post]()
var service:PostService!

override func viewDidLoad() {
    super.viewDidLoad()

    service = PostService()
    service.getPosts{
        (response) in
        self.loadPosts(response[" "] as! NSArray )
    }
}

func loadPosts(posts:NSArray){
    for post in posts{

        var userId = post["userId"] as! Int
        var title  = post["title"] as! String
        let postObj = Post(userid: userId, title: title)
        postsCollection.append(postObj)
        dispatch_async(dispatch_get_main_queue()){

            self.tableView.reloadData()
        }

    }


}
override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

// MARK: - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 0
}

override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return postsCollection.count
}


override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

    let post = postsCollection[indexPath.row] as NSData
    cell.textLabel?.text = post._userId
    cell.detailTextLabel = post._title
    return cell
}

为什么错误无法下标类型 '[职位]' 行中的值

解决方法 1:

不,我确信,这问题,但却是一个问题。

由于 postsCollection 具有一种独特类型没有类型强制转换的需要。
NSData反正是错误的类型。

let post = postsCollection[indexPath.row] // the compiler infers to Post

边注︰ 把 dispatch 块重新加载表查看重复循环,以便创建 Post 实例。重新加载表视图中每个循环迭代中是非常昂贵和不必要。

for post in posts {
        ...
}
dispatch_async(dispatch_get_main_queue()){
    self.tableView.reloadData()
}

并以下划线开头的 (公共) 属性是相当不寻常 (在 Swift )。

PS︰ 有两个问题

cell.textLabel?.text = String(post._userId)
cell.detailTextLabel?.text = post._title

编辑︰简单的工作解决方案,有只有两节课

class Post

class Post : CustomStringConvertible {
  var userId:Int
  var title: String

  init(userid:Int , title:String){
    self.userId = userid
    self.title = title
  }

  var description : String { return String(userId) }
}

class TableViewController

class TableViewController: UITableViewController {
var postsCollection = [Post]()

override func viewDidLoad() {
    super.viewDidLoad()

    let url = NSURL(string: "http://jsonplaceholder.typicode.com/posts")
    NSURLSession.sharedSession().dataTaskWithURL(url!){ [unowned self] (data , repsonse , error) in
      if error != nil {
        print(error!)
      } else {
        do {
          let posts = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers) as! [[String:AnyObject]]
          for post in posts {
            let postObj = Post(userid: post["userId"] as! Int, title: post["title"] as! String)
            self.postsCollection.append(postObj)
          }
          dispatch_async(dispatch_get_main_queue()){
              self.tableView.reloadData()
          }
        } catch let error as NSError {
          print(error)
        }
      }
      }.resume()
    }

    // MARK: - Table view data source

    override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 }

    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return postsCollection.count }

    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)

        let post = postsCollection[indexPath.row]
        cell.textLabel!.text = String(post.userId)
        cell.detailTextLabel!.text = post.title
        return cell
    }
}
赞助商