ppshein ppshein - 3 months ago 22
Swift Question

Cannot convert value of type 'AnyObject?' to specified type 'BookingObject!'

I have created booking object as follow in swift,

import Foundation

class BookingObject {
var bookingTitle: String = ""
var bookingDesc: String = ""

then add data as follow

private var bookingData:NSMutableArray?
for country in countryCode {
bookingObj.bookingTitle = country.name
bookingObj.bookingDesc = country.name

and problem is got following when retrieve value

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
/* error found that line */
let bookingObj:BookingObject! = bookingData?.objectAtIndex(indexPath.row)
let cell = bookingTable.dequeueReusableCellWithIdentifier("BookCell", forIndexPath: indexPath) as! BookCell
cell.lbAppointmentTitle.text = bookingObj.bookingTitle
return cell

Please let me know what I did wrong to leaked that error

Cannot convert value of type 'AnyObject?' to specified type


Use a struct and the CustomStringConvertible protocol:

struct Booking : CustomStringConvertible {
    let title : String
    var description : String { return title }

Declare the bookings property like this:

private var bookings : [BookingObject] = []

Add items like this:

for country in countryCode {
    bookings(Booking(title: country.name))

Get your items like this:

let booking = bookings[indexPath.row]