错误:无法在“自我”中分配给“...”

时间:2015-04-15 21:00:15

标签: swift initialization uikit init

我有这段代码

import UIKit

class SliderControllerView: UIView{
    private let type: ControlType!
    private let label: UILabel!
    private let slider: UISlider!
    private weak var delegate: SliderControllerDelegate?

    private let defaults: SliderDefaults!

    convenience init(type: ControlType, defaults: SliderDefaults, delegate: SliderControllerDelegate?) {

        self.init()

        self.type = type
        self.delegate = delegate
        self.defaults = defaults

        setTranslatesAutoresizingMaskIntoConstraints(false)

        label = UILabel()
        configureLabel()

        slider = UISlider()
        configureSlider(slider)

        SliderDefaults.set(slider, defaults: defaults)

        if let valueFromDetauls = userDefaultsValue {
            slider.value = Float(valueFromDetauls)
        }

        saveValueInUserDefaults()
        updateLabel()
    }

错误讯息:

  1. 无法分配到'键入'在' self'
  2. 无法分配到'默认值'在' self'
  3. 无法指定'标签'在' self'
  4. 无法分配到'滑块'在' self'
  5. 我做什么? 谢谢!

2 个答案:

答案 0 :(得分:3)

我对代码做了一些修改,所以它会编译,虽然它确实改变了一些意思。

class SliderControllerView: UIView {

    // Converted "let" to "var"
    private var type: ControlType!
    private var label: UILabel!
    private var slider: UISlider!
    private weak var delegate: SliderControllerDelegate?

    private var defaults: SliderDefaults!

    // Added frame to init
    convenience init(frame: CGRect, type: ControlType, defaults: SliderDefaults, delegate: SliderControllerDelegate?) {

        // Call designated init(frame: CGRect) for UIView
        self.init(frame: frame)
        self.type = type
        self.delegate = delegate
        self.defaults = defaults

        setTranslatesAutoresizingMaskIntoConstraints(false)

        label = UILabel()
        configureLabel()

        slider = UISlider()
        configureSlider(slider)

        SliderDefaults.set(slider, defaults: defaults)

        if let valueFromDetauls = userDefaultsValue {
            slider.value = Float(valueFromDetauls)
        }

        saveValueInUserDefaults()
        updateLabel()
}

答案 1 :(得分:2)

您无法在swift中设置let属性的值,因此请将它们设置为var属性。