相关疑难解决方法(0)

在Swift 3.0中通过Enum迭代

我有一个简单的枚举,我想迭代.为此,我采用了Sequence和IteratorProtocol,如下面的代码所示.顺便说一句,这可以复制/粘贴到Xcode 8中的Playground.

import UIKit

enum Sections: Int {
  case Section0 = 0
  case Section1
  case Section2
}

extension Sections : Sequence {
  func makeIterator() -> SectionsGenerator {
    return SectionsGenerator()
  }

  struct SectionsGenerator: IteratorProtocol {
    var currentSection = 0

    mutating func next() -> Sections? {
      guard let item = Sections(rawValue:currentSection) else {
        return nil
      }
      currentSection += 1
      return item
    }
  }
}

for section in Sections {
  print(section)
}
Run Code Online (Sandbox Code Playgroud)

但是for-in循环生成错误消息"Type'Sections.Type'不符合协议'Sequence'".协议一致性在我的扩展中; 那么,这段代码有什么问题?

我知道还有其他方法可以做到这一点,但我想了解这种方法有什么问题.

谢谢.

enums enumeration sequence swift

5
推荐指数
3
解决办法
1万
查看次数

在swift中从struct调用方法

我在这里找到了迭代枚举的优雅解决方案:如何使用String类型枚举枚举?

接下来,我无法弄清楚如何调用此方法.在面值,它看起来不像是一个参数,但当我尝试调用Card.createDeck()时,我得到一个编译器错误告诉我"错误:在调用中缺少参数#1的参数".

请让我知道我在这里做错了什么?我应该传递给这种方法的是什么?

struct Card {
    var rank: Rank
    var suit: Suit

    func simpleDescription() -> String {
        return "The \(rank.simpleDescription()) of \(suit.simpleDescription())"
    }

    func createDeck() -> [Card] {

        var deck = [Card]()

        var n = 1
        while let rank = Rank.fromRaw(n) {

            var m = 1
            while let suit = Suit.fromRaw(m) {
                deck += Card(rank: rank, suit: suit)
                m++
            }
            n++
        }

        return deck
    }

}
Run Code Online (Sandbox Code Playgroud)

methods enums struct swift

4
推荐指数
1
解决办法
4504
查看次数

Enum上的内省和迭代

是否有可能以编程方式找出Enum在Swift 2中有多少"案例"并迭代它们?

这段代码不能编译,但它让你知道我想要实现的目标:

enum HeaderStyles{

    case h1
    case h2
    case h3
}

for item in HeaderStyles{
    print(item)
}
Run Code Online (Sandbox Code Playgroud)

enums introspection swift swift2

4
推荐指数
1
解决办法
1116
查看次数

带参数的 Swift 枚举:如何比较它们?

我有以下枚举:

enum Message: ErrorType {
    case MessageWithInfo(info:String?)
    case MessageDidFail
    case MessageDidSend(info:String)
    case InvalidMessageData
    case MessageWithDelay(delay:Double)
    .... will keep adding more
}
Run Code Online (Sandbox Code Playgroud)

我想弄清楚如何编写 Equatable 函数,然后让我比较 Message 枚举。

我发现了一些关于堆栈溢出的类似问题,但我找不到一个可以让我进行比较而不必打开每个案例的问题。

有没有办法编写一次 equatable 函数并让它工作,即使我不断向这个枚举添加更多案例?

enums swift equatable

3
推荐指数
1
解决办法
1232
查看次数

如何快速从枚举成员原始值创建数组字符串

我是编程新手,而且很快。我有一个这样的枚举

enum City : String {
    case tokyo = "tokyo"
    case london = "london"
    case newYork = "new york"
}
Run Code Online (Sandbox Code Playgroud)

我可以从枚举原始值将该城市名称获取到数组中吗?我希望我能得到这样的东西:

let city = ["tokyo","london","new york"]
Run Code Online (Sandbox Code Playgroud)

ios swift

2
推荐指数
1
解决办法
3581
查看次数