1

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>')

2 Answers 2

2

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"
Sign up to request clarification or add additional context in comments.

Comments

0
  • 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.