我不知道如何解决它。我只想了解它的工作原理以及应该替换的内容。
I can't figure out how to fix it. I just want to understand how it works and what should be replaced.
我已经尝试删除个字符。
I've already tried to delete characters., but it still doesn't work.
import Foundation var shrinking = String("hello") repeat { print(shrinking) shrinking = String(shrinking.characters.dropLast()) } while shrinking.characters.count > 0我希望程序输出:
你好 地狱 hel he h
hello hell hel he h
,但根本不起作用。
推荐答案您的代码如果删除字符应该可以正常工作,建议您创建一个新的Playground文件。顺便说一句,您可以简单地使用 RangeReplaceableCollection 变异方法 popLast 并在字符串不为空时进行迭代,以避免调用集合计数属性多次:
Your code should work as it is if you delete the characters I suggest you create a new playground file. Btw you can simply use RangeReplaceableCollection mutating method popLast and iterate while your string is not empty to avoid calling your collection count property multiple times:
var shrinking = "hello" repeat { print(shrinking) shrinking.popLast() } while !shrinking.isEmpty这将打印
你好
hello
地狱
hel
he
h
或使用 removeLast 方法,但它要求字符串不为空,因此您需要在关闭前检查字符串是否为空:
or using removeLast method but it requires the string not to be empty so you would need to check if the string is empty at before the closure:
var shrinking = "hello" while !shrinking.isEmpty { print(shrinking) shrinking.removeLast() }更多推荐
“字符不可用”,请直接使用字符串
发布评论