Iterate through a String Swift 2.0

旧巷老猫 提交于 2019-11-27 04:35:05

As of Swift 2, String doesn't conform to SequenceType. However, you can use the characters property on String. characters returns a String.CharacterView which conforms to SequenceType and so can be iterated through with a for loop:

let word = "Zebra"

for i in word.characters {
    print(i)
}

Alternatively, you could add an extension to String to make it conform to SequenceType:

extension String: SequenceType {}

// Now you can use String in for loop again.
for i in "Zebra" {
    print(i)
}

Although, I'm sure Apple had a reason for removing String's conformance to SequenceType and so the first option seems like the better choice. It's interesting to explore what's possible though.

lchamp

String doesn't conform to SequenceType anymore. However you can access the characters property of it this way:

var word = "Zebra"

for i in word.characters {
    print(i)
}

Note that the documentation hasn't been updated yet.

Swift 3.0.1

Use the indices property of the characters property to access all of the indices of individual characters in a string.

let greeting = "Guten Tag!"
for index in greeting.characters.indices {
print("\(greeting[index]) ", terminator: "")
}
// Prints "G u t e n   T a g ! "

visit https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/StringsAndCharacters.html

Swift 4

Forin loop:

let word = "Swift 4"
for i in word {
    print(i)
}

map example:

let word = "Swift 4"
_ = word.map({ print($0) })

forEach example:

let word = "Swift 4"
word.forEach({ print($0) })
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!