iosswift3option-typeunwrapforced-unwrapping

How to Unwrap a Modal class object in Swift 3


Model Class:

class CountryModel: NSObject {

    var name:NSString!

    var countryId:NSString!

    init(name: NSString, countryId: NSString) {
        self.name = name
        self.countryId = countryId
    }

}

ViewController:

var nameArr = [CountryModel]() // Model Class object

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        var cell = UITableViewCell()

        cell = tableView.dequeueReusableCell(withIdentifier: "cell")!

        let arr = nameArr[indexPath.row] // How to do if let here

        let str:String? = "\(arr.countryId) \(arr.name)"

        if let sstr = str{
            cell.textLabel?.text = sstr
        }

        return cell

    }

How should one unwrap this because output is an optional, if I try to unwrap nameArr[indexPath.row] gives an error initializer for conditional binding must have optional type, not "country modal"

It works fine I am not concatenating arr.countryId with arr.name


Solution

  • This works fine

            var nameArr = [CountryModal]()
            nameArr.append(CountryModal.init(name: "harshal", countryId: "india"))
            nameArr.append(CountryModal.init(name: "james", countryId: "australia"))
    
            let arr = nameArr[0]
            let str:String? = "\(arr.countryId!) \(arr.name!)" 
            if let sstr = str{
               print(sstr)
            }
    
            let arr2 = nameArr[1]
            let str2:String? = "\(arr2.countryId!) \(arr2.name!)"
    
            if let sstr2 = str2{
                print(sstr2)
            }