È possibile utilizzare stride(from:, to:, by:)
per iterare ogni 2 caratteri nella stringa e utilizzare semplicemente join(with: separator)
per concatenare nuovamente la stringa.
Swift 4
extension String {
var pairs: [String] {
var result: [String] = []
let characters = Array(self)
stride(from: 0, to: count, by: 2).forEach {
result.append(String(characters[$0..<min($0+2, count)]))
}
return result
}
mutating func insert(separator: String, every n: Int) {
self = inserting(separator: separator, every: n)
}
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self)
stride(from: 0, to: count, by: n).forEach {
result += String(characters[$0..<min($0+n, count)])
if $0+n < count {
result += separator
}
}
return result
}
}
Swift 3
extension String {
var pairs: [String] {
var result: [String] = []
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: 2).forEach {
result.append(String(characters[$0..<min($0+2, characters.count)]))
}
return result
}
mutating func insert(separator: String, every n: Int) {
self = inserting(separator: separator, every: n)
}
func inserting(separator: String, every n: Int) -> String {
var result: String = ""
let characters = Array(self.characters)
stride(from: 0, to: characters.count, by: n).forEach {
result += String(characters[$0..<min($0+n, characters.count)])
if $0+n < characters.count {
result += separator
}
}
return result
}
}
Testing
let str1 = "112312451"
let finalString1 = str1.pairs.joined(separator: ":") // "11:23:12:45:1"
print(str1) // "112312451\n"
let finalString2 = str1.inserting(separator: ":", every: 2) // "11:23:12:45:1"
print(str1) // "112312451\n"
var str2 = "112312451"
str2.insert(separator: ":", every: 2)
print(str2) // "11:23:12:45:1\n"
fonte
2015-12-24 15:02:34
Per la cronaca e il tuo vantaggio in futuro, ':' è un "due punti". "Virgola" significa ','. – Arc676
cosa hai provato finora? nota che l'unica linea di codice che hai fornito non è in realtà nemmeno un codice valido – luk2302