1

I need to create an array whose objects are of type Range. But creating an array like below produces an error "Reference to generic type 'Range' requires arguments in <...>"

var ranges:Array<Range> = []

Basically, what I'm trying to accomplish is to create a list of ranges that will serve as a step function to generate a random type. I've done this without using array, but as I add more types I feel the need to just loop them over an array. My problem is that ranges somehow cannot be stored in an Array in Swift. Here's my old code that worked.

        let twisterUpperRange = UInt32(roundf(twisterRate * 1_000))
        let bombUpperRange = UInt32(roundf(bombRate * 1_000)) + twisterUpperRange
        let blindUpperRange = UInt32(roundf(blindRate * 1_000)) + bombUpperRange

        let randomNumber = arc4random_uniform(1_000) + 1

        var powerupType:PowerupType
        switch randomNumber {
        case 0...twisterUpperRange:
            powerupType = PowerupType.TwisterType
        case twisterUpperRange...bombUpperRange:
            powerupType = PowerupType.BombType
        case bombUpperRange...blindUpperRange:
            powerupType = PowerupType.BlindType
        default:
            powerupType = PowerupType.NormalType
        }

        return powerupType
1
  • 1
    Are your ranges all going to be the same type (i.e. UInt32)? If so, you can just do: var ranges: Array<Range<UInt32>>. Commented Sep 25, 2014 at 2:51

1 Answer 1

3

The error means that Swift Range is generic a generic type on the type of the interval ends:

var ranges : Array<Range<UInt32>> = []
let blindRate = 0.3
let twisterRate = 0.5
let bombRate = 0.2
let twisterUpperRange = UInt32(twisterRate * 1_000)
let bombUpperRange = UInt32(bombRate * 1_000) + twisterUpperRange
let blindUpperRange = UInt32(blindRate * 1_000) + bombUpperRange
ranges.append(0...twisterUpperRange)
ranges.append(twisterUpperRange...bombUpperRange)
ranges.append(bombUpperRange...blindUpperRange)
print(ranges)

Demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.