我需要一些帮助来建立一个类,该类将作为我的应用将使用的所有静态内容的基础,例如州,城市,国家,公司分类等。我不希望它们随着时间的推移而发生变化(否则变化很小)。
作为参考,我现在将考虑国家和城市(所有其他逻辑都相同)
国家/地区:
import UIKit
class Country {
var name: String
var cities: [City]
init(name:String,cities:[City]) {
self.name = name
self.cities = cities
}
}
Class City:
import UIKit
class City {
var name: String
init(name:String) {
self.name = name
}
}
在现有代码中,我使用了对这两个类的引用,但我将数据输入了ViewController。
import UIKit
class ViewController: UIViewController,UIPickerViewDelegate,UIPickerViewDataSource {
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var countryLbl: UILabel!
var countries = [Country]()
override func viewDidLoad() {
super.viewDidLoad()
pickerView.delegate = self
pickerView.dataSource = self
// Adding Countries and Cities
countries.append(Country(name: "UK",cities: [City(name: "London"),City(name: "Manchester"),City(name: "Bristol")]))
countries.append(Country(name: "USA",cities: [City(name: "New York"),City(name: "Chicago")]))
countries.append(Country(name: "China",cities: [City(name: "Beijing"),City(name: "Shanghai"),City(name: "Shenzhen"),City(name: "Hong Kong")]))
}
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
func pickerView(_ pickerView: UIPickerView,numberOfRowsInComponent component: Int) -> Int {
if component == 0 {
return countries.count
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities.count
}
}
func pickerView(_ pickerView: UIPickerView,titleForRow row: Int,forComponent component: Int) -> String? {
if component == 0 {
return countries[row].name
} else {
let selectedCountry = pickerView.selectedRow(inComponent: 0)
return countries[selectedCountry].cities[row].name
}
}
func pickerView(_ pickerView: UIPickerView,didSelectRow row: Int,inComponent component: Int) {
pickerView.reloadAllComponents()
let selectedCountry = pickerView.selectedRow(inComponent: 0)
let selectedCity = pickerView.selectedRow(inComponent: 1)
let cityR = countries[selectedCountry].cities[selectedCity].name
countryLbl.text = "The right answer was: in \(selectedCountry) in \(cityR)"
}
}
为了使代码更整洁,我想将下面的代码移动到另一个类并从ViewController调用它
// Adding Countries and Cities
countries.append(Country(name: "UK",City(name: "Bristol")]))
countries.append(Country(name: "USA",City(name: "Chicago")]))
countries.append(Country(name: "China",City(name: "Hong Kong")]))
}
被类似
的东西代替 let countriesAndCities = Dicitionary.getcountriesAndCities
// Here I would expect countriesAndCities to have the same content as countries.append(...) above.
这可行吗?
谢谢