Swift,包含整数的数组文字可以与整数数组互换使用吗?

Mak*_*tro 1 swift

在我的示例中,我有一个接受IndexSet的方法:

func printIndexSet(_ indexSet: IndexSet) {
    indexSet.forEach {
        print($0)
    }
}
Run Code Online (Sandbox Code Playgroud)

如果我尝试传递一个包含整数的数组文字,它可以推断出它的类型并构造一个indexSet:

printIndexSet([1, 2]) // Compiles fine
Run Code Online (Sandbox Code Playgroud)

如果我给它一个整数数组,虽然它不会编译

// The following fail with error:
// Cannot convert value of type '[Int]' to expected argument type 'IndexSet'
printIndexSet(Array<Int>([1,2]))
let indices: [Int] = [1, 2]
printIndexSet(indices)
Run Code Online (Sandbox Code Playgroud)

这里发生了什么事?

laj*_*eme 5

Swift中的类型和文字之间存在重要差异.

如你所说,[1,2]是一个数组文字.不是数组.数组文字基本上可用于创建符合ExpressibleByArrayLiteral的任何类型.

您可以使用数组文字来创建数组,但您可以使用它来创建其他类型,例如IndexSets.

随着printIndexSet([1, 2])你使用数组文本来创建一个索引集.

并且printIndexSet(Array<Int>([1,2]))给你一个错误,因为你的func期望一个IndexSet作为一个参数而不是一个Array.希望这可以帮助!

更新:

正如@rmaddy在我的回答下面的评论中正确指出的那样,IndexSet符合SetAlgebra,它符合ExpressibleByArrayLiteral.这就是您可以使用数组文字创建IndexSet的原因.

  • 你缺少的部分是`IndexSet`符合`SetAlgebra`,后者又符合`ExpressibleByArrayLiteral`,这就是OP的第一个例子有效的原因. (2认同)