例如:
func createArray(_ oneArray: [Int],_ twoArray: [Int],_ threeArray: [Int],_ one: Int,_ two: Int,_ three: Int) -> (oneArrayNew: [Int], twoArrayNew: [Int], threeArrayNew: [Int]){
// ...
// ... *random code*
// ...
// ...
return (oneArrayNew, twoArrayNew, threeArrayNew)
}
如果我想使用第一次调用(oneArrayNew, twoArrayNew, threeArrayNew)
的输出作为现在使用相同函数的输入来再次调用此函数,我该怎么做?
答案 0 :(得分:1)
您可以将元组分配给变量result
,然后访问每个成员:
let result = createArray(...
let result2 = createArray(result.oneArrayNew, result.twoArrayNew, ...
或者您可以将调用结果分配给元组以创建三个新变量:
let (a1, a2, a3) = createArray(...
let result2 = createArray(a1, a2, a3, ...
甚至重用现有变量:
var (a1, a2, a3) = createArray(...
(a1, a2, a3) = createArray(a1, a2, a3, ...
完整示例:
我通过从每个数组中删除前N
个项目来实现了创建新数组的功能。
在操场上尝试:
func createArray(_ oneArray: [Int],_ twoArray: [Int],_ threeArray: [Int],_ one: Int,_ two: Int,_ three: Int) -> (oneArrayNew: [Int], twoArrayNew: [Int], threeArrayNew: [Int]){
let oneArrayNew = Array(oneArray.dropFirst(one))
let twoArrayNew = Array(twoArray.dropFirst(two))
let threeArrayNew = Array(threeArray.dropFirst(three))
return (oneArrayNew, twoArrayNew, threeArrayNew)
}
let result = createArray([1,2,3,4], [5,6,7,8], [9,10,11,12], 1, 2, 3)
print(result.oneArrayNew) // [2, 3, 4]
print(result.twoArrayNew) // [7, 8]
print(result.threeArrayNew) // [12]
var (a1, a2, a3) = createArray([1,2,3,4], [5,6,7,8], [9,10,11,12], 2, 2, 2)
print(a1) // [3, 4]
print(a2) // [7, 8]
print(a3) // [11, 12]
(a1, a2, a3) = createArray(a1, a2, a3, 1, 1, 1)
print(a1) // [4]
print(a2) // [8]
print(a3) // [12]
答案 1 :(得分:0)
我相信您在这里谈论的是元组。这是一个例子。
func blah(x: Int, y: Int) -> (a: Int, b: Int) {
return (x,y)
}
let output = blah(1,1)
print(output.0, output.b) // You can access them using indices or the variable names. If they don't have names, you'll have to use indices.
关于将元组作为输入传递的内容,在Swift 2中已被弃用,后来在Swift 3中被移除了。因此,除了传递参数外,您别无选择
blah(output.a, output.b)
或者您甚至可以使用@vacawama answer中所示的多个变量。