簡體   English   中英

iOS Swift:范圍數組

[英]iOS Swift: Array of Range

我有一個Player類,用於存儲Int類型的rating屬性:

class Player {
    typealias Rating: Int
    var rating: Rating = 0
}

然后,我有各種Range實例,用於指定給定player所處的level

private let level1Range = 0 ..< 100
private let level2Range = 100 ..< 500

然后,我可以switch player rating屬性以獲得player所在的級別:

switch rating {
case level1Range:
    print("On Level 1")
case level2Range:
    print("On Level 2")
default:
    break
} 

我希望能夠說出下一關是什么,以及player離下一關有多遠。

我不確定解決此問題的最佳方法。 我首先創建一個數組:

private var ratingRanges: [Range] {
    return [level1Range, level2Range]
}

但是我得到了錯誤:

引用通用類型'Range'時需要在<...>中插入參數'<<#Bound:Comparable#>>'

如果這行得通,我想我可以找到第一個非零值:

ratingRanges.first(where: { $0.min() - self.rating > 0 })

為了找到下一個范圍。

還是有一種更有效的方法來實現這一目標?

謝謝你的幫助

您需要提供Range的通用占位符類型:

private var ratingRanges: [Range<Rating>] {
    return [level1Range, level2Range]
}

或更簡單的是,具有自動類型推斷的(惰性)存儲屬性:

private lazy var ratingRanges = [level1Range, level2Range]

然后可以確定下一個范圍

func nextRange() -> Range<Rating>? {
    return ratingRanges.first(where: { $0.lowerBound > rating})
}

我的解決方案是創建Level枚舉:

    enum Level: Int {
    case level1 = 1
    case level2

    init?(rating: Int) {
        switch rating {
        case Level.level1.range:
            self = .level1
        case Level.level2.range:
            self = .level2
        default:
            return nil
        }
    }

    var range: CountableRange<Int> {
        switch self {
        case .level1:
            return level1Range
        case .level2:
            return level2Range
        }
    }
}

然后,您需要做的就是向Player類添加以下方法:

func nextLevel() -> Level? {
    guard let currentLevel = Level(rating: rating) else {
        return nil
    }
    guard let nextLevel = Level(rawValue: currentLevel.rawValue + 1) else {
        return nil
    }
    return nextLevel
}

func distanceTo(level: Level) -> Int {
    let levelLowerBound = level.range.lowerBound
    return levelLowerBound - rating
}

可能您應該只保留范圍的最大值。 例如,代替

private let level1Range = 0 ..< 100
private let level2Range = 100 ..< 500

您可以使用

private let level1MaxRating = 100
private let level2MaxRating = 500

並與

switch rating {
case 0...level1MaxRating:
    print("level 1")
case (level1MaxRating+1)...level2MaxRating:
    print("level 2")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM