gpt4 book ai didi

arrays - 使用常量初始化 swift 数组

转载 作者:行者123 更新时间:2023-11-28 13:20:40 25 4
gpt4 key购买 nike

我有一个二维数组,我试图用它来将一组值从选择器映射到一组特定的值。我想让它可读,所以我尝试使用 C 风格并将我的一组值定义为常量,然后在初始化中使用它们,但是我收到一个错误,告诉我我的类没有名为常量的成员.我在 Playground 上测试了它,一切正常,因为 Playground 是解释性的。任何人都知道如何最好地解决这个问题。我知道如何从技术角度解决问题,但对保持可读性很着迷。下面是代码吸管

// definitions for FORCE objects

let LIVELY = 0
let LIGHT = 1
let ROUNDED = 2
let POWERFUL = 3
let CHAMPAGNE = 4
let SUCREBLANC = 5
let SUCREROUGEOUBLANC = 6
let SUCREROUGE = 7
let CHAMPAGNEROSE = 8
let ROSE = 9

//definitions for SAVEUR objects

let FLORAL = 0
let FRUITY = 1
let OAKY = 2
let SPICY = 3

let redForceNamePointerArray = [
/* 1 2 3 4 5 6 7 8 9 10 11 12 */
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL],
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL],
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL],
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL],
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL],
/* 1 */ [LIGHT,ROUNDED,POWERFUL,NOIMAGE,LIGHT,CHAMPAGNE,SUCREROUGEOUBLANC,CHAMPAGNE,ROUNDED,ROUNDED,SUCREBLANC,POWERFUL]];

l

最佳答案

常量初始值设定项不能引用类中的其他常量。这是语言或编译器的限制。这是一个替代方案:

class C {
enum Image: Int {
case NOIMAGE = -1
case LIVELY
case LIGHT
case ROUNDED
case POWERFUL
case CHAMPAGNE
case SUCREBLANC
case SUCREROUGEOUBLANC
case SUCREROUGE
case CHAMPAGNEROSE
case ROSE
}

enum Flavor: Int {
case FLORAL = 0
case FRUITY
case OAKY
case SPICY
}

let redForceNamePointerArray: [[Image]] = {
typealias I = Image
return [
/* 1 2 3 4 5 6 7 8 9 10 11 12 */
/* 1 */ [I.LIGHT,I.ROUNDED,I.POWERFUL,I.NOIMAGE,I.LIGHT,I.CHAMPAGNE,I.SUCREROUGEOUBLANC,I.CHAMPAGNE,I.ROUNDED,I.ROUNDED,I.SUCREBLANC,I.POWERFUL],
/* 1 */ [I.LIGHT,I.ROUNDED,I.POWERFUL,I.NOIMAGE,I.LIGHT,I.CHAMPAGNE,I.SUCREROUGEOUBLANC,I.CHAMPAGNE,I.ROUNDED,I.ROUNDED,I.SUCREBLANC,I.POWERFUL]
]
}()
}

但是现在 redForceNamePointerArray 的元素是 C.Image 而不是 Int。如果您真的希望它们是 Int:

    let redForceNamesInt: [[Int]] = {
typealias I = Image
return [
/* 1 2 3 4 5 6 7 8 9 10 11 12 */
/* 1 */ [I.LIGHT,I.ROUNDED,I.POWERFUL,I.NOIMAGE,I.LIGHT,I.CHAMPAGNE,I.SUCREROUGEOUBLANC,I.CHAMPAGNE,I.ROUNDED,I.ROUNDED,I.SUCREBLANC,I.POWERFUL],
/* 1 */ [I.LIGHT,I.ROUNDED,I.POWERFUL,I.NOIMAGE,I.LIGHT,I.CHAMPAGNE,I.SUCREROUGEOUBLANC,I.CHAMPAGNE,I.ROUNDED,I.ROUNDED,I.SUCREBLANC,I.POWERFUL]
].map { $0.map { $0.rawValue } }
}()

关于arrays - 使用常量初始化 swift 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26225332/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com