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])
}

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

相关推荐
YungFan3 小时前
iOS26适配指南之UIButton
ios·swift
麦兜*1 天前
【swift】SwiftUI动画卡顿全解:GeometryReader滥用检测与Canvas绘制替代方案
服务器·ios·swiftui·android studio·objective-c·ai编程·swift
Swift社区2 天前
Swift 实战:从数据流到不重叠区间的高效转换
开发语言·ios·swift
HarderCoder5 天前
Swift 结构体属性:let 与 var 的选择艺术
swift
HarderCoder5 天前
使用 Swift 的 defer 管理状态清理(译文)
swift
HarderCoder5 天前
把 GPT 塞进 iPhone:iOS 26 的 Foundation Models 框架全解析
swift
HarderCoder5 天前
用 SwiftUI 打造“会长大”的组件 —— 从一次性 Alert 到可扩展设计系统
swift
东坡肘子6 天前
苹果首次在中国永久关闭了一家 Apple Store | 肘子的 Swift 周报 #097
swiftui·swift·apple
YungFan6 天前
iOS26适配指南之UIVisualEffectView
ios·swift
大熊猫侯佩9 天前
WWDC 25 玻璃态星际联盟:SwiftUI 视图协同“防御协议”
swiftui·swift·wwdc