TenaciousJay
TenaciousJay

Reputation: 6870

Range Operators (..< and ...) on Swift Strings

Can someone explain why half open and closed ranges no longer work the same on strings in Swift 3?

This code works:

var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start..<end   // <-- Half Open Range Operator still works
let ell = hello.substring(with: range)

But this does not:

var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start...end   // <-- Closed Range Operator does NOT work
let ello = hello.substring(with: range)   // ERROR

It results in an error like the following:

Cannot convert value of type 'ClosedRange<String.Index>' (aka 'ClosedRange<String.CharacterView.Index>') to expected argument type 'Range<String.Index>' (aka 'Range<String.CharacterView.Index>')

Upvotes: 1

Views: 574

Answers (2)

matt
matt

Reputation: 535284

To do what you're trying to do, don't call substring(with:). Just subscript directly:

var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let ello = hello[start...end] // "ello"

Upvotes: 2

Nhat Dinh
Nhat Dinh

Reputation: 3447

  • Why let range = start..<end work?

NSRange is what you need if you wanna use substring(with:) (described here).

Here is the definition of Range:

A half-open interval over a comparable type, from a lower bound up to, but not including, an upper bound.

To create a Range:

You create Range instances by using the half-open range operator (..<).

So bellow code is exactly true (and its will work):

var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start..<end   // <-- Half Open Range Operator still works
let ell = hello.substring(with: range)
  • Why let range = start...end not works:

With bellow you forced a ClosedRange to become an Range:

var hello = "hello"
let start = hello.index(hello.startIndex, offsetBy: 1)
let end = hello.index(hello.startIndex, offsetBy: 4)
let range = start...end   // <-- Closed Range Operator does NOT work
let ello = hello.substring(with: range)   // ERROR
  • How to convert ClosedRange to Range ?

Converting between half-open and closed ranges

Upvotes: 0

Related Questions