Skip to content

Make it easier to iterate through DiceKit types #94

@Samasaur1

Description

@Samasaur1

One example of this problem is here. Take a look at the doc comment for the chances property of a Chances object.

/// The rolls and the chances of them occurring.
///
/// This is the property one should use in order to iterate through the possibilities, like so:
///
/// ```
/// let chances: Chances = getChancesFromSomewhereElse()
/// let arr = chances.chances.sorted(by: { first, second in
/// first.key < second.key
/// })
/// for (roll, chance) in arr {
/// print("The chance of rolling a \(roll) is \(chance.n) out of \(chance.d)")
/// }
/// ```
///
/// - Since: 0.21.0
public private(set) var chances: [Roll: Chance]

It wants you to use chances.chances, and then possibly sorted(by:) on top of that, if you want to iterate through it. However, Swift has support for adding iteration to custom types, using IteratorProtocol. While I'm not sure how far we should take this idea (mapping? conformance to Collection? other DiceKit type?), these two ideas seems like a good start:

import DiceKit

let dice: Dice = getDiceStruct()
for die in dice {
    print(die)
}
for (die, count) in dice {
    print("Die \(die) is repeated \(count) time(s)")
}

let chances: Chances = getChances()
for (roll, chance) in chances {
    print("The probability of rolling a \(roll) is \(chance)")
}

I'm not as sure about iterating through Dice, in part because I do see two ways to do that, as I listed above. Given 2d6 + d4, the first one would loop three times (d6, d6, d4), and the second would loop twice ((d6, 2), (d4, 1)). More consideration is required on that front. However, the idea overall seems sound.

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions