可选的只读变量的Swift协议默认实现

时间:2017-10-24 05:33:59

标签: ios swift optional swift-protocols swift-extensions

我有以下代码,协议MyDisplayable有三个可选的String,我通过扩展我有一个默认的协议实现。我的问题是,因为我确定扩展返回了三个字符串,有没有办法可以将它们用作非可选项,如果其他实现覆盖它会有任何风险吗? (参见下面代码中的问题1和2)

非常感谢!

protocol MyDisplayable {
    var displayName: String? { get }
    var shortDescription: String? { get }
    var longDescription: String? { get }
}

protocol MyObject : MyDisplayable, CustomStringConvertible {
}

extension MyObject {
    var displayName: String? {
        return "noname"
    }

    var shortDescription: String? {
        return "something can't be described"
    }

    var longDescription: String? {
        return "no way to describe it further"
    }

    var description: String {
        // **1. is there a way to use the strings as if they are non-optional?**
        // **2. is it a problem if another class implements the protocol and returns `nil` for any of the strings, but here they are force unwrapped?**
        return "\(displayName!): \(shortDescription!)\n\(longDescription!)"
    }
}

class Something : MyObject {
}

let something = Something()
print("Something: \(something)")

2 个答案:

答案 0 :(得分:0)

默认实现中的条件展开怎么样?

<script>


    $('#selectAll').click(function(e){
        var table= $(e.target).closest('table');
        $('td input:checkbox',table).prop('checked',this.checked);
    });
    </script>

答案 1 :(得分:0)

不幸的是,将声明的可选项视为非可选项是不可能的。 您已在协议中将这些字符串声明为可选字符串,因此当您实现该协议时,它们仍然是可选的。

但是,您可以使用getter-setter来确保变量始终存储某些值,即使它们被声明为可选值。

我将详细说明一些代码:

protocol MyDisplayable {
    var displayName: String? { get set }
    var shortDescription: String? { get set }
    var longDescription: String? { get set }
}

protocol MyObject : MyDisplayable, CustomStringConvertible {
}

extension MyObject {
    var displayName: String? {
        get {
            return "noname"
        }
        set {
            newValue ?? ""
        }
    }

    var shortDescription: String? {
        get {
            return "something can't be described"
        }
        set {
            newValue ?? ""
        }
    }

    var longDescription: String? {
        get {
            return "no way to describe it further"
        }
        set {
            newValue ?? ""
        }
    }

    var description: String {
        // **1. is there a way to use the strings as if they are non-optional?**
        // **2. is it a problem if another class implements the protocol and returns `nil` for any of the strings, but here they are force unwrapped?**
        return "\(displayName!): \(shortDescription!)\n\(longDescription!)"
    }
}

class Something : MyObject {
}

let something = Something()
print("Something: \(something)")

现在,即使其他一些类覆盖了这些字符串的nil值,它们也会返回空字符串&#34;&#34;。 它们仍然是可选的,因为它们被声明为可选项,但现在它们将始终具有非零值。