Objective-C Simplest way to create comma separated string from an array of objects
Solution 1:
Use the NSArray
instance method componentsJoinedByString:
.
In Objective-C:
- (NSString *)componentsJoinedByString:(NSString *)separator
In Swift:
func componentsJoinedByString(separator: String) -> String
Example:
In Objective-C:
NSString *joinedComponents = [array componentsJoinedByString:@","];
In Swift:
let joinedComponents = array.joined(seperator: ",")
Solution 2:
If you're searching for the same solution in Swift, you can use this:
var array:Array<String> = ["string1", "string2", "string3"]
var commaSeperatedString = ", ".join(array) // Results in string1, string2, string3
To make sure your array doesn't contains nil values, you can use a filter:
array = array.filter { (stringValue) -> Bool in
return stringValue != nil && stringValue != ""
}