ClosedInterval< String>到Swift中的[String] [英] ClosedInterval<String> to [String] in Swift

查看:44
本文介绍了ClosedInterval< String>到Swift中的[String]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么呢?

let i = 1...100
let s = [Int](i)

收益

[1, 2, 3, ..., 100]

但是

let i = "a"..."z"
let s = [String](i)

收益

Cannot invoke initializer for type '[String]' with an argument list of type '(ClosedInterval<String>)'

i.contains("b")

收益

true

推荐答案

Int 符合 ForwardIndexType ,因此在

let i = 1...100

... 是运算符

public func ...<Pos : ForwardIndexType where Pos : Comparable>(start: Pos, end: Pos) -> Range<Pos>

,结果为 Range< Int> .范围是集合和序列:可以枚举范围的元素并从中创建一个数组.

and the result is a Range<Int>. Ranges are collections and sequences: One can enumerate the elements of the range and create an array from it.

但是 String Character 不符合 ForwardIndexType :没有方法可以从一个字符串或字符前进到下一个字符串或字符.因此在

But String and Character do not conform to ForwardIndexType: There is no method to advance from one string or character to the next. Therefore in

let i = "a"..."z"

... 是运算符

public func ...<Bound : Comparable>(start: Bound, end: Bound) -> ClosedInterval<Bound>

,结果为 ClosedInterval< String> .您可以检查是否该间隔中包含特定的字符串,但是您不能枚举其元素.

and the result is a ClosedInterval<String>. You can check if a particular string is contained in that interval, but you can not enumerate its elements.

"a" ..."z" 表示"a"< = s< ="z" 根据Unicode标准,而不仅仅是26个小写字母从英文字母比较,例如这是什么意思Swift中的字符串和字符比较不区分语言环境?.例如

"a"..."z" represents all strings s for which "a" <= s <= "z" according to the Unicode standard, and not just the 26 lowercase letters from the english alphabet, compare e.g. What does it mean that string and character comparisons in Swift are not locale-sensitive?. For example

let c = i.contains("ä")

产生 true .

在Swift 3中,范围和间隔类型已重命名,重新组织:

In Swift 3, the range and interval types have been renamed and reorganized:

"1" ... "100"  // CountableClosedRange<Int>
"a" ... "z"    // ClosedRange<String>

如果您打算创建一个包含所有字符的数组然后根据它们在Unicode表中的顺序从"a"到"z"您可以枚举 UTF-32 代码单元:

If your intention is to create an array with all characters from "a" to "z" according to their ordering in the Unicode tables then you can enumerate the UTF-32 code units:

let i = UnicodeScalar("a").value ... UnicodeScalar("z").value
let charArray = (i.map { Character(UnicodeScalar($0)) })
// or
let stringArray = (i.map { String(UnicodeScalar($0)) })

结果是

["a", "b", "c", ... , "z"]

作为 Character 的数组或 String 的数组.

这篇关于ClosedInterval&lt; String&gt;到Swift中的[String]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆