I want to initialiaze an array if it is nil.
The reason for this is that I have an optional array (as I want it to be nil until an API call is made - it is optional and this is part of the question context):
Here is the issue:
var array: [String]? = ["1","2","3"]
if array == nil { pageArray = []}
array! += ["4"]
The code works but is not easy to read. There is a force unwrap for array which is not good.
What the question isn't: Note this is not production code, does not contain the imports for UIKit or other code not related to the array.I may have badly named variable etc. but this question is about an array. I may have misspelt something in this question and it might not be clear, but I really need help on the initialization of the array and the title of the question (and the question itself) refers to this.
What I've tried I tried a guard, but of course guards should not fallthrough so this seems a poor option.
The question How can I initialize an array if and only if it is nil?
LoginResponseresponse works by setting the value of a global variable likepageArray. That's nasty, and it's going to bite you in the ass. Instead, use a proper async mechanism. It could be callback closures, Futures/Promises, or observable streams like from RxSwift or Apple's Combine. I would start with medium.com/ios-os-x-development/…let content = LoginResponse(linkslist: ["1","2","3"])have, exactly? Does it effectpageArrayin some capacity? If it doesn't, then why is there the seperation between declaration (var pageArray: [Page]?) and initialization (if pageArray == nil { pageArray = [] })? Why couldn't you just writevar pageArray = []let content = LoginResponse(linkslist: ["1","2","3"])is where it is, and that there's a reason that you wrote a seperate decl/init rather than justvar pageArray = [].