gpt4 book ai didi

ios - OptionSetType 协议(protocol) Swift

转载 作者:搜寻专家 更新时间:2023-11-01 05:53:28 26 4
gpt4 key购买 nike

Swift 的 OptionSetType 协议(protocol)的目的是什么,它与仅仅利用 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com