ios - check for nil and extract data from dictionary in swift -
if user provides date value store in dictionary:
let dict:dictionary<string, any> = ["fromdate":fromdate any]
if user not provide date value store in dictionary this:
let dict:dictionary<string, any> = ["fromdate": [:] ]
i tried retrieve value dictionary inside cellforrowat
function this:
let dict:dictionary<string, any> = alldates[indexpath.row] guard let fromdate:string = getdatestring(createddate: dict["fromdate"] as! date) != nil else { fromdate:string = "none" } cell.fromdatelabel.text = gettimestringiso8601(createddate: fromdate)
this date string function
func getdatestring(createddate:date) -> string{ let formatter = dateformatter() formatter.calendar = calendar(identifier: .iso8601) formatter.locale = locale(identifier: "en_us_posix") formatter.locale = locale.current formatter.timezone = timezone(secondsfromgmt: 0) formatter.dateformat = "yyyy-mm-dd" return formatter.string(from: createddate) }
i error on guard statement:
type ‘string’ not optional value can never nil
how can check if date not nil , date converted , if date nil skip , put in statement “none” instead of date?
the error in guard statement because method getdatestring:
not returns optional value. checking return value of method never nil per definition. need check date value dict optional.
try like,
var fromdate = "none" if let dateval = dict["fromdate"] as? date { fromdate = getdatestring(createddate: dateval) cell.fromdatelabel.text = gettimestringiso8601(createddate: fromdate) } else { cell.fromdatelabel.text = fromdate }
Comments
Post a Comment