0

I don't know why this won't work. I'm trying to automatically generate a list of numbers up to a limit "upTo" but it doesn't work.

I suspect it will be something obvious like "num" not being an array. I've tried this and it hasn't worked.

func tTables(set1 : [Int], upTo: Int) -> [Int] {
        var array = set1
        
        ForEach(1 ..< upTo + 1){num in
            array.append(num)
        }

        return array
    }

Please be descriptive as I'm only a beginner.

1
  • I'm not familiar with this area - but I wonder if this is better tagged as Swift, rather than SwiftUI. I assume there is no UI involvement here. Commented Nov 26, 2020 at 12:46

2 Answers 2

2

ForEach is a SwiftUI view container, ie view, you should use swift for-in operator instead

func tTables(set1 : [Int], upTo: Int) -> [Int] {
        var array = set1
        
        for num in 1 ..< upTo + 1 {
            array.append(num)
        }

        return array
    }
Sign up to request clarification or add additional context in comments.

Comments

1

To fill the array you could add the sequence as an array

func tTables(set1 : [Int], upTo: Int) -> [Int] {
    var array = set1
    array.append(contentsOf: Array(1...upTo))
    return array
}

tTables(set1: array, upTo: 5)

another way to do it is to use inout instead of returning an array

func tTables(set1 : inout [Int], upTo: Int) {
    set1.append(contentsOf: Array(1...upTo))
}

var array = [Int]()
tTables(set1: &array, upTo: 5)

But if the variable you pass to the function is always empty you could skip the function altogether and directly initialise the array with a sequence

let array = Array(1...5)

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.