Reputation: 865
I've created a custom object which contain id, name and shortname. I would like to only retrieve the id's and do a ",".join()
so that it will be a string like for instance "1, 2"
So how can I convert an array like var recentArray = Array<News>()
to an string with only the id's seperated by comma?
Custom Class
class Team: NSObject{
var id: Int!
var name: NSString!
var shortname: NSString!
init(id: Int, name:NSString, shortname: NSString) {
self.id = id
self.name = name
self.shortname = shortname
}
required convenience init(coder aDecoder: NSCoder) {
let id = aDecoder.decodeIntegerForKey("id")
let name = aDecoder.decodeObjectForKey("name") as! String
let shortname = aDecoder.decodeObjectForKey("shortname") as! String
self.init(id: id, name: name, shortname: shortname)
}
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(id, forKey: "id")
aCoder.encodeObject(name, forKey: "name")
aCoder.encodeObject(shortname, forKey: "shortname")
}
}
Upvotes: 5
Views: 3212
Reputation: 25459
You can map the array to get just id's from the Team array and reduce the array to string:
let a = Team(id: 1, name: "Greg", shortname: "G")
let b = Team(id: 2, name: "John", shortname: "J")
let c = Team(id: 3, name: "Jessie", shortname: "Je")
let d = Team(id: 4, name: "Ann", shortname: "A")
let array = [a,b,c,d]
let result = array.map({$0.id}).reduce("", combine: {result, id in return result == "" ? "\(id)" : "\(result),\(id)"})
Upvotes: 0
Reputation: 717
you have tu use map
function.
var t1 = Team(id: 1, name: "Adria", shortname: "Ad")
var t2 = Team(id: 2, name: "Roger", shortname: "Ro")
var t3 = Team(id: 3, name: "Raquel", shortname: "Ra")
var array: [Team] = [t1, t2, t3];
var arrayMap: Array = array.map(){ toString($0.id) }
var joinedString: String = ",".join(arrayMap)
println(joinedString) // 1,2,3
Upvotes: 3
Reputation: 40955
map
the objects to an array of strings, and then join that:
", ".join(recentArray.map { toString($0.id) })
Upvotes: 1