The controller has a collectionView, including 1 cell, 5 section and some row, downloading data from LeanCloud just like Parse. Code always fails with fatal error: Array index out of range. In my opinion, I may have some problem in dealing with array of array, about how to access and how to add element. Any one can help me solve this bug? The bug line is listed below:
var temp = self.restaurantLean[number].
import UIKit
import AVOSCloud
class DiscoverViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, RestaurantLeanCollectionCellDelegate, UIGestureRecognizerDelegate {
#IBOutlet var imageView: UIImageView!
#IBOutlet var collectionView: UICollectionView!
private var restaurantLean = [[RestaurantLean]]()
override func viewDidLoad() {
super.viewDidLoad()
collectionView.backgroundColor = UIColor.clearColor()
loadTripsFromLeanCloud()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: Data Source
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return restaurantLean.count
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return restaurantLean[section].count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! RestaurantLeanCollectionCell
cell.delegate = self
cell.nameLabel.text = restaurantLean[indexPath.section][indexPath.row].name
cell.typeLabel.text = restaurantLean[indexPath.section][indexPath.row].type
cell.locationLabel.text = restaurantLean[indexPath.section][indexPath.row].location
cell.isLike = restaurantLean[indexPath.section][indexPath.row].isLike
cell.imageView.image = UIImage()
cell.layer.cornerRadius = 4.0
if let image = restaurantLean[indexPath.section][indexPath.row].image {
image.getDataInBackgroundWithBlock({ (imageData, error) -> Void in
print(image)
if let data = imageData {
print("loading")
cell.imageView.image = UIImage(data: data)
print("success")
}
})
}
return cell
}
//Download the data from Baas LeanCloud
func loadTripsFromLeanCloud() {
restaurantLean.removeAll(keepCapacity: true)
for number in 0...4 {
let name = "Restaurant_" + String(number)
print(name)
print(number)
let query = AVQuery(className: name)
query.cachePolicy = AVCachePolicy.NetworkElseCache
print("1")
query.findObjectsInBackgroundWithBlock({ (objects, error) -> Void in
print("2")
if let error = error {
print("3")
print("Error: \(error) \(error.userInfo)")
}
print("4")
if let objects = objects {
print("5")
for (index, object) in objects.enumerate() {
let restaurant = RestaurantLean(avObject: object as! AVObject)
self.restaurantLean[number].append(restaurant)
let indexPath = NSIndexPath(forRow: index, inSection: number)
self.collectionView.insertItemsAtIndexPaths([indexPath])
}
}
})
print("6")
}
}
You are not adding elements to restaurantLean array itself (you only add objects to nested arrays). Here is possible solution.
func loadTripsFromLeanCloud() {
restaurantLean.removeAll(keepCapacity: true)
for number in 0...4 {
restaurantLean.append([]) // This line
// ...
}
}
Related
I have a problem with an array of data, in this data array I send the name of 6 images so that later they are loaded in a CollectionView, the 6 images load well, without any problem, but when I add a String value to send it gives me a error that is empty:
This is my class where is my data array:
import UIKit
class HBook{
var imagenB: UIImage!
var estatus: String!
init(estatus: String, imagenB: UIImage) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1"],
["imagenB":"book2"],
["imagenB":"book3"],
["imagenB":"book4"],
["imagenB":"book5"],
["imagenB":"book6"],
["estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
hbook.append(HBook(estatus: item["estatus"]!, imagenB: UIImage(named: item["imagenB"]!)!))
}
return hbook
}
}
I print my data array to see which variable is empty, but apparently all have an assigned value:
I do not know why I'm sending an empty value.
This information was retrieved in another class that has a CollectionView and a Label, the method where I passed the information is in the cellForItemAt method:
class DetailViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout {
#IBOutlet weak var contenedorCollection: UIView!
#IBOutlet weak var myCollection: UICollectionView!
#IBOutlet weak var pages: UIPageControl!
#IBOutlet weak var estatus: UILabel!
var hbook = HBook.getData()
var nombreH = ""
override func viewDidLoad() {
super.viewDidLoad()
pages.numberOfPages = hbook.count
self.title = nombreH
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return hbook.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CellCollectionViewCell
cell.imageview.image = hbook[indexPath.row].imagenB
estatus.text = hbook[indexPath.row].estatus
return cell
}
I think the problem is in data class. Please replace your HBook class with following code and it will work without any further change :
class HBook{
var imagenB: UIImage?
var estatus: String?
init(estatus: String? = nil, imagenB: UIImage? = nil) {
self.estatus = estatus
self.imagenB = imagenB
}
class func getData() -> [HBook]{
let rawData = [
["imagenB":"book1","estatus":"No reservado"],
["imagenB":"book2","estatus":"No reservado"],
["imagenB":"book3","estatus":"No reservado"],
["imagenB":"book4","estatus":"No reservado"],
["imagenB":"book5","estatus":"No reservado"],
["imagenB":"book6","estatus":"No reservado"]
]
var hbook:[HBook] = []
for item in rawData{
if let image = item["itemnB"]{
hbook.append(HBook(estatus: item["estatus"], imagenB:UIImage(named:image)))
}else{
hbook.append(HBook(estatus: item["estatus"]))
}
}
return hbook
}
}
I'm getting the following error:
Cannot assign value of type '[[String : AnyObject]]' to type '[[String : AnyObject?]]'
It's strange this assignment was working before then when I restarted my Xcode, I started to get this error. From what I have read online, this should not give the error.
Here is my code:
import UIKit
import Alamofire
import SwiftyJSON
class Signal Condo TableViewController: UITableViewController {
#IBOutlet var tableview: UITableView!
var singleCondoData = [[String:AnyObject]]()
var CondoIndivi = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.delegate = self
self.tableView.dataSource = self
}
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 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return singleCondoData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SignleTableTableViewCell
if singleCondoData.count != 0 {
let dict = singleCondoData[indexPath.row] as NSDictionary
//cell.label1.text? = (dict["name"] as? String)!
if let nullcheck = (dict["address"] as? String) {
cell.label2.text? = nullcheck
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dict = singleCondoData[indexPath.row] as NSDictionary
if let unitNullCheck = (dict["mls_number"] as? String) {
let item_id = unitNullCheck
getCondoUnits(item_id)
print(item_id)
}
}
//get the individual condo id
func getCondoUnits(condo_id : String){
Alamofire.request(.GET, "http://android.goidx.com/search/?mls_number=" + String(condo_id)).validate().responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
if let resData = json.arrayObject {
self.CondoIndivi = (resData as? [[String:AnyObject]])!
print(self.CondoIndivi)
}
if self.CondoIndivi.count > 0 {
self.tableview.reloadData()
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "details" :
let buildingdDetailVC = segue.destinationViewController as! DetailsViewController
buildingdDetailVC.CondoIndivi2 = self.CondoIndivi // line of the error
default:
break
}
}
}
}
The type of CondoIndivi2 variable is [[String: AnyObject?]] but you are passing an array of type [[String: AnyObject]] where the dictionary values are non-optional.
Since any non-optional value with same type can be safely converted to its optional corresponding, you can do the following:
buildingdDetailVC.CondoIndivi2 = self.CondoIndivi.map { $0 as [String: AnyObject?] }
I m getting this error :fatal error: Index out of range .I can't get what i m doing wrong .What i'm trying to do is , access an array dictionary by using an integer index than pass a string to get the value mapped to it .The sample works fine on playground but not excode why ? (The array dictionary is not empty)
Here is my code
var CondoIndivi2 = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
scrollView.contentSize.height = 1500
print(CondoIndivi2)
if let description_Condo = self.CondoIndivi2[0]["description"] as? String {
print(description_Condo)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is the view that sends data to CondoIndivi2
import UIKit
import Alamofire
import SwiftyJSON
class SignleCondoTableViewController: UITableViewController {
#IBOutlet var tableview: UITableView!
var singleCondoData = [[String:AnyObject]]()
var CondoIndivi = [[String:AnyObject]]()
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
self.tableView.delegate = self
self.tableView.dataSource = self
}
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 1
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return singleCondoData.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! SignleTableTableViewCell
if singleCondoData.count != 0 {
let dict = singleCondoData[indexPath.row] as NSDictionary
//cell.label1.text? = (dict["name"] as? String)!
if let nullcheck = (dict["address"] as? String) {
cell.label2.text? = nullcheck
}
}
return cell
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let dict = singleCondoData[indexPath.row] as NSDictionary
if let unitNullCheck = (dict["mls_number"] as? String) {
let item_id = unitNullCheck
getCondoUnits(item_id)
print(item_id)
}
}
//get the individual condo id
func getCondoUnits(condo_id : String){
Alamofire.request(.GET, "http://android.goidx.com/search/?mls_number=" + String(condo_id)).validate().responseJSON { response in
if let value = response.result.value {
let json = JSON(value)
if let resData = json.arrayObject {
self.CondoIndivi = resData as! [[String:AnyObject]]
print(self.CondoIndivi)
}
if self.CondoIndivi.count > 0 {
self.tableview.reloadData()
}
}
}
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let identifier = segue.identifier {
switch identifier {
case "details" :
let buildingdDetailVC = segue.destinationViewController as! DetailsViewController
buildingdDetailVC.CondoIndivi2 = self.CondoIndivi
default:
break
}
}
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
As #James put in his comment, you're creating an empty array in your code:
var CondoIndivi2 = [[String:AnyObject]]()
And then you're trying to access indexing in the position 0:
if let description_Condo = self.CondoIndivi2[0]["description"] as? String {
print(description_Condo)
}
And of course, you will have a runtime error of Index of out Range because your array it's empty, you always need to be sure before index an array that the index is greater than zero, less than equal to the size of the array and the array is not empty.
I hope this help you.
Inside your getCondoUnits(condo_id : String) is an asynchronous block(Alamofire.request), the CondoIndivi2 is received later than the viewDidLoad is executed. You should just pass condo_id to next viewController and do the request in it.
so this is my first post here I've been developing in swift for a few months now and just can't work my way around this problem.
I have tried explaining what I need help with in my image.
If i click on tableview row 1 i want send an array of 30-70 images to a collection view and this kinda works, except it shows same images on all rows, tableview row 2 -3 -4.
image of collectionView
Please take a look at this link for my parse Database
parse database
I am more than happy to share on bitbucket.
//Here goes the TableView
import UIKit
import Parse
class TableViewController: PFQueryTableViewController {
var selectedRow:PFUser?
var userids = [""]
var wonk = ["wonk"]
var slagtHuset = ["slagtHuset"]
var Adelgatan = ["Adelgatan"]
// Initialise the PFQueryTable tableview
override init(style: UITableViewStyle, className: String!) {
super.init(style: style, className: className)
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)!
// Configure the PFQueryTableView
self.parseClassName = "crowd"
self.textKey = "cellTitle"
self.pullToRefreshEnabled = true
self.paginationEnabled = false
// self.objectsPerPage = 3
}
// Define the query that will provide the data for the table view
override func queryForTable() -> PFQuery {
var query = PFQuery(className: "crowd")
query.orderByDescending("cellTitle")
// Only retrieve the last ten
query.limit = 10
return query
}
//override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath, object: PFObject?) -> PFTableViewCell {
var cell = tableView.dequeueReusableCellWithIdentifier("CustomCell") as! CustomTableViewCell!
if cell == nil {
cell = CustomTableViewCell(style: UITableViewCellStyle.Default, reuseIdentifier: "CustomCell")
}
// Extract values from the PFObject to display in the table cell
if let nameEnglish = object?["cellTitle"] as? String {
cell.customNameEnglish.text = nameEnglish
}
// Display flag image
var initialThumbnail = UIImage(named: "question")
cell.customFlag.image = initialThumbnail
if let thumbnail = object?["crowdImage"] as? PFFile {
cell.customFlag.file = thumbnail
cell.customFlag.loadInBackground()
}
return cell
}
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var detailScene = segue.destinationViewController as! DetailViewController
// Pass the selected object to the destination view controller.
if let indexPath = self.tableView?.indexPathForSelectedRow {
let row = Int(indexPath.row)
detailScene.currentObject = objects?[row] as? PFObject
//detailScene.currentObject = [Adelgatan, slagtHuset]
// NSIndexPath *indexPath=[self.tableView indexPathForSelectedRow];
// DOG details= (DOG)segue.destinationViewController;
// PFObject *object=[self.typeDog objectAtIndex:indexPath.row ];
// details.stringdata=[object objectForKey:#"username"];
// pass whatever data you want to display in the collection view as an array here.
// details.array = ...
}
}
override func viewDidAppear(animated: Bool) {
// Refresh the table to ensure any data changes are displayed
tableView.reloadData()
}
Here is code for detailView(collectionView)
import UIKit
var countries = PFObject
class DetailViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
// Container to store the view table selected object
var currentObject : PFObject?
var wonk = ["wonk"]
var slagtHuset = ["slagtHuset"]
var Adelgatan = ["Adelgatan"]
// var clubs = [slagtHuset, Adelgatan, wonk]
// Some text fields
#IBOutlet var collectionView: UICollectionView!
#IBOutlet weak var flag: PFImageView!
override func viewDidLoad() {
super.viewDidLoad()
// Resize size of collection view items in grid so that we achieve 3 boxes across
let cellWidth = ((UIScreen.mainScreen().bounds.width) - 3 - 3 ) / 2
let cellHeight = ((UIScreen.mainScreen().bounds.width) - 4 - 3 ) / 2
let cellLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
cellLayout.itemSize = CGSize(width: cellWidth, height: cellHeight)
}
func loadCollectionViewData() {
// Build a parse query object
var query = PFQuery(className:"crowd")
//more specs query.whereKey("currencyCode", equalTo:"EUR")
query.orderByAscending("objectId")
// Fetch data from the parse platform
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]?, error: NSError?) -> Void in
// The find succeeded now rocess the found objects into the countries array
if error == nil {
// Clear existing country data
countries.removeAll(keepCapacity: true)
// Add country objects to our array
if let objects = objects as? [PFObject] {
countries = Array(objects.generate())
}
// reload our data into the collection view
self.collectionView.reloadData()
} else {
// Log details of the failure
print("Error: \(error!) \(error!.userInfo)")
}
}
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
print(countries)
return countries.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("cell", forIndexPath: indexPath) as! CollectionViewCell
// Display "initial" flag image
var initialThumbnail = UIImage(named: "question")
cell.cellImage.image = initialThumbnail
// Here is my problem where i only load image from Adelgatan
// Fetch final flag image - if it exists
if let value = countries[indexPath.row]["Adelgatan"] as? PFFile {
let finalImage = countries[indexPath.row]["Adelgatan"] as? PFFile
finalImage!.getDataInBackgroundWithBlock {
(imageData: NSData?, error: NSError?) -> Void in
if error == nil {
if let imageData = imageData {
cell.cellImage.image = UIImage(data:imageData)
}
}
}
}
return cell
I got that error a while ago and I'm not sure, what's wrong. The Post is just normal custom class with two attributes of type String and int.
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()
}
}
settings :
import Foundation
class Settings {
var viewPost = "http://jsonplaceholder.typicode.com/posts"
}
post:
class Post {
var _userId:Int
var _title: String
init(userid:Int , title:String){
self._userId = userid
self._title = title
}
func toJSON() ->String{
return ""
}
}
and 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
}
why error Cannot subscript a value of type '[Post]' in line
I'm not sure that this is the issue but it is an issue.
Since postsCollection has a distinct type there is no need to cast the type.
NSData is the wrong type anyway.
let post = postsCollection[indexPath.row] // the compiler infers to Post
Side note: Put the dispatch block to reload the table view after the repeat loop to create the Post instances. Reloading the table view in each iteration of the loop is very expensive and not necessary.
for post in posts {
...
}
dispatch_async(dispatch_get_main_queue()){
self.tableView.reloadData()
}
And (public) properties starting with a underscore are pretty unusual (in Swift).
PS: There are two further issues
cell.textLabel?.text = String(post._userId)
cell.detailTextLabel?.text = post._title
Edit: Simple working solution, there are only two classes
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
}
}