如何计算 Swift 中字符串中前导空格的数量?

How to count number of leading spaces in a string in Swift?

我想知道如何计算 Swift 中字符串中前导空格的数量。

也就是说,如果字符串是" Hello world ",结果应该是2

谢谢

一种方法是使用 prefix(while:),然后计算您得到了多少个字符:

yourString.prefix(while: { [=10=] == " " }).count