@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);
@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

本文转载自 Erica Sadun 的博客

In the dark fetid implementation mists behind the slick city Swift streets lies a secret world where enumerations are merely ints with pretensions. In more objective terms, Swift enums provide a complete and finite ordered listing of the possible members in a fixed collection. They basically come in three flavors.

Basic EnumerationsFirst, there’s a common variety of “related things” that form a family.

enum Coin {case Heads, Tails}

These basic enumerations provide a fixed vocabulary about possible states you may encounter (if rollValue == .Heads or if collection.contains(.Tails)). Collections with enumerations can contain repetitions. For example, [.Tails, .Tails, .Heads] represents a series of enumeration states, perhaps detailing the history of coin tosses.

Avoid basic enumerations for bit flags as there’s a specific RawOptionSet solution for flags.

Fixed Values. A second flavor of enums offer an associated a raw value. The following example uses natural ordering, starting with 1. Tails’ rawValue is 2.

enum Coin: Int {case Heads = 1, Tails}

These values can be continuous, as in this example, or discrete {case Heads = 5, Tails = 23} but the type, which is declared after the enumeration name, is always homogenous.

You can use other types, such as Strings, but there’s always a one-to-one correspondence between the enumeration and its value. So a .King enumeration may always equate to 12 or “King”. Think of these as a look-up table.

Associated PayloadsAnd there’s the kind that packs payloads. The most commonly used implementation of these is optionals (case .None, case .Some(T)) but you can build your own as well. Cases can use any types, and those types may include tuples.

enum Coin {case Heads(NSDate, Bool, String); case Tails}

The Dark Underbelly of the Enum

To better understand enumerations, it helps to poke at them with a sharp stick. For obvious reasons, don’t use the following material for production code. Or really for any code. That said, I found this exercise extremely valuable for understanding how enums work.

Enums are typically one byte long.

sizeof(Coin); // 1

If you want to get very very silly, you can build an enumeration with hundreds of cases, in which case the enum takes up 2 or more bytes depending on the minimum bit count needed. If you’re building enumerations with more than 256 cases, you probably should reconsider why you’re using enumerations.

Basic enumerations (the first two cases) are Hashable, that is, they provide an integer hashValue that is unique to each value. Unsurprisingly, the hash values for enumerations start at zero and increase monotonically. (Yes, this is an implementation detail. Alarm bell. Warning blare.)

enum Planets {case Mercury, Venus, Earth, Mars, Jupiter, Saturn, Neptune, Uranus, Pluto} 
print(Planets.Mars.hashValue) // 3
print(Planets.Mercury.hashValue) // 0

Enumerations with basic associated values are also raw representable. The rawValue follows from whatever default or explicit assignment you’ve made. All raw values are of the same type, in this case Int:

enum Foo : Int {case i = 1, j = 5, k = 9}
Foo.j.hashValue // 1
Foo.j.rawValue // 5

Moving Forward

So given these details of how enumerations work:

  • How do you create instances from rawValues?
  • How do you create instances from hashValues?
  • How do you query an enumeration about its members?

I warn you in the strongest possible terms against continuing to read. Tom does not approve.

Creating instances from Raw Values

Okay, I lied. This one, he does approve of. That’s because it’s legal.

enum Foo : Int {case i = 1, j = 5, k = 9}
Foo(rawValue: 5) // .j

You create instances using the built-in constructor, supplying the raw value.

Enhancing Enums

Now we wander into the shadow of the valley of doom, so you should start to fear some evil. Swift is no longer with you, and unsafe bitcasts lie ahead. The goal is to create this protocol, with default implementations that supplies the following features to all enumerations of the first two types.

public protocol EnumConvertible: Hashable {
    init?(hashValue hash: Int)
    static func countMembers() -> Int
    static func members() -> [Self]
}

Building Enums from Hash Values

Since it’s a given that an enumeration is basically an Int8 that stores the hash value, you can build a really simple initializer. Just cast the Int8 that’s initialized with a hash value to the enumeration type.

let member = unsafeBitCast(UInt8(index), Self.self)

This line doesn’t check for safe values, so you probably want to use some sort of check that the value is within the membership limit, and create a failable initializer instead.

internal static func fromHash(
    hashValue index: Int) -> Self {
    let member = unsafeBitCast(UInt8(index), Self.self)
    return member
}
public init?(hashValue hash: Int) {
    if hash >= Self.countMembers() {return nil}
    self = Self.fromHash(hashValue: hash)
}

Once added to the protocol, you can construct an instance from its hash value (countable, starting with 0) and look up its raw value:

Foo(hashValue: 1)!.rawValue // 5

Boom done. And Tom turns away, disapproval writ large upon his face.

Counting Members

The hash-value-based init depends on there being some way to count enumeration members. If you know you’ll always deal with one-byte enumerations, this is super easy. Adding support for two bytes isn’t much harder.

static public func countMembers() -> Int {
    let byteCount = sizeof(self)
    if byteCount == 0 {return 1}
    if byteCount byteCount > 2 {
    fatalError("Unable to process enumeration")}
    let singleByte = byteCount == 1
    let minValue = singleByte ? 2 : 257
    let maxValue = singleByte ? 2 << 8 : 2 << 16
    for hashIndex in minValue..<maxValue {
    switch singleByte {
    case true:
    if unsafeBitCast(UInt8(hashIndex), self).hashValue == 0 {
    return hashIndex
    }
    case false:
    if unsafeBitCast(UInt16(hashIndex), self).hashValue == 0 {
    return hashIndex
    }
    }
    }
    return maxValue
}

This approach uses a simple iteration to construct values until a hashValue look-up fails. It’s pretty brain dead although it knows that 2-byte enums cannot contain fewer than 256 values.

Unfortunately, protocol implementation doesn’t allow you to create storage so you end up re-computing this value all the time (or would if you used this, which you won’t because Tom would not approve).

Enumerating Enumerations

The final goal lies in creating a collection that allows you to enumerate through your enumerations to cover all available cases. For that, you need to return all members.

static public func members() -> [Self] {
    var enumerationMembers = [Self]()
    let singleByte = sizeof(self) == 1
    for index in 0..<Self.countMembers() {
    switch singleByte {
    case true:
    let member = unsafeBitCast(UInt8(index), self)
    enumerationMembers.append(member)
    case false:
    let member = unsafeBitCast(UInt16(index), self)
    enumerationMembers.append(member)
    }
    }
    return enumerationMembers
}

As with the membership count, this is something that would benefit either from being built-in (well, of course), or from implementation that prevents it being computed more than once.

Once you add this, you can perform tasks like “show me a function as it relates to each member of an enumeration”. Although actual sequencing is an illusion — enumeration members may not be built upon any intrinsic sequence semantics — it can be super handy to be able to access items in this way.

Wrap-Up

You can see an example of why this function would be particularly helpful in this gist, which I wrote in response to a post on devforums. Someone was looking for a probability-weighted enum and it was their post that led me to start exploring this whole question.

I gisted my answer here. It is based on a far less elegant solution for collecting members but it showcases why the use-case is valid and compelling.

The entire protocol discussed in this post is at this gist and awaits your feedback, insight, and suggestions. Please tweet or leave comments here because Github doesn’t notify by email.

Finally. Sorry, Tom.

@import url(http://i.cnblogs.com/Load.ashx?type=style&file=SyntaxHighlighter.css);@import url(/css/cuteeditor.css);

iOS - Swift Enumerations or how to annoy Tom的更多相关文章

  1. iOS swift的xcworkspace多项目管理(架构思想)

    iOS  swift的xcworkspace多项目管理(架构思想) 技术说明: 今天在这里分享 swift下的 xcworkspace多项目管理(架构思想),能为我们在开发中带来哪些便捷?能为我们对整 ...

  2. iOS Swift 模块练习/swift基础学习

    SWIFT项目练习     SWIFT项目练习2 iOS Swift基础知识代码 推荐:Swift学习使用知识代码软件 0.swift中的宏定义(使用方法代替宏) 一.视图  +控件 1.UIImag ...

  3. ios swift 实现饼状图进度条,swift环形进度条

    ios swift 实现饼状图进度条 // // ProgressControl.swift // L02MyProgressControl // // Created by plter on 7/2 ...

  4. Building gRPC Client iOS Swift Note Taking App

    gRPC is an universal remote procedure call framework developed by Google that has been gaining inter ...

  5. iOS Swift WisdomScanKit图片浏览器功能SDK

    iOS Swift WisdomScanKit图片浏览器功能SDK使用 一:简介      WisdomScanKit 由 Swift4.2版编写,完全兼容OC项目调用. WisdomScanKit的 ...

  6. iOS Swift WisdomScanKit二维码扫码SDK,自定义全屏拍照SDK,系统相册图片浏览,编辑SDK

    iOS Swift WisdomScanKit 是一款强大的集二维码扫码,自定义全屏拍照,系统相册图片编辑多选和系统相册图片浏览功能于一身的 Framework SDK [1]前言:    今天给大家 ...

  7. iOS Swift WisdomHUD 提示界面框架

    iOS Swift WisdomHUD 提示界面框架  Framework Use profile(应用简介) 一:WisdomHUD简介 今天给大家介绍一款iOS的界面显示器:WisdomHUD,W ...

  8. iOS Swift WisdomKeyboardKing 键盘智能管家SDK

    iOS Swift WisdomKeyboardKing 键盘智能管家SDK [1]前言:    今天给大家推荐个好用的开源框架:WisdomKeyboardKing,方面iOS日常开发,优点和功能请 ...

  9. iOS swift项目IM实现,从长连接到数据流解析分析之Socket

    iOS  swift项目IM实现,从长连接到底层数据解析分析之Socket 一:项目简介:  去年开始接手了一个国企移动项目,项目的需求是实现IM即时通讯功能. * 一期版本功能包括了:       ...

随机推荐

  1. 输入url到渲染出页面的过程

    输入地址 浏览器查找域名的 IP 地址 这一步包括 DNS 具体的查找过程,包括:浏览器缓存->系统缓存->路由器缓存... 浏览器向 web 服务器发送一个 HTTP 请求 服务器的永久 ...

  2. ES6 学习笔记之二 块作用域与闭包

    "闭包是函数和声明该函数的词法环境的组合." 这是MDN上对闭包的定义. <JavaScript高级程序设计>中则是这样定义的:闭包是指有权访问另一个函数作用域中的变量 ...

  3. Node.js爬取豆瓣数据

    一直自以为自己vue还可以,一直自以为webpack还可以,今天在慕课逛node的时候,才发现,自己还差的很远.众所周知,vue-cli基于webpack,而webpack基于node,对node不了 ...

  4. docker设置固定ip地址

    Docker安装后,默认会创建下面三种网络类型 $ docker network ls NETWORK ID NAME DRIVER SCOPE 9781b1f585ae bridge bridge ...

  5. centos6下从源码安装setuptools和pip

    1. 下载setuptools及pip的源码包 setuptools与pip都是python的模块 setuptools源码包: https://pypi.python.org/pypi/setupt ...

  6. 谷歌内核浏览器 iframe内容的 tab切换 滚动条消失

    问题: 新版本的-webkit- 内核浏览器 在tab切换时,iframe 内容区 丢失滚动条 如下图 (虽然滚动条位置还在,可以垂直滚动,但滚动条不见了) 解决思路: 让iframe重新计算宽高,重 ...

  7. maven排除jar包冲突

    首先查看mvn中冲突的包 使用命令:mvn dependency:tree -Dverbose | grep "omitted for conflict with" windows ...

  8. Visual Studio 2017 Enterprise 发布 15.3.3 版,附离线安装包百度网盘下载。

    Visual Studio 2017 Enterprise 发布 15.3.3 版,附离线安装包百度网盘下载. Visual Studio 2017 Enterprise 更新至 15.3.3 ,本安 ...

  9. POJ - 1426 暴力枚举+同余模定理 [kuangbin带你飞]专题一

    完全想不到啊,同余模定理没学过啊,想起上学期期末考试我问好多同学'≡'这个符号什么意思,都说不知道,你们不是上了离散可的吗?不过看了别人的解法我现在会了,同余模定理介绍及运用点这里点击打开链接 简单说 ...

  10. 浅谈JavaScript位操作符

    因为ECMAscript中所有数值都是以IEEE-75464格式存储,所以才会诞生了位操作符的概念. 位操作符作用于最基本的层次上,因为数值按位存储,所以位操作符的作用也就是操作数值的位.不过位操作符 ...