4

I am trying some simple code, which I found on natashatherobot.com.

var str = "Hello, playground"

let rangeOfHello = Range(start: str.startIndex, end: advance(str.startIndex, 5))
let helloStr = str.substringWithRange(rangeOfHello)
return helloStr

It works fine when I try it in Playgrounds:

Playground

But when I try using it in my Xcode project it gives me a compilation error:

Xcode Project

Any ideas why this is happening?

3 Answers 3

2

In your function declaration you are saying that it returns a void, but you are trying to return a string, You need to add the -> String in the end of your function to match what you are trying to do

your function:

func getStringBetween(startString: String, endString: String) -> ()

shoud be:

func getStringBetween(startString: String, endString: String) -> String
Sign up to request clarification or add additional context in comments.

Comments

2

You did not specify the return type of your func:

func getStringBetween(startString: String, endString: String) -> String {

Comments

0

The problem is the method getStringBetween(:endString:), which you defined in your extension for String.
This method does not define a return type (there's no -> Type after the parameter list). Therefore the implicit return type is Void, so your method could be written as:

func getStringBetween(startString: String, endString: String) -> Void

In Swift the type Void is equivalent to an empty tuple ().

The problem is therefore that Swift expects a return type of Void denoted by (), but you're returning a String.
This problem is easily fixed by adding the return type String to the declaration of your method:

func getStringBetween(startString: String, endString: String) -> String

Side Note:
When writing return, without a specification of what is to be returned, Swift automatically returns ().

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.