Home > Blockchain >  Unable to assign different variable types according to condition in same class in Swift
Unable to assign different variable types according to condition in same class in Swift

Time:12-14

I need to declaring variables according to this isCandidateResult == false or true

here isCandidateResult == false than in FilterData Class in need to assign

var jobType: [String] = []    
var jobRole: String = ""

and isCandidateResult == true

var jobType: String = ""   
var jobRole: [String] = []

but how i am unable to

code: to achieve my goal i have tried like this code but.. with this code i am getting below errors

 import UIKit
 var isCandidateResult: Bool = false

if isCandidateResult == false{//Error: Statements are not allowed at the top level
class FilterData {

var jobType: [String] = []    
var jobRole: String = ""

init(jobType: [String], jobRole: String) {
    self.jobType = jobType
    self.jobRole = jobRole
}
}
}
else{

class FilterData {

var jobType: String = ""   
var jobRole: [String] = []

init(jobType: String, jobRole: [String]) {
    self.jobType = jobType
    self.jobRole = jobRole
}
}
}



class FilterViewController: UIViewController {

@IBOutlet weak var filterTableView: UITableView!
@IBOutlet weak var subFilterTableView: UITableView!
@IBOutlet weak var filterTitle: UILabel!

if isCandidateResult == false{
var filterData = FilterData(jobType: [], jobRole: "")//Cannot find 'FilterData' in scope
}
elase{
var filterData = FilterData(jobType: "", jobRole: [])
}
override func viewDidLoad() {
    super.viewDidLoad()
}
}

ERRORs: 1)

Statements are not allowed at the top level 2) Cannot find 'FilterData' in scope

CodePudding user response:

That's not how it should be done.

Instead, create a model which could be initialized with a job type and roles, or with a job role and types, a model for the UITableView. That way, you don't need to care about if it's job type & roles or the other one. You populate the model only. And let the tableview manage its own data. It doesn't need to know what's inside.

struct FilterTableViewModel {

    let title: String
    let elements: [String]

    init(jobType: String, roles: [String]) {
        title = jobType
        elements = roles
    }

    init(jobRole: String, types: [String]) {
        title = jobRole
        elements = types
    }
}

And:

class FilterViewController: UIViewController {
    var filterData: [FilterTableViewModel] = []
}
  • Related