1

I want to get values from one array, and put them into another array using recursion function.And want to notice that I do not want to use loop(like 'for in loop')

var rudics = ["one", "two", "three", "four", "five", "six"]
var array = [""]
func changeArray (var new:[String]) {
    array = [new.first!]
    if new.count > 0 {
    new.removeLast()
    changeArray(new)
    }
}

changeArray(rudics)

it gives me an error

fatal error: unexpectedly found nil while unwrapping an Optional value
Playground execution failed: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0).

and so on..

please help me!

1
  • the error might be at array = [new.first!]. You are doing it before checking for new.count and new might be empty at that time. Commented May 29, 2015 at 7:43

1 Answer 1

3

You might consider something like this:

var rudics = ["one", "two", "three", "four", "five", "six"]
var array = [String]()
func changeArray (var new:[String]) {
    if let first = new.first {
        array.append(first)
        new.removeAtIndex(0)
        changeArray(new)
    }
}

changeArray(rudics)
Sign up to request clarification or add additional context in comments.

8 Comments

when I call 'array' it gives [one", "one", "one", "one", "one", "one"]
Yep ... edited it. It was due to the fact that in your first example you take the first item but remove the last
You might consider correcting it in your question, since it was not central to the problem you posted.
Just it confused because I tried to reverse this array last time :) .At first I wrote new.removeAtIndex(0) as you did . :)
If I want to use optional value like new.first, should I always use optional binding? not just if statement?thats why my code shows an error?
|

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.