Swift的OptionSetType协议的目的是什么,它与仅利用Set获得那些SetAlgebraType方法有何不同?

最佳答案

我将在使用OptionSetType时从实用角度回答。对我而言,OptionSetType的目的是删除C / ObjC中的所有位操作。

考虑具有绘制矩形边界的函数的示例。用户可以要求它绘制0到4个边界。

这是Swift中的代码:

struct BorderType: OptionSetType {
    let rawValue: Int
    init (rawValue: Int) { self.rawValue = rawValue }

    static let Top = BorderType(rawValue: 1 << 0)
    static let Right = BorderType(rawValue: 1 << 1)
    static let Bottom = BorderType(rawValue: 1 << 2)
    static let Left = BorderType(rawValue: 1 << 3)
}

func drawBorder(border: BorderType) {
    // Did the user ask for a Left border?
    if border.contains(.Left) { ... }

    // Did the user ask for both Top and Bottom borders?
    if border.contains([.Top, .Bottom]) { ... }

    // Add a Right border even if the user didn't ask for it
    var border1 = border
    border1.insert(.Right)

    // Remove the Bottom border, always
    var border2 = border
    border2.remove(.Bottom)
}

drawBorder([.Top, .Bottom])

在C中:
typedef enum {
    BorderTypeTop    = 1 << 0,
    BorderTypeRight  = 1 << 1,
    BorderTypeBottom = 1 << 2,
    BorderTypeLeft   = 1 << 3
} BorderType;

void drawBorder(BorderType border) {
    // Did the user ask for a Left border?
    if (border & BorderTypeLeft) { ... }

    // Did the user ask for both Top and Bottom borders?
    if ((border & BorderTypeTop) && (border & BorderTypeBottom)) { ... }

    // Add a Right border even if the user didn't ask for it
    border |= BorderTypeRight;

    // Remove the Bottom border, always
    border &= ~BorderTypeBottom;
}

int main (int argc, char const *argv[])
{
    drawBorder(BorderTypeTop | BorderTypeBottom);
    return 0;
}

C短一些,但是乍一看,谁能知道这行的含义?
border &= ~BorderTypeBottom;

尽管这是即时的意义:
var border2 = border
border2.remove(.Bottom)

与C的斯巴达哲学相比,它符合Swift的目标,即成为一种表达性强,易于学习的语言。

关于ios - OptionSetType协议(protocol)Swift,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/38110941/

10-13 08:08