最新消息:20210816 当前crifan.com域名已被污染,为防止失联,请关注(页面右下角的)公众号

[已解决]swift出错:Value of type Int has no member Generator

Swift crifan 3942浏览 0评论

代码:

imageArr:[UIImage]

    for index in imageArr.count {
出错:
Value of type ‘Int’ has no member ‘Generator’
想要实现:
for循环中,使用int数组,然后循环获得对应的index值
[解决过程]

1.搜:

swift Value of type Int has no member Generator
swift for  index error Value of type Int has no member Generator
 参考:
搜:
swift for  index from int
swift for in  range
参考:
后来改为:
    print("imageArr.count=\(imageArr.count)")
    for index in 0...imageArr.count-1 {
        print("index=\(index)")
    }
即可。
输出:
imageArr.count=4
index=0
index=1
index=2
index=3
[总结]
上述语法错误:
Value of type Int has no member Generator
的含义是:
即,对于此处for循环中的,in后面的值,是需要是一个列表类型的值
-》而列表类型的值,才有Generator,生成器,才能每次生成一个值
-》这样,才能实现for循环的,每一次取其中一个值的
-》而此处的imageArr.count,是个Int值
-》Int值,不是列表类型的值,是没有生成器,是没法生成每次供for循环取出一个值的
-》所以此处改为:0…imageArr.count-1,就是个列表类型的值,对应的0到imageArr.count-1的Int数组,是有Generator,是可以每次生成一个值供for循环使用的
[后记]
对于:
for index in 0...imageArr.count-1
 更好的写法是:
for index in 0..<imageArr.count

这样意思更加明确:是0到count-1的数组

并且:当imageArr.count为0时,上述代码不会崩溃

(注:0…imageArr.count-1会崩溃)

转载请注明:在路上 » [已解决]swift出错:Value of type Int has no member Generator

发表我的评论
取消评论

表情

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址
84 queries in 0.164 seconds, using 22.01MB memory