Swift 3中var的默认值

时间:2017-03-28 14:51:09

标签: swift string struct

在我的结构中,我将vars声明为:

public var name:String?
public var X:String?
public var Y:String?

现在我的问题是,如果有人访问.name的struct,如果没有设置我需要返回X + Y,前提是X& Y被设置,否则我需要返回“虚拟”。我如何实现这一目标?

2 个答案:

答案 0 :(得分:2)

应该有效

struct Struct {
    private var _name: String?
    var name: String? {
        get {
            if let name = _name {
                return name
            } else if let x = X, let y = Y {
                return x + y
            } else {
                return "dummy"
            }
        }

        set(newValue){
            _name = newValue
        }
    }

    var X: String?
    var Y: String?
}

答案 1 :(得分:0)

考虑使用这样的计算属性:

struct S
{
    private var _name:String?
    public var X:String?
    public var Y:String?

    public var name:String
    {
        if let name:String = self._name
        {
            return name
        }
        else if let x:String = self.X, let y:String = self.Y
        {
            return x + y
        }
        else
        {
            return "dummy"
        }
    }
}

要设置name,请添加Swift property setter

    public var name:String
    {
        get
        {
            ...
        }
        set(new_value)
        {
            self._name = new_value
        }
    }

但是,这不允许您将名称设置回nil。为此,您需要在结构中定义专用的setter方法。