first 10 characters or less of a string of any size in swift

To get the first 10 characters or less of a string in Swift, you can use the prefix method with a range.

Here's an example:

main.swift
let str = "The quick brown fox jumps over the lazy dog"
let prefixLength = min(str.count, 10)
let prefix = str.prefix(prefixLength)
print(prefix)
146 chars
5 lines

This will output:

main.swift
The quick
10 chars
2 lines

In this example, we first get the length of the prefix by taking the minimum of the string's length and 10. This ensures that if the string is shorter than 10 characters, we won't try to get characters that are out of bounds.

We then use the prefix method to get a substring of the original string that contains the first prefixLength characters.

Finally, we print the prefix substring.

related categories

gistlibby LogSnag