Hey so could do with some more experienced eyes looking at this issue I'm having.
I have two arrays of playable cards and non playable cards I need to have them as one array to pass into the game when it loads each level but the location of where the cards are added is important so I've made an array of the locations I want them inserted.
Here is my Card model and Level model with an example data
struct Card {
var content: String
var id: Int
var isFaceUp = false
var isMatched = false
}
struct Level {
let levelNumber: String
let numberOfNonCards: Int
let numberOfPlayableCards: Int
let locationsToPlacePlayableCards: [Int]
let winningScore: Int
}
static let levels = [ Level(levelNumber: "one", numberOfNonCards: 20, numberOfPlayableCards: 10, locationsToPlacePlayableCards: [3, 4, 6, 7, 9, 12, 20, 21, 22, 23], winningScore: 5) ] }
and below is me trying to get this to work.
private static func createCardGame(level: Level) -> [Card] {
var cards = [Card]()
var playableCards = [Card]()
for indexPath in 0..<level.numberOfNonCards {
cards.append(Card(content: catCards[0], id: indexPath*3))
}
for indexPath in 0..<level.numberOfPlayableCards {
playableCards.append(Card(content: catCards[indexPath], id: indexPath*2))
playableCards.append(Card(content: catCards[indexPath], id: indexPath*2 5))
}
playableCards.shuffle()
var playingCardLocations = level.locationsToPlacePlayableCards
for indexPath in 0..<playingCardLocations.count {
cards.insert(contentsOf: playableCards[indexPath], at: playingCardLocations[indexPath])
}
return cards
}
This isn't working as I have to make Card conform to Collection which seems to then require it conforms to Sequence and then IteratorProtocol. So wondering what's the best way to implement those protocols? Because can't find much about them? Or is there a better way of doing this in your experience? Would really appreciate your help and input.
CodePudding user response:
insert(contentsOf:at:)
expects to be passed a collection of elements to be inserted but it's only being passed a single card.
There's another version of insert that takes a single element. The only change is removing contentsOf
.
cards.insert(playableCards[indexPath], at: playingCardLocations[indexPath])
https://developer.apple.com/documentation/swift/array/3126951-insert
Another option is to put the card into an array before inserting it, but it's unnecessary when there's a method that takes a single value.
cards.insert(contentsOf: [playableCards[indexPath]], at: playingCardLocations[indexPath])