where indirect和嵌套enum

2016-01-23  本文已影响56人  ShawnDu

where和模式匹配

case中用where:

let name = ["李一", "张三", "李二", "王四"]
name.forEach {
    switch $0 {
    case let x where x.hasPrefix("李"):
        print("\(x)是李家的人")
        
    default:
        print("hello:\($0)")
    }
}

输出:

李一是李家的人
hello:张三
李二是李家的人
hello:王四

也可以用if let:

if let score = $0 where score > 60 {}
for score in numArray where score > 60{}
extension SequenceType where Self.Generator.Element: Comparable {
 public fund sort() -> [self.Generator.Element]
}

indirect和嵌套enum

indirect enum LinkedList<Element: Comparable> {
    case Empty
    case Node(Element, LinkedList<Element>)
}
let linkedList = LinkedList.Node(1, .Node(2, .Node(3, .Node(4, .Empty))))
//1->2->3->4

对于像struct enum值类型,加上indirect编译器会加入中间层,可以递归。实现链表中删除节点只需要在enum中加入:

    func linkedListByRemovingElement(element: Element) -> LinkedList<Element> {
        guard case let .Node(value, next) = self else {
            return .Empty
        }
        return value == element ? next : LinkedList.Node(value, next.linkedListByRemovingElement(element))
    }
//测试结果
“let result = linkedList.linkedListByRemovingElement(2)
print(result)
// 1 -> 3 -> 4”
上一篇下一篇

猜你喜欢

热点阅读