Xcode 8.2.1环境下Swift无法用Int.random随机化数组元素求替代方案
Hey Alex, I totally get your frustration—dealing with version gaps and missing methods can be a real headache. Let's fix this step by step:
First, the reason Int.random(in:) isn't working for you is that this method was introduced in Swift 4.2, but Xcode 8.2.1 uses Swift 3.0. That method just doesn't exist in your version yet. No worries though, there are two simple, reliable alternatives that work perfectly with your setup.
Option 1: Use arc4random_uniform (No Extra Frameworks Needed)
This is a classic, battle-tested random function that's easy to adapt for Swift 3:
- First, define your array of dice images clearly (this keeps your code clean):
let diceImages = [photo1, photo2, photo3, photo4, photo5, photo6] - Generate a safe random index (no out-of-bounds crashes guaranteed):
// Convert array count to UInt32 (required by arc4random_uniform) let randomIndex = Int(arc4random_uniform(UInt32(diceImages.count))) // Assign the random image to your image view diceImageView.image = diceImages[randomIndex]arc4random_uniform(n)returns a random number between 0 andn-1, so using your array's count ensures we only get valid indices for your dice images.
Option 2: Use GameplayKit (Cleaner, No Type Conversion)
Apple's GameplayKit framework has Swift-friendly randomization tools that skip the type conversion hassle. Here's how to use it:
- First, import the framework at the top of your file:
import GameplayKit - Generate your random index and assign the image:
This method directly returns anlet diceImages = [photo1, photo2, photo3, photo4, photo5, photo6] let randomIndex = GKRandomSource.sharedRandom().nextInt(upperBound: diceImages.count) diceImageView.image = diceImages[randomIndex]Intthat's guaranteed to be between 0 anddiceImages.count - 1, so no messy conversions required.
Why Your Shuffle Attempt Might Have Failed
If you tried using shuffle earlier, you might have hit snags because Swift 3 handles shuffling differently:
shuffle()modifies the array in place (so your array needs to be mutable, declared withvarinstead oflet)shuffled()returns a brand new shuffled array
Here's how it would work if you prefer this approach:
var mutableDiceImages = [photo1, photo2, photo3, photo4, photo5, photo6] mutableDiceImages.shuffle() // Shuffles the array in place diceImageView.image = mutableDiceImages.first // Grab the first element of the shuffled array
That said, for just picking a single random element, the index-based methods above are more efficient.
Hope these solutions work smoothly for your dice app!
内容的提问来源于stack exchange,提问作者Alex

