let s = "05554446677"
let s2 = String(format: "%@ (%@) %@ %@ %@",
s.substring(to: s.index(s.startIndex, offsetBy: 1)),
s.substring(with: s.index(s.startIndex, offsetBy: 1) ..< s.index(s.startIndex, offsetBy: 4)),
s.substring(with: s.index(s.startIndex, offsetBy: 4) ..< s.index(s.startIndex, offsetBy: 7)),
s.substring(with: s.index(s.startIndex, offsetBy: 7) ..< s.index(s.startIndex, offsetBy: 9)),
s.substring(with: s.index(s.startIndex, offsetBy: 9) ..< s.index(s.startIndex, offsetBy: 11))
)
Но это не работает, если строковые символы считаются более или менее 11
private func formattedNumber(number: String) -> String {
var cleanPhoneNumber = number!.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()
var mask = "+X (XXX) XXX XX-XX"
var result = ""
var index = cleanPhoneNumber.startIndex
for ch in mask.characters {
if index == cleanPhoneNumber.endIndex {
break
}
if ch == "X" {
result.append(cleanPhoneNumber[index])
index = cleanPhoneNumber.index(after: index)
} else {
result.append(ch)
}
}
return result
}
Итак, это лучше работает.
"" => ""
"0" => "+0"
"412" => "+4 (12"
"12345678901" => "+1 (234) 567 89-01"