Compare length of two strings: Difference between revisions
Content added Content deleted
No edit summary |
|||
Line 2,795: | Line 2,795: | ||
</pre> |
</pre> |
||
⚫ | |||
Swift provides a simple ''count'' property to find how many syntactic characters are in any given String. When counting bytes Swift supports Unicode codepoints. |
|||
In this example we use the ''sorted'' and ''forEach'' methods from the Sequence protocol to first sort our list into a new Array and then print each item in order. String interpolation is used to print the details of each item. |
|||
⚫ | |||
⚫ | |||
Here we use anonymous argument names with the ''sorted'' closure and a named argument with the ''forEach'' to illustrate how to use either style. |
|||
MainModule: { |
|||
⚫ | |||
let list = ["abcd", "abcd🤦♂️", "123456789", "abcdef", "1234567"] |
|||
list.sorted { $0.count > $1.count }.forEach { string in |
|||
_start: (λ |
|||
print("\(string) has \(string.count) characters") |
|||
} |
|||
(ret (< (size r) (size l))))) do |
|||
⚫ | |||
(lout width: 10 s " : " (size s) " code points") ) |
|||
) |
|||
⚫ | |||
{{out}} |
{{out}} |
||
<pre> |
<pre> |
||
123456789 has 9 characters |
|||
1234567 has 7 characters |
|||
abcdef has 6 characters |
|||
abcd🤦♂️ has 5 characters |
|||
abcd : 4 code points |
|||
abcd has 4 characters |
|||
</pre> |
</pre> |
||