天天看點

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彙編代碼示例解釋