在数组中使用join()有什么用?什么目的?
在其他语言中,它用于将数组元素连接到字符串中。例如,
Ruby Array.join
我已经问了一些关于join()的问题 Swift Array join EXC_BAD_ACCESS
答案 0 :(得分:151)
这是一个有用的字符串示例:
Swift 3.0
let joiner = ":"
let elements = ["one", "two", "three"]
let joinedStrings = elements.joined(separator: joiner)
print("joinedStrings: \(joinedStrings)")
输出:
joinedStrings:one:two:three
Swift 2.0
var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = elements.joinWithSeparator(joiner)
print("joinedStrings: \(joinedStrings)")
输出:
joinedStrings:one:two:three
Swift 1.2:
var joiner = ":"
var elements = ["one", "two", "three"]
var joinedStrings = joiner.join(elements)
println("joinedStrings: \(joinedStrings)")
用于比较的Obj-C中的相同内容:
NSString *joiner = @":";
NSArray *elements = @[@"one", @"two", @"three"];
NSString *joinedStrings = [elements componentsJoinedByString:joiner];
NSLog(@"joinedStrings: %@", joinedStrings);
输出:
joinedStrings:one:two:three