Để lấy N ký tự cuối của chuỗi trong Swift, cách hiện đại (Swift 4+) là dùng suffix(_:). Cách cũ substring(from:) đã deprecated.
Cách 1: suffix(_:) - Khuyến khích (Swift 4+)
let str = "12312$$33@"
let last4 = str.suffix(4) // Substring: "33@"
let last4String = String(last4) // Convert về String: "33@"
print(last4String)
Cách 2: substring(from:) - Cũ (Swift 3, Deprecated)
// Deprecated: 'substring(from:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator.
let last4 = str.substring(from: str.index(str.endIndex, offsetBy: -4))
Kết quả

Extension tiện lợi
extension String {
func last(_ count: Int) -> String {
guard count > 0 else { return "" }
return String(suffix(count))
}
}
// Sử dụng:
"12312$$33@".last(4) // "33@"
"Hello".last(10) // "Hello" (an toàn nếu count > length)
"".last(3) // ""
Lưu ý
suffix(_:)trả vềSubstring(zero-copy view vào string gốc). Chuyển thànhStringnếu cần lưu lâu/dùng độc lập.- Nếu
count > string.count,suffixtrả về toàn bộ string (không crash). - Đếm ký tự Unicode (grapheme clusters), không phải byte – đúng với emoji, ký tự kết hợp.