在swift 4.0中,直接调用reversed
字符串将完成工作
let str = "abc" String(str.reversed()) // This will give you cba
该函数reversed(_:)
迭代Character
所提供的字符串中的每一个s
,并以相反的顺序简单地将它们集中在一起.
// 1st pass in the 'for' loop: // @ start of iteration: 'str' equals "" // update value of 'str' according to // str = aCharacterAsString + str = "!" + "" // 2nd pass in the 'for' loop: // @ start of iteration: str equals "!" // update value of 'str' according to // str = anotherCharacterAsString + str = "p" + "!" // 3rd pass in the 'for' loop: // @ start of iteration: str equals "p!" // update value of 'str' according to // str = yetAnotherCharacterAsString + str = "l" + "p!" // and so on ... // after end of 'for' loop: str == "help!" // this value of 'str' is then return to callee (which prints it)
一个更简单的方法是使用reversed()
在CharacterView
对的String
实例:
let str = "!pleH" print(String(str.characters.reversed())) // Help!
Swift 4您可以直接在字符串中使用它
let str = "!pleH" print(String(str.reversed())) // Help!
内联注释,
func reverse(_ s: String) -> String { var str = "" //.characters gives the character view of the string passed. You can think of it as array of characters. for character in s.characters { str = "\(character)" + str //This will help you understand the logic. //!+"" //p+! //l+p! ... goes this way print ( str) } return str } print (reverse("!pleH"))
注意:如果您不想使用reversed()
内置功能,则可以使用以下代码。[面试要求]
在字符串上使用高阶函数“ Reduce ” 的一线。
extension String { func reverse() -> String { return self.reduce("") { "\($1)" + $0 } } }
var string = "My,playground and my Swift" var reverseString = "" for str in string { reverseString.insert(str, at: reverseString.startIndex) } print(reverseString)