ios - How to store database into struct using swift3? -
i have function database , return in mutablearray, need database in struct.
do need mutablearray struct or should data straight struct?
i have no idea how approach or how store database struct
my code:
class crimesinfo: nsobject { var name: string = string() var detail: string = string() var time: string = string() }
the function:
func getallcrimesdata() -> nsmutablearray { sharedinstance.database!.open() let resultset: fmresultset! = sharedinstance.database!.executequery("select * crimetable", withargumentsin: nil) let marrcrimesinfo : nsmutablearray = nsmutablearray() if (resultset != nil) { while resultset.next() { let crimesinfo : crimesinfo = crimesinfo() crimesinfo.name = resultset.string(forcolumn: "name") crimesinfo.detail = resultset.string(forcolumn: "detail") crimesinfo.time = resultset.string(forcolumn: "time") marrcrimesinfo.add(crimesinfo) } }
there's lot going on here. here of thoughts:
- your
getallcrimesdata
getscrimesinfo
. "data" or "into, pick one, stay consistent. - your
getallcrimesdata
return array of kinds of data mushed together. there's no need this, fill out structs immediately, rather worrying parsing array structs later. - there's never reason use
nsarray
,nsdictionary
, or mutable versions in swift. use native swift type. - use safe
guard let
orif let
checking deal optionality ofresultset
, rather using implicitly-unwrapped optional. - there's no reason make
crimesinfo
class - there's no reason make
crimesinfo
inheritnsobject
- there's no reason pre-fil
name
/detail
/time
empty string. doubt want crime named""
.
here's how write this:
struct crimeinfo: nsobject { let name: string let details: string let time: string init(name: string, detail: string, time: string) { self.name = name self.details = details self.time = time } init(fromresultset: fmresultset) { self.init( name: resultset.string(forcolumn: "name"), details: resultset.string(forcolumn: "detail"), time: resultset.string(forcolumn: "time") ) } } let crimesintoquery = "select * crimetable" func getallcrimesinfo() -> [crimeinfo] { let database = sharedinstance.database! database.open() guard let resultset = database.executequery(crimesintoquery, withargumentsin: nil) { else return [] } var crimes = [crimeinfo]() while resultset.next() { crimes.add(crimeinfo(fromresultset: resultset)) } return crimes }
Comments
Post a Comment