UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

Cannot Pass Immutable Value as Inout argument: function call returns an immutable value, Type '()' cannot conform to 'sequence'

Forums > Swift

Here is some code I have written unfortunately it doesn't work. These are the errors I get: cannot pass immutable value as inout argument: function call returns an immutable value. Type '()' cannot conform to 'Sequence'.

func reverse( from array: inout [Int]) -> [Int] { var arrayRes : [Int] = [] if array == [] { return array } else if array.count == 1 { return array } else { // Swap first two members array.swapAt(0, 1) // Break down the array into smaller parts arrayRes = reverse( &Array(array[2..<array.count])) // Append one of the arrays which has been reversed and append the solved part return array[0...1] += arrayRes } }

2      

hi Mark,

i am not sure why you need an inout argument (your function call returns a new array, but it would also create the side effect on the incoming argument of swapping the first two elements). the easiest translation of your code to do what i think you want it to do is

func reverse(from array: [Int]) -> [Int] {
    guard array.count >= 2 else {
        return array
    }
    var firstTwoElements = Array(array[0...1])
    firstTwoElements.swapAt(0,1)
    return firstTwoElements + reverse(from: Array(array[2..<array.count]))
}

by the way, it helps to enclose any code you post by starting and ending with three consecutive backticks ``` on their own line. that's what triggers the code formatting above.

hope that helps,

DMG

2      

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.