我已经将一些JSON数据解码为一个视图控制器中的数组。以下是我的JSON数据的结构:
struct Country: Codable {
var id: Int
var country: String
var capital: String
var nationalLanguage: [String]
var population: Int
}
我将tableView中所选行的所有数据传递给单独视图控制器中Country类型的属性。我已经对出现错误的行进行了评论。
class DetailViewController: UIViewController {
@IBOutlet var idTextField: UITextField!
@IBOutlet var nameTextField: UITextField!
@IBOutlet var capitalTextField: UITextField!
@IBOutlet var languageTextField: UITextField!
@IBOutlet var populationTextField: UITextField!
var countryItem: Country?
override func viewDidLoad() {
idTextField.text = countryItem?.id // Error
nameTextField.text = countryItem?.country
capitalTextField.text = countryItem?.capital
languageTextField.text = countryItem?.nationalLanguage // Error
populationTextField.text = countryItem?.population // Error
}
}
错误显示:
Expression type '()' is ambiguous without more context
我知道这是因为这三种数据类型不是字符串类型,但我不确定我需要做什么来解决这个问题。将它们键入字符串不起作用,并给我以下错误:
Initializer 'init(_:)' requires that 'Int?' conform to 'LosslessStringConvertible'
您将Int/数组设置为UITextField
的字符串text
值。您需要
if let res = countryItem {
idTextField.text = String(res.id) // Error Int set to String
nameTextField.text = res.country
capitalTextField.text = res.capital
languageTextField.text = res.nationalLanguage.first // Error Array to String
populationTextField.text = String(res.population) // Error Int set to String
}