从枚举中选择随机值

KkM*_*MIW 1 enums swift

从给定的枚举中选择随机值

public class SwiftConfettiView: UIView {

    public enum ConfettiType {
        case confetti
        case triangle
        case star
        case diamond
        case image(UIImage)
    }
Run Code Online (Sandbox Code Playgroud)

// 在其他类中的用法

    confettiView.type = .confetti
Run Code Online (Sandbox Code Playgroud)

想随机设置五彩纸屑查看三角形、星形、菱形、五彩纸屑

//这行不通

confetti.type =  ConfettiType.allCases.randomElement()!
Run Code Online (Sandbox Code Playgroud)

类型 'SwiftConfettiView.ConfettiType' 没有成员 'allCases'

//所以,所有的五彩纸屑到一个数组列表并从那里加载!

var confettiList = [SwiftConfettiView.ConfettiType.confetti
    , SwiftConfettiView.ConfettiType.diamond
    ,        SwiftConfettiView.ConfettiType.triangle
    ,        SwiftConfettiView.ConfettiType.star
Run Code Online (Sandbox Code Playgroud)

]

    confettiView.type = confettiList.randomElement()!
Run Code Online (Sandbox Code Playgroud)

它工作正常!

这种方法是对还是错?

iMu*_*hid 5

这里你的枚举是关联类型。因此,如果类型为图像,则必须提供图像作为参数。我已经考虑了默认图像。

extension ConfettiType: CaseIterable {
    static var allCases: [ConfettiType] {
        let img: UIImage = UIImage(named: "default_image")! // change as your expectation
        return [.confetti, .triangle, .star, .diamond, .image(img)]
    }    
}
let randomEnum = ConfettiType.allCases.randomElement()
Run Code Online (Sandbox Code Playgroud)

否则,如果您的图像类型是这样的,image(UIImage?)那么我们可以将其nil设为默认值。在这种情况下,它会更方便。