swift - Join results of for into one string -


i have places stored in core data in entity called "places" has attribute called "name". current loop return each name works well, , print in console shows of names expected. currently, console shows each 1 on separate line, separate places. possible fetch names each place , store in single string. here current code:

    {         let results = try mycontext.executefetchrequest(fetchrequest) as! [places]              places in results{                          let array = [places.name!].joinwithseparator(", ")                 print(array)             }      } catch let error nserror {         // failure         print("fetch failed: \(error.localizeddescription)")     } } 

here output, on each line (which shows separate objects), i'd them in 1 string (and printed on same line comma separator)

output

the output printed is: france, germany, poland, hungary, serbia

thank reading, hope can me!

you can use reduce method.

let placenames = results.reduce("") { (placenames, place) -> string in     return placenames + place.name + " " } 

now have single string concatenation of place names.

short notation

you can write follow

let placenames = results.reduce("") { $0 + $1.name + " " } 

example

lets place defined follow (i using struct class work well)

struct place {     let name: string } 

now let's define results array of place(s)

let results = [place(name: "italy"), place(name: "uk"), place(name: "usa")] 

and let's test code

let placenames = results.reduce("") { $0 + " " + $1.name } print(placenames) // "italy uk usa " 

removing last blank space

you maybe have noticed blank space appended @ , of generated string. can rid of updating code follow

let placenames = string(     places         .reduce("") { $0 + $1.name + " " }         .characters         .droplast() ) 

why solution better loop?

the code suggesting here follow functional programming paradigm. there several advantages on classic loop:

  1. it's thread safe: since using immutable values don't have worry other threads change values while using them.
  2. it's less error prone because it's more declarative: describing how result should be, not how build it.

that's :)


Comments

Popular posts from this blog

sublimetext3 - what keyboard shortcut is to comment/uncomment for this script tag in sublime -

java - No use of nillable="0" in SOAP Webservice -

ubuntu - Laravel 5.2 quickstart guide gives Not Found Error -