Non-constant range: argument must be an integer literal

更新 Xcode IDE 后 ForEach 方法抛出了如下异常

复制代码
Non-constant range: argument must be an integer literal

新增了指向性 id 参数 init(_:content:)

原始方法

复制代码
ForEach(0 ..< pickerTitleColors.count) {
    Text(self.pickerTitleColors[$0]).tag($0).foregroundColor(self.pickerStyleColors[$0])
}

改进后

复制代码
// 方式一
ForEach(0 ..< pickerTitleColors.count, id:\.self) {
    Text(self.pickerTitleColors[$0]).tag($0).foregroundColor(self.pickerStyleColors[$0])
}

// 方式二
ForEach(0 ..< pickerTitleColors.count, id:\.self) { item in
    Text(self.pickerTitleColors[item]).tag(item).foregroundColor(self.pickerStyleColors[item])
}

// 方式三
ForEach(pickerTitleColors.indices, id:\.self) { item in
    Text(self.pickerTitleColors[item]).tag(item).foregroundColor(self.pickerStyleColors[item])
}

以上便是此次分享的全部内容,希望能对大家有所帮助!

相关推荐
如此风景2 天前
Swift异步详解
swift
HarderCoder2 天前
强制 SwiftUI 重新渲染:`.id()` 这把“重启键”你用对了吗?
swift
HarderCoder2 天前
Swift 6.2 新语法糖:在字符串插值里直接给 Optional 写默认值
swift
HarderCoder2 天前
窥探 `@Observable` 的“小黑盒”:private 属性到底会不会被观察?
swift
zzywxc7872 天前
AI 在金融、医疗、教育、制造业等领域有着广泛的应用,以下是这些领域的一些落地案例
人工智能·python·spring cloud·金融·swift·空间计算
HarderCoder2 天前
Swift 并发避坑指南:自己动手实现“原子”属性与集合
swift
HarderCoder3 天前
惊!只是 `import Foundation`,`String.contains("")` 的返回值居然变了?
swift
HarderCoder3 天前
Swift 6.2 新武器:`weak let` —— 既弱引用又不可变的安全魔法
swift
HarderCoder3 天前
吃透 Swift 的 `@autoclosure`:把“表达式”变“闭包”的延迟利器
swift
HarderCoder3 天前
@Observable 遇上属性包装器:一键绕过‘计算属性’禁令的 Swift 5.9 实战技巧
swift