Skip to main content
 首页 » 操作系统

ios之Swift 中的以下 for 循环语法有什么问题

2024年01月01日42telwanggs

为什么即使我已经从 Apple's documentation 中复制了代码,它仍然在 for 循环中显示错误?

这是有问题的地方。


编辑:添加代码
这是我在该类(class)中的全部代码

import UIKit 
import Alamofire 
 
import Foundation 
import SystemConfiguration 
 
class SignUpViewController2: UIViewController 
{ 
    for let index = 0; index < 3; ++index 
    { 
        println("index is \(index)") 
    } 
 
    for let i = 0; i < 3; i++ 
    { 
        print("HI") 
    } 
 
    override func viewDidLoad() 
    { 
        super.viewDidLoad() 
 
        if Reachability.isConnectedToNetwork() 
        { 
            println("YES") 
        } 
    } 
 
    override func didReceiveMemoryWarning() { 
        super.didReceiveMemoryWarning() 
        // Dispose of any resources that can be recreated. 
    } 
} 



这是全类错误的图片

请您参考如下方法:

for var index = 0; index < 3; ++index 
{ 
    println("hi") 
} 

这在 Playground 上对我有用。

由于没有更大的代码片段可用,我只能猜测,但一个可能的问题可能是您正在 swift 文件中尝试此操作。在那种情况下,请确保循环在函数中而不是在类定义之外。我试过了,它给了我同样的错误,但是当在任何函数中移动时错误消失了

编辑:-

我看到您在类定义中添加了代码,而不是在任何特定函数中。请修改代码如下:-

class SignUpViewController2: UIViewController 
{ 
    func forLoops() 
    { 
        for var index = 0; index < 3; ++index 
        { 
            println("index is \(index)") 
        } 
 
        for var i = 0; i < 3; i++ 
        { 
            print("HI") 
        } 
    } 
 
    override func viewDidLoad() 
    { 
        super.viewDidLoad() 
 
        if Reachability.isConnectedToNetwork() 
        { 
            println("YES") 
        } 
        forLoops() 
    } 
 
    override func didReceiveMemoryWarning() { 
        super.didReceiveMemoryWarning() 
        // Dispose of any resources that can be recreated. 
    } 
} 

现在就可以了。您必须将所有循环和可执行语句放在一个函数中。仅在您的类定义中包含属性声明/定义和函数。

希望这对您有所帮助。

EDIT2:- 问题 2 是您使用常量而不是变量编写了 for 循环。请更改

for let index = 0; index < 3; ++index 
{ 
    println("index is \(index)") 
} 

到

for var index = 0; index < 3; ++index 
{ 
    println("index is \(index)") 
} 

您不能更改常量的值,这就是它在增量运算符处出现问题的原因。