我正在尝试编写一些代码,以便在我正在开发的应用程序中将一些测试数据播种到核心数据数据库中,关于 Pokémon。我的播种代码基于此:http://www.andrewcbancroft.com/2015/02/25/using-swift-to-seed-a-core-data-database/
不过我在一件事上遇到了一个小问题。我似乎无法将 nil 值放入元组中。
我目前正在尝试将一些 Pokémon Move 播种到数据库中。一个 Action 可以有一堆不同的属性,但它具有哪种组合完全取决于 Action 本身。所有种子 Move 数据都在一个元组数组中。
为了证明...
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
]
...很好。这是一个具有上述所有属性的移动,其中 speedPriority 中的零意味着什么。但是,有些 Action 没有power 或accuracy 属性,因为它们与特定 Action 无关。但是,在没有power 或accuracy 命名元素的数组中创建第二个元组,例如...
(name: "Acupressure", moveType: normal!, category: "Status", powerpoints: 30, effect: "Sharply raises a random stat", speedPriority: 0)
...可以理解地抛出一个错误
Tuple types {firstTuple} and {secondTuple} have a different number of elements (8 vs. 6)
因为,好吧,元组有不同数量的元素。因此,我尝试...
(name: "Acupressure", moveType: normal!, category: "Status", power: nil, accuracy: nil, powerpoints: 30, effect: "Sharply raises a random stat", speedPriority: 0)
但这也没有用,因为它给出了错误:
Type 'Int' does not conform to protocol 'NilLiteralConvertible'
那么,有什么方法可以做我想做的事吗?有没有办法在元组中放置一个 nil 值,或者以某种方式使其成为可选元素?感谢!
最佳答案
你可以做如下的事情:
typealias PokemonMove = (name: String?, category: String?)
var move1 : PokemonMove = (name: nil, category: "Special")
let moves: [PokemonMove] = [
(name: nil, category: "Special"),
(name: "Absorb", category: "Special")
]
根据需要添加更多参数,我只拿了两个参数来解释概念。
关于swift - 在 Swift 的元组中是否可以有一个 nil 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29489647/