swift数组存储数据

时间:2016-07-03 21:58:50

标签: arrays swift function

我创建了一个返回多个值的函数

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
            ki=kind
        }
    }
    }
    return (largest , ki!)
}

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

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

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

如何将函数中返回的值存储在数组

2 个答案:

答案 0 :(得分:0)

<强>更新

如果您希望单个数组中的两个值ar[0]Intar[1]String,则您需要声明ar2 } {是[Any]并在初始化ar2时解压缩元组:

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

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

如果您只是将回报分配给ar2并将其保留为元组,则可以使用ar2.0ar2.1访问值:

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

或者,如果您更改largestNum以返回命名元组:

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

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

原始答案:

声明数组ar2以保存IntString的元组对,然后将返回值包装在[]中以创建数组:

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

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

因为元组实际上是用于临时值,所以使用struct将值存储在数组中会更好:

更改您的功能以返回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)]

如果您希望ar2只保留一个值,那么只需执行以下操作:

var ar2 = largestNum(interestingNumbers)

和Swift会推断出类型(原始代码中的元组或使用InterestingNumber时的struct

答案 1 :(得分:0)

您的代码在xcode 7.3.1 playground

中运行正常 好的,现在我得到你的问题了:

for in loop

函数定义中箭头后面的部分是类型(我认为称为tupel),您可以将它用作变量。