Cannot assign value of type 'CLong?' (aka 'Optional<Int>') to type 'String?' [Swift 5]

不问归期 提交于 2021-02-11 14:59:49

问题


Questions : How do I use DateFormatter(Type: CLong) in tableview?

Similar questions I looked for

How to change JSON string to date format in tableview

I looked up questions like these on stackoverflow. However, there was no way to use Type: CLong.

Clong is a type I'm new to using, so I don't know what type to use Optional.

connection json file

struct BoardList: Codable {
    var b_date: CLong?
}

TableViewController

var boards: [BoardList]?

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "TableViewCell", for: indexPath) as! TableViewCell
      if let boards = self.boards {
         let model = boards[indexPath.row]
            
         let dateFormatter = DateFormatter()
         dateFormatter.dateFormat = "yyyy/MM/dd HH:mm:ss"

         cell.txtDate.text = model.b_date // ERROR [Cannot assign value of type 'CLong?' (aka 'Optional<Int>') to type 'String?']
    
     }
     return cell
 }

++ I must take the CLong type. Because the server value is specified in that format.

value assigned to Postman


回答1:


The server sends JSON. There is no type CLong in JSON, it's an Int.

You can decode the date without any date formatter just be declaring b_date as Date. The default date decoding strategy is secondsSince1970 which the integer represents.

let jsonString = """
{"b_date" : 1602813427}
"""

struct BoardList: Codable {
    let b_date: Date
}

let data = Data(jsonString.utf8)

do {
    let result = try JSONDecoder().decode(BoardList.self, from: data)
    print(result)
} catch {
    print(error)
}
 

You can also specify the convertFromSnakeCase strategy and declare the struct member bDate to get rid of the ugly snake case name.



来源:https://stackoverflow.com/questions/64386099/cannot-assign-value-of-type-clong-aka-optionalint-to-type-string-sw

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!