react native - Checking for nil parameter and if that parameter is an empty string in Swift -
there may or may not easier way write this, feel being novice @ swift, missing something. have parameter (filename) method optional string?
need check if nil
, or if empty string. code have, , works fine, seems bit more concise/readable.
func writefile(filename: string?, withcontents contents: string, errorcallback failurecallback: rctresponsesenderblock, callback successcallback: rctresponsesenderblock) -> void { // if filename has value -- not nil if let filename = filename { // check see if string isn't empty if count(filename) < 1 { // craft failure message let resultsdict = [ "success": false, "errmsg": "filename empty" ] // execute javascript failure callback handler failurecallback([resultsdict]) return; // halt execution of function } // else, filename nil, , should return same error message. } else { // craft failure message let resultsdict = [ "success": false, "errmsg": "filename empty" ] // execute javascript failure callback handler failurecallback([resultsdict]) return; // halt execution of function } }
how
first create nil string optional set example var filename: string?
now code lets see if filename nil/empty in 1 simple line:
if (filename ?? "").isempty { println("empty") } else { println("not empty") }
this uses ??
, swift "nil coalescing operator". (link)
for expression:
a ?? b
where a
optional says:
if not nil, return a. if nil, return b instead.
so
if (filename ?? "").isempty
says
first, evaluate filename , see if it's nil. if so, replace empty string.
next, check result see if it's empty.
Comments
Post a Comment