问题描述:

I was trying to convert the below python code to swift

Python code

a0,a1,a2= map(int, [1,2,3])

print(a0,a1,a2)

Output: 1 2 3

Swift code

var a0,a1,a2:Int = [1,2,3]."What should be code here?"

Is there any one line solution for mapping object in swift like python ?

Note I already know that i can get the value with index, but i need a solution like python

网友答案:

You're doing a destructuring assignment in Python there, but Swift doesn't support it for arrays. You can only do that with tuples, like Squall pointed out in a comment.

Swift has a map function though, which you can use like so:

let result = [1, 2, 3].map { n in
    // `myFunction` could be any function or initializer you want
    return myFunction(n)
}

And a shorter equivalent is:

let result = [1, 2, 3].map(myFunction)

A translation of your code would be:

let result = [1, 2, 3].map { n in
    return Int(n)
}

This code does nothing though, because the array is already an array of int's.

相关阅读:
Top