天天看点

mips汇编代码示例解释_通过代码示例快速解释范围 范围类型 (Types of ranges) 在Swift中将范围转换为NSRange (Converting a Range to an NSRange in Swift) 范围和字符串 (Ranges and Strings) 使用字符串索引 (Working with String indexes) 结论 (Conclusion)

mips汇编代码示例解释

Ranges in Swift allow us to select parts of Strings, collections, and other types. They’re the Swift variant of NSRange which we know from Objective-C although they’re not exactly the same in usage, as I’ll explain in this blog post.

Swift中的范围使我们可以选择字符串,集合和其他类型的一部分。 它们是NSRange的Swift变体,我们从Objective-C知道,尽管它们的用法并不完全相同,我将在此博客文章中进行解释。

Ranges allow us to write elegant Swift code by making use of the range operator. Your first time working with them might be because you needed to select a range of characters from a String but there’s a lot more you can do with it!

范围允许我们通过使用范围运算符来编写精美的Swift代码。 第一次与他们合作可能是因为您需要从字符串中选择一系列字符,但是您可以做更多的事情!

范围类型 (Types of ranges)

There are multiple types of ranges in Swift you can use. The easiest way of working with them is by making use of the range operator. Let’s go over the different types available in Swift.

您可以在Swift中使用多种类型的范围。 使用它们的最简单方法是使用范围运算符。 让我们看一下Swift中可用的不同类型。

近程运算符从a…b (Closed range operator going from a…b)

let range: ClosedRange = 0...10
print(range.first!) // 0
print(range.last!) // 10
           

A closed range operator going from

a...b

defines a range that includes both a and b in which

a

must not be greater than

b

.

a...b

开始的封闭范围运算符定义的范围包括a 和 b,其中

a

不得大于

b

The closed operator is useful if you’d like to use all the values. For example, if you’d like to iterate over all elements of a collection:

如果您想使用所有值,则封闭运算符很有用。 例如,如果您要遍历集合的所有元素:

let names = ["Antoine", "Maaike", "Jaap"]
for index in 0...2 {
    print("Name \(index) is \(names[index])")
}
// Name 0 is Antoine
// Name 1 is Maaike
// Name 2 is Jaap
           

The different types of operators can also be used to select elements from a collection. For this, however, we need to make use of the

CountableClosedRange

type:

还可以使用不同类型的运算符从集合中选择元素。 但是,为此,我们需要使用

CountableClosedRange

类型:

let names = ["Antoine", "Maaike", "Jaap"]
let range: CountableClosedRange = 0...2
print(names[range]) // ["Antoine", "Maaike", "Jaap"]
           

Obviously, Swift is smart enough to detect the countable variant by itself. Therefore, you could write the above code as follows:

显然,Swift足够聪明,可以自行检测可数的变体。 因此,您可以编写上面的代码,如下所示:

let names = ["Antoine", "Maaike", "Jaap"]
print(names[0...2]) // ["Antoine", "Maaike", "Jaap"]
           

半开范围运算符从a .. <b (Half-open range operator going from a..<b)

let range: Range = 0..<10
print(range.first!) // 0
print(range.last!) // 9
           

A half-open range defines a range going from

a

to

b

but does not include

b

. It's named half-open as it's containing its first value but not its final value. Just like with the closed range, the value of

a

must not be greater than

b

.

半开范围定义从

a

b

的范围,但不包括

b

。 它被命名为“ 半开”,因为它包含其第一个值而不是最终值。 就像与封闭的范围内,价值

a

必须不大于

b

The half-open operator can be used to iterate over zero-based lists such as arrays and collections in Swift in which you want to iterate up to but not including the length of the list. It’s basically the same as the earlier code example but now we can make use of the

count

property:

半开运算符可用于遍历基于零的列表,例如Swift中的数组和集合,您要在其中迭代直到(但不包括)列表的长度。 它与前面的代码示例基本相同,但是现在我们可以使用

count

属性:

let names = ["Antoine", "Maaike", "Jaap"]
print(names[0..<names.count]) // ["Antoine", "Maaike", "Jaap"]
           

If we would’ve done the same with a closed operator we would run into the following error:

如果对封闭的运算符执行相同的操作,则会遇到以下错误:

Fatal error: Array index is out of range

致命错误:数组索引超出范围

单边操作员从… (One-sided operator going from a…)

A one-sided range operator only defines one side of the bounds, for example,

a...

or

...b

. A one-sided range goes as far as possible in one direction—for example, taking all the elements of an array from the start of the array to index 2:

单边范围运算符仅定义边界的一侧,例如

a...

...b

。 单边范围在一个方向上尽可能地延伸-例如,将数组的所有元素从数组的开始到索引2:

let names = ["Antoine", "Maaike", "Jaap"]
print(names[...2]) // ["Antoine", "Maaike", "Jaap"]
           

Or taking all the elements starting from index 1 till the end of the array:

或取所有从索引1开始到数组结尾的元素:

let names = ["Antoine", "Maaike", "Jaap"]
print(names[1...]) // ["Maaike", "Jaap"]
           

A one-sided range can be used for iteration but only if used with a starting value

a...

. Otherwise, it's unclear where the iteration should start. Iterating over a one-sided range requires you to manually check where the loop should end as it would otherwise continue indefinitely.

单边范围可以用于迭代,但前提是必须与起始值

a...

。 否则,不清楚迭代应该在哪里开始。 在单边范围内进行迭代需要您手动检查循环应在何处结束,否则循环将无限期继续。

let neededNames = 2
var collectedNames: [String] = []
for index in 0... {
    guard collectedNames.count != neededNames else { break }
    collectedNames.append(names[index])
}
print(collectedNames) // ["Antoine", "Maaike"]
           

在Swift中将范围转换为NSRange (Converting a Range to an NSRange in Swift)

Sooner or later you might run into an issue when you want to convert a

Range

into a

NSRange

type. For example, if you're working with an

NSAttributedString

in which you like to apply attributes to a specific range. In the following example, we'd like to apply an orange color to "Swift" in the title:

想要将

Range

转换为

NSRange

类型时,迟早可能会遇到问题。 例如,如果您正在使用

NSAttributedString

,您希望在其中将属性应用于特定范围。 在下面的示例中,我们想为标题中的“ Swift”应用橙色:

let title = "A Swift Blog"
let range = title.range(of: "Swift")
let attributedString = NSMutableAttributedString(string: title)
attributedString.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], range: range) // Cannot convert value of type 'Range<String.Index>?' to expected argument type 'NSRange' (aka '_NSRange')
           

As

Range

can't be converted to

NSRange

we're running into the following error:

由于

Range

无法转换为

NSRange

我们

NSRange

以下错误:

Cannot convert value of type ‘Range?’ to expected argument type ‘NSRange’ (aka ‘_NSRange’)

无法转换“范围”类型的值? 到预期的参数类型“ NSRange”(又名“ _NSRange”)

We can fix this by making use of the available convenience initializer of an

NSRange

that takes a Swift

Range

:

我们可以通过使用采用Swift

Range

NSRange

便利初始化程序来解决此问题:

let convertedRange = NSRange(range, in: title)
           

The final code will look as follows:

最终代码如下所示:

let title = "A Swift Blog"
let range = title.range(of: "Swift")!
let convertedRange = NSRange(range, in: title)
let attributedString = NSMutableAttributedString(string: title)
attributedString.setAttributes([NSAttributedString.Key.foregroundColor: UIColor.orange], range: convertedRange)
print(attributedString)
// A {
// }Swift{
//     NSColor = "UIExtendedSRGBColorSpace 1 0.5 0 1";
// } Blog{
// }
           

范围和字符串 (Ranges and Strings)

Strings and ranges are a bit more special. As you might know, a

String

is actually a collection of characters. However, not every character is of the same size. We can demonstrate this by working with a

NSRange

and a

NSString

that contains an emoji:

字符串和范围更特殊。 您可能知道,

String

实际上是字符的集合。 但是,并非每个字符都具有相同的大小。 我们可以通过使用

NSRange

和包含表情符号的

NSString

来证明这一点:

let emojiText: NSString = "🚀launcher"
print(emojiText.substring(with: NSRange(location: 0, length: 2)))
// Expected: 🚀l
// Actually returns: 🚀
           

As you can see, the rocket emoji is more than 1 character long. Therefore, our substring is not returning the expected outcome.

如您所见,火箭表情符号的长度超过1个字符。 因此,我们的子字符串没有返回预期的结果。

使用字符串索引 (Working with String indexes)

The solution to this problem is to make use of

Range<String.Index>

instead of

Range<Int>

. The

String.Index

takes into account the actual size of a character. We can only make use of a half-open

Range

as that's required by the

String

subscript.

解决此问题的方法是使用

Range<String.Index>

而不是

Range<Int>

String.Index

考虑了字符的实际大小。 我们只能使用

String

下标所要求的半开

Range

let emojiText = "🚀launcher"
let endIndex = emojiText.index(emojiText.startIndex, offsetBy: 2)
let range: Range<String.Index> = emojiText.startIndex..<endIndex
print(emojiText[range]) // 🚀l
           

结论 (Conclusion)

That was it! Hopefully, you’ve learned a bit more about the possibilities that Swift gives us when working with ranges and collections. We used closed, half-open, and one-sided operators that all have their pros and cons.

就是这样! 希望您已学到更多有关Swift在处理范围和集合时为我们提供的可能性的信息。 我们使用了封闭式,半开放式和单面运算符,它们各有利弊。

If you like to improve your Swift knowledge, even more, check out the Swift category page. Feel free to contact me or tweet to me on Twitter if you have any additional tips or feedback.

如果您想进一步提高Swift知识,请查看Swift类别页面 。 如果您有其他任何提示或反馈,请随时与我联系或在Twitter上发给我。

Thanks!

谢谢!

Originally published at SwiftLee.

最初发表在 SwiftLee上 。

More posts and updates: @twannl

更多帖子和更新: @twannl

翻译自: https://medium.com/flawless-app-stories/ranges-in-swift-explained-with-code-examples-ced68c750bd5

mips汇编代码示例解释