Implementing functions in swift

2019-05-18 03:17发布

I am new to swift and trying to implement a simple function that takes minimum and max number as input and returns an array with all the numbers in the limit. I am getting an error //Error: Reference to generic type 'Array' requires arguments in <...> may I know what I am missing on?

func serialNumberLimits(minimumNumber n1:Int, maximumNumber n2:Int) -> Array {

// Initialized an empty array
var array = Int[]()

//Initialized a "Temp" variable
var temp:Int = 0


for index in n1..n2 {

    temp += n1
    n1++

    if index == 1 { array.insert(temp, atIndex: 0) }

    else { array.insert(temp, atIndex: index-1) }

}

return array

}

1条回答
孤傲高冷的网名
2楼-- · 2019-05-18 04:02

Use following function
1)As you are using n1 in function and changing its value so declare it as var as all parameters are constants in swift by default

2)Use Array<Int> as it needs to be define which type of array is in swift.Swift is strongly typed language so all type need to be defined.

Run following code it will compile with no errors

func serialNumberLimits(var minimumNumber n1:Int, maximumNumber n2:Int) -> Array<Int> {

    // Initialized an empty array
    var array = Int[]()

    //Initialized a "Temp" variable
    var temp:Int = 0


    for index in n1..n2 {

        temp += n1
        n1++

        if index == 1 { array.insert(temp, atIndex: 0) }

        else { array.insert(temp, atIndex: index) }

    }

    return array

}
查看更多
登录 后发表回答