Swift 2预期声明错误&实例成员不能在视图控制器上使用

时间:2015-12-06 20:43:17

标签: ios swift2

以下是代码的屏幕截图:

Image

图像显示更清晰的视图,因此您最好看到它

import UIKit

class ViewController: UIViewController {
// Inputs
    @IBOutlet weak var billField: UITextField!
//Outputs
    @IBOutlet weak var tipPercentageLabel: UILabel!
    @IBOutlet weak var personsLabel: UILabel!
    @IBOutlet weak var tipTotalLabel: UILabel!
    @IBOutlet weak var tipPerPerson: UILabel!
    @IBOutlet weak var GrandTotalLabel: UILabel!
    @IBOutlet weak var totalPerPerson: UILabel!
//Slider
    @IBOutlet weak var tipSlider: UISlider!
    @IBOutlet weak var personsStepper: UIStepper!
// Variables\
    var amountDouble = Double(50)
    var sliderValue = 18
    var tipPerc = 0.18
    var tip = Double(10)
    var myTip = Double(10)
    var persons = Int(1)



    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        GrandTotalLabel.text = "Grand Total"
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    @IBAction func tipSliderChanged(sender: UISlider) {
        print("tip adjusted")

        sliderValue = Int(sender.value)
        tipPerc = Double(sliderValue) * 0.01
        tipPercentageLabel.text = "\(sliderValue)%"

    }
    @IBAction func personsStepper(sender: UIStepper) {
        print("persons adjusted")

        persons = Int(sender.value)
        personsLabel.text = "\(persons)"
    }





    let pctFormatter = NSNumberFormatter()
    pctFormatter.numberStyle = NSNumberFormatterStyle.CurrencyStyle

上面的线上出现的第一个错误" pctFormatter",错误是"预期宣言"

    amountDouble = (billField.text as NSString).doubleValue

    tip = amountDouble * tipPerc

    tipPercentageLabel.text = "(Int(sliderValue))%"
    tipTotalLabel.text = pctFormatter.stringFromNumber(tip)
    var result = Double(amountDouble)+Double(tip) 

第二个错误在上面的行中,错误在于说明"实例成员数量' amountDouble'不能在类型'查看控制器'

上使用
    GrandTotalLabel.text = pctFormatter.stringFromNumber(tip/personsDouble) 

并且最后一个在上面的线上并且说预期的声明

    myTip = Double(tip/personsDouble)
    totalPerPerson.text = pctFormatter.stringFromNumber(result / personsDouble)

}

1 个答案:

答案 0 :(得分:2)

问题是你有一行不在方法中的代码。该代码只是位于class定义中,并且编译器不知道在func实现之外应该做什么。

顺便说一下,如果你的意图是定义一个用代码初始化的属性,你可以这样做:

let pctFormatter: NSNumberFormatter = {
    let _formatter = NSNumberFormatter()
    _formatter.numberStyle = .CurrencyStyle
    return _formatter
}()

但是pctFormatter下面的其他代码行显然是要放在一个方法中,所以那些具有func实现的代码。