我正在做一个Swift编程书的实验,并坚持在struct本身内部构造一个struct。但错误报告参数已解包。我怎么能把它作为参数值?
struct Card {
var rank: Rank
var suit: Suit
func simpleDescription() -> String {
return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
}
func FullDeck() -> Card[] {
var deck: Card[]
for i in 1...13
{
for j in 0...3
{
let rank_para = Rank.fromRaw(i)
let suit_para = Suit.fromRaw(j)
**deck.append(Card(rank: rank_para, suit : suit_para ))
//value of optional type unwrapped;did you mean to use ? or !**
}
}
return deck
}
}
enum Rank: Int {
case Ace = 1
case Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten
case Jack, Queen, King
func simpleDescription() -> String {
switch self {
case .Ace:
return "ace"
case .Jack:
return "jack"
case .Queen:
return "queen"
case .King:
return "king"
default:
return String(self.toRaw())
}
}
func compare(sec:Rank) -> Bool {
var first = 0
var second = 0
if self.toRaw() == 1 {
first = 1
} else {
first = self.toRaw()
}
if sec.toRaw() == 1 {
second = 1
} else {
second = self.toRaw()
}
return first > second
}
}
enum Suit: Int{
case Spades = 0
case Hearts, Diamonds, Clubs
func simpleDescription() -> String {
switch self {
case .Spades:
return "spades"
case .Hearts:
return "hearts"
case .Diamonds:
return "diamonds"
case .Clubs:
return "clubs"
}
}
}
答案 0 :(得分:1)
fromRaw
方法返回一个可选值:Rank?
和Suit?
。这意味着价值可能是零。你需要检查一下:
if let aRank = rank_para {
if let aSuit = suit_para {
deck.append(Card(rank: aRank, suit: aSuit))
}
}
使用"如果让",你"打开"可选值为值(aRank和aSuit),不再是可选的(不能为零)。
if rank_para and suit_para {
deck.append(Card(rank: rank_para!, suit: suit_para!))
}
在这里,您正在检查rank_para和suit_para是否为零。如果两者都没有,你打电话给追加和"打开"使用!
的可选值。 !
表示如果值nil
抛出运行时错误,则将此变量视为不能nil
。