是否可以在Swift元组中使用nil值?

Rhy*_*gan 1 null tuples swift

我正在尝试编写一些代码,用于将一些测试数据播种到我正在开发的关于神奇宝贝的应用程序的核心数据数据库中.我的播种代码基于此:http://www.andrewcbancroft.com/2015/02/25/using-swift-to-seed-a-core-data-database/

我有一件事有点问题.我似乎无法在元组中添加nil值.

我正在尝试将一些神奇宝贝动作播种到数据库中.移动可以有许多不同的属性,但它具有哪种组合完全取决于移动本身.所有种子移动数据都在元组数组中.

展示...

let moves = [
    (name: "Absorb", moveType: grass!, category: "Special", power: 20, accuracy: 100, powerpoints: 25, effect: "User recovers half the HP inflicted on opponent", speedPriority: 0),
    // Snip
]
Run Code Online (Sandbox Code Playgroud)

......很好.这是一个包含所有上述属性的举动,其中speedPriority为零意味着什么.但是,有些动作没有动力精确属性,因为它们与特定动作无关.但是,在数组中创建第二个元组而没有命名元素的精度,例如......

(name: "Acupressure", moveType: normal!, category: "Status", powerpoints: 30, effect: "Sharply raises a random stat", speedPriority: 0)
Run Code Online (Sandbox Code Playgroud)

......可以理解地抛出一个错误

元组类型{firstTuple}和{secondTuple}具有不同数量的元素(8对6)

因为,元组有不同数量的元素.所以相反,我试过......

(name: "Acupressure", moveType: normal!, category: "Status", power: nil, accuracy: nil, powerpoints: 30, effect: "Sharply raises a random stat", speedPriority: 0)
Run Code Online (Sandbox Code Playgroud)

但这也没有用,因为它给出了错误:

类型'Int'不符合协议'NilLiteralConvertible'

那么,有什么办法可以做我想做的事情吗?有没有办法在元组中放置一个nil值,或以某种方式使它成为一个可选元素?谢谢!

Abd*_*lah 6

您可以执行以下操作:

typealias PokemonMove = (name: String?, category: String?)

var move1 : PokemonMove = (name: nil, category: "Special")

let moves: [PokemonMove] = [
    (name: nil, category: "Special"),
    (name: "Absorb", category: "Special")
]
Run Code Online (Sandbox Code Playgroud)

根据需要添加更多参数,我只用了两个参数来解释概念.