6

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")
    }    
}
1
  • Why would you use implicitly unwrapped optionals if you're assigning a non-optional value in init anyway? Commented May 5, 2015 at 9:08

3 Answers 3

3

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
Sign up to request clarification or add additional context in comments.

Comments

1

map the objects to an array of strings, and then join that:

", ".join(recentArray.map { toString($0.id) })

Comments

0

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)"})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.