Error using Swift - Instance member cannot be used on type 'ViewController'

前端 未结 2 2015
野趣味
野趣味 2020-12-09 20:08

I\'ve been trying to make an app in Xcode 7 using Swift and I\'m trying to convert numbers inside a textfield to an integer using this code, let a = Int(percentLabel.t

相关标签:
2条回答
  • 2020-12-09 20:43

    You cannot have these two lines outside of a function call in a class

    let myString = percentLabel
    let myInt: Int? = Int(myString)
    

    You cannot intialise a property to a value of another property, you cannot set a variable's default value to that of another property. you would usually do this in a function like viewDidLoad or viewWillAppear. Arsen's answer should also work as it will try to get the value lazily, or as you request it.

    let myString = percentLabel would also not return the text, you'd need to do let myString = percentLabel.text but you cannot assign this value like a property. you'll need to put his code in the body of a function

    0 讨论(0)
  • 2020-12-09 20:45

    This code returns a new value every time you call it. I expect it what you're looking for

    var myInt: Int? {
        return Int(percentLabel.text!)
    }
    

    instead of

    let myString = percentLabel
    let myInt: Int? = Int(myString)
    
    0 讨论(0)
提交回复
热议问题