for (char x='A'; x<='Z'; x++) {
在Swift中,这是不可能的。知道怎么做吗?
答案 0 :(得分:13)
在Swift中,你可以像这样在字符串上迭代字符:
Swift 2
for char in "abcdefghijklmnopqrstuvwxyz".characters {
println(char)
}
Swift 1.2
for char in "abcdefghijklmnopqrstuvwxyz" {
println(char)
}
可能有更好的方法。
答案 1 :(得分:13)
这有点麻烦,但以下作品(Swift 3/4):
for value in UnicodeScalar("a").value...UnicodeScalar("z").value { print(UnicodeScalar(value)!) }
我怀疑这里的问题是&#34; a&#34; ...&#34; z&#34;对于不同的字符串编码可能会有所不同。
(旧东西)
也很麻烦,但没有额外的中间变量:
for letter in map(UnicodeScalar("a").value...UnicodeScalar("z").value, {(val: UInt32) -> UnicodeScalar in return UnicodeScalar(val); })
{
println(letter)
}
答案 2 :(得分:6)
for i in 97...122{println(UnicodeScalar(i))}
答案 3 :(得分:2)
针对Swift 3.0及更高版本进行了更新
let startChar = Unicode.Scalar("A").value
let endChar = Unicode.Scalar("Z").value
for alphabet in startChar...endChar {
if let char = Unicode.Scalar(alphabet) {
print(char)
}
}
答案 4 :(得分:1)
此解决方案适用于Swift 3.0,并将打印出每个OP请求的值:
"ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.flatMap { print($0) }
或者为您提供一系列字母:
let alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ".characters.flatMap { $0.description }
答案 5 :(得分:1)
Swift 4.2 版本要容易得多
for char in "abcdefghijklmnopqrstuvwxyz" {
print(char)
}
答案 6 :(得分:0)
“纯功能” 快速5 方式:
(Unicode.Scalar("A").value...Unicode.Scalar("Z").value).forEach({
let letter = Unicode.Scalar($0)!
print(letter)
/* do other stuff with letter here */
})
答案 7 :(得分:0)
extension ClosedRange where Bound == UnicodeScalar {
func toArray() -> [UnicodeScalar] {
(lowerBound.value...upperBound.value).compactMap { UnicodeScalar($0) }
}
}
extension ClosedRange where Bound == String {
func toArray() -> [UnicodeScalar]? {
guard let lower = lowerBound.first?.unicodeScalars.first,
let upper = upperBound.first?.unicodeScalars.first else { return nil }
return (lower...upper).toArray()
}
}
("a"..."z").toArray() // option 1
(UnicodeScalar("a")...UnicodeScalar("z")).toArray() // option 2
答案 8 :(得分:-1)
你试过这个吗?
for var myChar:CChar = 65 ; myChar <= 90 ; ++myChar {
let x:String = String(format: "%c", myChar)
println(x)
}
如果您已经知道字符代码