Swift - if string is nil. don't add it to the array
Swift - if string is nil. don't add it to the array I have an Array of Image links - Array Image let alamofireSource = [AlamofireSource(urlString: Img1!)!, AlamofireSource(urlString: Img2!)!, AlamofireSource(urlString: Img3!)!, AlamofireSource(urlString: Img4!)!] slideshow.setImageInputs(alamofireSource) some posts have only one image or two or three, and so on. so, sometimes image 2 (for example) is nil, In that case, I don't want it to be added to the array, is that possible? 3 Answers 3 You can try ( Swift 4 ) let arr = [img1,img2].compactMap{$0}.map{AlamofireSource(urlString:$0)!} or let arr = alamofireSource.compactMap{$0} for Swift 3 let arr = alamofireSource.flatMap{$0} Thanks a trillion! It fixed the problem :-) – Sophie Bernard Jul 3 at 10:22