首先,我正在使用Xcode 6 beta 2.其次,我确实有编程经验(基本,VB,脚本语言),但它不包括任何严肃的OO编程,我对IOS编程完全不熟悉。直接进入斯威夫特。提前感谢那些可以提供帮助的人。我几天来一直在努力奋斗。
无法构建简单的UIImage数组。 (为了简单起见,我已经删除了所有其他代码。)我试图理解为什么声明一个UIImage数组并加载图像在viewDidLoad()中工作,而不是在" base" ViewController,我似乎需要它来处理其他事情。
(我注意到它似乎与这个数组声明有关,这会引起我的困惑。我可以在任一位置声明并分配简单的UIImage变量。)
这是我的代码:
// ViewController.swift
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
var icon = UIImage[]()
icon.append(UIImage(named: "yes.png")) <<==== expected declaration error
icon.append(UIImage(named: "no.png"))
}
但是这段代码没有:
import UIKit
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var icon = UIImage[]()
icon.append(UIImage(named: "yes.png")) <==== no error, and builds
icon.append(UIImage(named: "no.png"))
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
答案 0 :(得分:10)
您只能在类的方法之外拥有属性声明。该类的所有功能都在方法内部。在方法之外声明var icon = UIImage[]()
时,它是实例属性声明并且是有效代码。
接下来的两行尝试修改属性。方法之外的代码永远不会执行,因为无法调用它。虽然您可以在方法之外声明属性,但您必须在类中的方法中使用它们。
我建议学习更多关于面向对象编程的知识,因为看起来你还没有完全掌握它。你可能想尝试一种比swift目前更具可靠性和学习资源的语言。如果您打算进行iOS开发,即使您想使用Swift,学习objective-c也会有所帮助,因为您将获得两种语言相同的Apple API。