Omar Diab Omar Diab - 3 months ago 13
Swift Question

swift array storing data

I made a function that returns multiple values

let interestingNumbers = [ // String:Array<Int>
"Prime": [2, 3, 5, 7, 11, 23],
"Fibonacci": [1, 1, 2, 3, 5, 80],
"Square": [1, 4, 9, 16, 25],
func largestNum(objDictionary:[String:Array<Int>]) -> (Int,String) {
var largest = 0
var ki:String? = nil
for (kind, numbers) in interestingNumbers {
for number in numbers {
if number > largest {
largest = number
return (largest , ki!)

print(largestNum(interestingNumbers)) //calling fuction and print

/*var ar2:[Int,String] = largestNum(interestingNumbers))

print(ar2)*/' this code have an error`

How can I store the returned values from the function in the array



If you want both values in a single array with ar[0] being the Int and ar[1] being the String, then you'll need to declare ar2 to be [Any] and unpack the tuple when initializing ar2:

let largest = largestNum(interestingNumbers)
var ar2:[Any] = [largest.0, largest.1]

print(ar2) // [80, "Fibonacci"]

If you just assign the return to ar2 and leave it as a tuple, you can access the values with ar2.0 and ar2.1:

var ar2 = largestNum(interestingNumbers)
print(ar2.0)  //  80
print(ar2.1)  //  "Fibonacci"

Or if you change your largestNum to return a named tuple:

func largestNum(objDictionary:[String:Array<Int>]) -> (number: Int, kind: String) {

var ar2 = largestNum(interestingNumbers)
print(ar2.number)  //  80
print(ar2.kind)    // "Fibonacci"

Original Answer:

Declare your array ar2 to hold tuples pairs of Int and String, and then wrap your return value in [] to create an array:

var ar2:[(Int,String)] = [largestNum(interestingNumbers)]

print(ar2)  // [(80, "Fibonacci")]

Because tuples are really meant for temporary values, it is better style to store values in an array using a struct:

Change your function to return an InterestingNumber:

struct InterestingNumber {
    let kind: String
    let number: Int

func largestNum(objDictionary:[String:Array<Int>]) -> InterestingNumber {
    // contents omitted for brevity

    return InterestingNumber(kind: ki!, number: largest)

let largest = largestNum(interestingNumbers)

// Define your array to hold `InterestingNumber`s:   
var ar2:[InterestingNumber] = [largest]

print(ar2)  // [InterestingNumber(kind: "Fibonacci", number: 80)]

If you meant for ar2 to just hold a single value, then simply do:

var ar2 = largestNum(interestingNumbers)

and Swift will infer the type (which is a tuple in your original code or an InterestingNumber when using the struct.