Swift equivalent of Array.componentsJoinedByString?
Swift 3.0:
Similar to Swift 2.0, but API renaming has renamed joinWithSeparator
to joined(separator:)
.
let joinedString = ["1", "2", "3", "4", "5"].joined(separator: ", ")
// joinedString: String = "1, 2, 3, 4, 5"
See Sequence.join(separator:) for more information.
Swift 2.0:
You can use the joinWithSeparator
method on SequenceType
to join an array of strings with a string separator.
let joinedString = ["1", "2", "3", "4", "5"].joinWithSeparator(", ")
// joinedString: String = "1, 2, 3, 4, 5"
See SequenceType.joinWithSeparator(_:) for more information.
Swift 1.0:
You can use the join
standard library function on String
to join an array of strings with a string.
let joinedString = ", ".join(["1", "2", "3", "4", "5"])
// joinedString: String = "1, 2, 3, 4, 5"
Or if you'd rather, you can use the global standard library function:
let joinedString = join(", ", ["1", "2", "3", "4", "5"])
// joinedString: String = "1, 2, 3, 4, 5"
How do I convert a Swift Array to a String?
If the array contains strings, you can use the String
's join
method:
var array = ["1", "2", "3"]
let stringRepresentation = "-".join(array) // "1-2-3"
In Swift 2:
var array = ["1", "2", "3"]
let stringRepresentation = array.joinWithSeparator("-") // "1-2-3"
This can be useful if you want to use a specific separator (hypen, blank, comma, etc).
Otherwise you can simply use the description
property, which returns a string representation of the array:
let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]"
Hint: any object implementing the Printable
protocol has a description
property. If you adopt that protocol in your own classes/structs, you make them print friendly as well
In Swift 3
join
becomesjoined
, example[nil, "1", "2"].flatMap({$0}).joined()
joinWithSeparator
becomesjoined(separator:)
(only available to Array of Strings)
In Swift 4
var array = ["1", "2", "3"]
array.joined(separator:"-")
Split string to arrays with maximum variables in each array
Step 1 - get fully separated array:
let numbers = "12,3,5".components(separatedBy: ",")
Step 2 - chunk your result to parts with ext:
extension Array {
func chunked(by chunkSize: Int) -> [[Element]] {
return stride(from: 0, to: self.count, by: chunkSize).map {
Array(self[$0..<Swift.min($0 + chunkSize, self.count)])
}
}
}
let chunkedNumbers = numbers.chunked(by: 10)
Step 3:
let stringsArray = chunkedNumbers.map { $0.joined(separator: ",") }
Result: ["12,3,5,75,584,364,57,88,94,4", "79,333,7465,867,56,6,748,546,573,466"]
Link to gist playground.
Purpose of Array Join function in Swift
Here is a somewhat useful example with strings:
Swift 3.0
let joiner = ":"
let elements = ["one", "two", "three"]
let joinedStrings = elements.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
output:
joinedStrings: one:two:three
Swift 2.0
var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = elements.joinWithSeparator(joiner)
print("joinedStrings: \(joinedStrings)")
output:
joinedStrings: one:two:three
Swift 1.2:
var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = joiner.join(elements)
println("joinedStrings: \(joinedStrings)")
The same thing in Obj-C for comparison:
NSString *joiner = @":";
NSArray *elements = @[@"one", @"two", @"three"];
NSString *joinedStrings = [elements componentsJoinedByString:joiner];
NSLog(@"joinedStrings: %@", joinedStrings);
output:
joinedStrings: one:two:three
Join an Array in Objective-C
NSArray *array1 = [NSArray arrayWithObjects:@"1", @"2", @"3", nil];
NSString *joinedString = [array1 componentsJoinedByString:@","];
componentsJoinedByString:
will join the components in the array by the specified string and return a string representation of the array.
Create a comma-separated list with and before the last item in Objective-C, in particular
That third party library @timgcarlson mentions sounds promising. Here's what I'd do natively...
- (NSString *)humanReadableListFromArray:(NSArray *)array withOxfordStyle:(BOOL)oxford {
if (array.count == 0) return @"";
if (array.count == 1) return array[0];
if (array.count == 2) return [array componentsJoinedByString:@" and "];
NSArray *firstItems = [array subarrayWithRange:NSMakeRange(0, array.count-1)];
NSString *lastItem = [array lastObject];
NSString *lastDelimiter = (oxford)? @", and " : @" and ";
return [NSString stringWithFormat:@"%@%@%@",
[firstItems componentsJoinedByString:@", "], lastDelimiter, lastItem];
}
How do I get multiple conditionals to run inside a while loop if the boolean of the conditional is true?
If are you trying to implement some kind of Morse encoding, I suggest to create a dictionary for all letters first, then simply loop through it:
let cipher = ["a": ".-", "b": "-...", "c": "-.-.", <...and so on...>]
for pair in cipher {
text = text.replacingOccurrences(of: pair.key, with: pair.value)
}
Convert Swift method using extend and append functions to Objective-C
When you do this:
[collect addObject:[self serializeObject:nestedObject key:newKey]];
You are adding an NSArray
to your collect
object. Instead, you want to add the objects contained within the response to collect
:
[collect addObjectsFromArray:[self serializeObject:nestedObject key:newKey]];
Convert NSArray to NSString in Objective-C
NSString * result = [[array valueForKey:@"description"] componentsJoinedByString:@""];
Related Topics
Arkit - How to Put 3D Object on Qrcode
How to Alloc/Dealloc Unsafe Pointers in Swift
Scenekit -- How to Get Animations for a .Dae Model
How to Quit Swift Repl Without Using Ctrl-D
How to Implement Hash(Into:) from Hashvalue in Swift
Get Playground to Display All Loop Results
How to Simulate Traits/Mixins in Swift
How to Avoid Using Anypublisher/Erasetoanypublisher All Over the Place
How to Recognize Continuous Touch in Swift
How to Record Video in Realitykit
How to Fix Error: This Class Is Not Key Value Coding-Compliant for the Key Tableview.'
Scenekit - Get Direction of Camera
Swift - Initialize View Controller from Storyboard by Overriding Init