Hi everyone ,
I am actually doing the tile map tutorial, I feel myself stuck with the meaning of a line in a method in the chapter 13: Intermediate Tile Maps page 364.
func tileGroupForName(tileSet: SKTileSet, name: String)
→ SKTileGroup? {
let tileGroup = tileSet.tileGroups
.filter { $0.name == name }.first
return tileGroup
}
This method returns a named tile group within a tile set to replace a tile texture.
The line I don’t understand is :
let tileGroup = tileSet.tileGroups
.filter { $0.name == name }.first
If anyone can help me pleaaaase
@nehemie
let tileGroup = tileSet.tileGroups.filter { $0.name == name }.first
First we have tileSet.tileGroups.filter {}
Here you can specify a new array which consists of values specified within the closure.
You can experiment with this in a playground.
This more explicit code:
var array = [1, 2, 3, 4, 5, 1, 2]
let newArray = array.filter ( { value -> Bool in
value == 1
})
in a playground will result in newArray
being equal to [1, 1]
In the book’s code, $0
is an inexplicit parameter. In the above code, $0
is replaced by the explicit value
.
The closure should contain an expression resulting in a boolean, which indicates whether the particular value being processed should survive the filter.
$0.name == name
asks whether each name value in the array is equal to the name variable.
The book’s code doesn’t create an array though. Appended to the filter closure is .first
.
That just means that the first value in the new filtered array will be used, just in case there are more of them.
I hope that helps
1 Like
Thanks Caroline for rescuing me again and sorry for the late answer, I live in Australia.
I do have some questions ,
1)Why do I have to use a filter and not just the User Data name straight away?
- Is $0.name equal to tileGroups.name ?
3)Does .first represent the first tile of my tileGroups.name filtered ?
thanks again Caroline
@nehemie - I’m usually in Australia, but am in England at the moment.
Going from the top:
Obstacles
is the SKTileSet. Each SKTileSet has an array of SKTileGroups.
[wall, wall-cracked, wall-broken]
is the array of SKTileGroups. Each SKTileGroup has an array of SKTileGroupRules.
[Tile]
(under wall-cracked
is the array of SKTileGroupRules. Each SKTileGroupRule has an array of SKTileDefinitions.
[wall-cracked]
(under wall-cracked->Tile
) is the array of SKTileDefinitions. A SKTileDefinition is the class that has the userData
property.
So you need to go down quite a long way from the SKTileGroup to get to the userData
.
tileSet.tileGroups
returns [wall, wall-cracked, wall-broken]
, so you need to filter out wall-cracked
(for example).
tileSet.tileGroups.filter {
$0.name == name
}
returns [wall-cracked]
(when name == “wall-cracked”
).
To get just wall-cracked
, you need to get it out of the array, so first
will get the first occurrence.
thank you very much for the helpful informations, I didn’t understand it was structured like that, I am going to read that chapter again