Swift中的Optional以及函数

2016-06-02  本文已影响196人  婉卿容若

5.31

计划

唐巧烧脑体操1-2

总结

体操一 总结: Optional

public enum Optional<Wrapped> : _Reflectable, NilLiteralConvertible {
    case None
    case Some(Wrapped)
    
    @available(*, unavailable, renamed="Wrapped")
    public typealias T = Wrapped
    
    /// Construct a `nil` instance.
    @_transparent
    public init() { self = .None }
    
    /// Construct a non-`nil` instance that stores `some`.
    @_transparent
    public init(_ some: Wrapped) { self = .Some(some) }
    
}

源码地址

 public subscript(key: Key) -> Value? {
    get {
      return _variantStorage.maybeGet(key)
    }
    set(newValue) {
      if let x = newValue {
        // FIXME(performance): this loads and discards the old value.
        _variantStorage.updateValue(x, forKey: key)
      }
      else {
        // FIXME(performance): this loads and discards the old value.
        removeValueForKey(key)
      }
    }
  }

源码地址

体操二 总结: 函数

函数编程:
数据与函数是低耦合的
函数隐藏了它们的实现,语言的抽象是函数,以及将函数组合起来表达。
核心抽象模型是函数,不是数据结构
核心活动是编写新的函数。
变量缺省是不变的,减少可变性变量的使用,并发性好


函数是"第一等公民"
所谓"第一等公民"(first class),指的是函数与其他数据类型一样,处于平等地位,可以赋值给其他变量,也可以作为参数,传入另一个函数,或者作为别的函数的返回值。

延伸学习

一个可以抛出的方法实际上做的事情是执行一个闭包,接着选择返回一个值或者是抛出一个异常

 let fileManager = NSFileManager.defaultManager()
 let url: NSURL = NSURL(fileReferenceLiteral: "http://www.ibm.com/developerworks/cn/mobile/mo-cn-swift/index.html")
 do{
        try fileManager.copyItemAtURL(url, toURL: url)
 }catch let error as NSError{
      print("cuo le: \(error.localizedDescription)")
 }        
上一篇 下一篇

猜你喜欢

热点阅读