Swift v3.0-PREVIEW-1 發布

jopen 8年前發布 | 11K 次閱讀 Swift IOS OS X Objective-C

Swift是一款為iOS和OS X 應用打造的新式編程語言,它吸取了C語言和Objective-C語言的精華,同時完美兼容C語言。Swift采用了安全編程模式,增加了許多現代語言的特性,使編程工作更加簡單,靈活,有趣。一款重新設計的語言,再加上成熟并且深受歡迎的Cocoa框架和Cocoa Touch框架,Swift為軟件開發工作帶來了無限遐想。

特點:

  • 從它的語法中能看到Java Objective-C JavaScript C# Python等語言的影子
  • 語法簡單、代碼簡潔、使用方便
  • 可與Objective-C混合使用(相互調用)
  • 提供了類似 Java 的名字空間(namespace)、泛型(generic)、運算對象重載(operator overloading)
  • 讓應用開發更簡單、更快、更穩定
  • 確保最終應用有著更好的質量

更新日志

  • SE-0093: Slice types now have a base property that allows public readonly access to their base collections.

  • Nested generic functions may now capture bindings from the environment, for example:

    func outer<T>(t: T) -> T {
      func inner<U>(u: U) -> (T, U) {
        return (t, u)
      }
      return inner(u: (t, t)).0
    }
  • Initializers are now inherited even if the base class or derived class is generic:

    class Base<T> {
      let t: T

    init(t: T) { self.t = t } }

    class Derived<T> : Base<T> { // init(t: T) is now synthesized to call super.init(t: t) }</pre> </li>

  • SE-0081 "Move 'where' clause to end of declaration" is implemented, allowing you to write 'where' clauses after the signature for a declaration, but before its body. For example, before:

      func anyCommonElements<T : SequenceType, U : SequenceType 
                             where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element>
          (lhs: T, _ rhs: U) -> Bool
      {
          ...
      }

    after:

      func anyCommonElements<T : SequenceType, U : SequenceType>(lhs: T, _ rhs: U) -> Bool
          where T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element
      {
          ...
      }

    The old form is still accepted for compatibility, but will eventually be rejected.

  • SE-0071: "Allow (most) keywords in member references" is implemented. This allows the use of members after a dot without backticks, e.g. "foo.default".

  • SE-0057: Objective-C lightweight generic classes are now imported as generic types in Swift. Because Objective-C generics are not represented at runtime, there are some limitations on what can be done with them in Swift:

    • If an ObjC generic class is used in a checked as?as!, or is cast, the generic parameters are not checked at runtime. The cast succeeds if the operand is an instance of the ObjC class, regardless of parameters.

      let x = NSFoo<NSNumber>(value: NSNumber(integer: 0))
      let y: AnyObject = x
      let z = y as! NSFoo<NSString> // Succeeds
    • Swift subclasses can only inherit an ObjC generic class if its generic parameters are fully specified.

      // Error: Can't inherit ObjC generic class with unbound parameter T
      class SwiftFoo1<T>: NSFoo<T> { }

      // OK: Can inherit ObjC generic class with specific parameters class SwiftFoo2<T>: NSFoo<NSString> { }</pre> </li>

    • Swift can extend ObjC generic classes, but the extensions cannot be constrained, and definitions inside the extension do not have access to the class's generic parameters.

      extension NSFoo {
        // Error: Can't access generic param T
        func foo() -> T {
          return T()
        }
      }

      // Error: extension can't be constrained extension NSFoo where T: NSString { }</pre> </li>

    • Foundation container classes NS[Mutable]ArrayNS[Mutable]Set, and NS[Mutable]Dictionary are still imported as nongeneric classes for the time being.

    • </ul> </li>
    • As part of the changes for SE-0055 (see below), the pointee types of imported pointers (e.g. the id in id *) are no longer assumed to always be _Nullable even if annotated otherwise. However, an implicit or explicit annotation of_Null_unspecified on a pointee type is still imported as Optional.

    • SE-0055: The types UnsafePointerUnsafeMutablePointerAutoreleasingUnsafeMutablePointerOpaquePointer,Selector, and Zone (formerly NSZone) now represent non-nullable pointers, i.e. pointers that are never nil. A nullable pointer is now represented using Optional, e.g. UnsafePointer<Int>? For types imported from C, non-object pointers (such as int *) now have their nullability taken into account.

      One possible area of difficulty is passing a nullable pointer to a function that uses C variadics. Swift will not permit this directly, so as a workaround please use the following idiom to pass it as a pointer-sized integer value instead:

      unsafeBitCast(nullablePointer, to: Int.self)
    • SE-0046 Function parameters now have consistent labelling across all function parameters. With this update the first parameter declarations will now match the existing behavior of the second and later parameters. This change makes the language simpler.

      Functions that were written and called as follows

        func foo(x: Int, y: Int) {
        }
        foo(1, y: 2)

      func bar(a a: Int, b: Int) { } bar(a: 3, b: 4)</pre>

      will now be written as (to achieve the same behavior):

          func foo(_ x: Int, y: Int) {}
          foo(1, y: 2)
          func bar(a: Int, b: Int) {}
          bar(a: 3, b: 4)
      </li>
    • SE-0037 Comments are now treated as whitespace when determining whether an operator is prefix, postfix, or binary. For example, these now work:

        if /*comment*/!foo { ... }
        1 +/*comment*/2

      This also means that comments can no longer appear between a unary operator and its argument.

        foo/* comment */! // no longer works

      Any parse errors resulting from this change can be resolved by moving the comment outside of the expression.

    • SE-0031 The location of the inout attribute has been moved to after the : and before the parameter type.

    • </ul>
        func foo(inout x: Int) {
        }

      will now be written as:

        func foo(x: inout Int) {
        }
      • SE-0053 let is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to remove it from the function declaration.

      • SE-0003 var is no longer accepted as a parameter attribute for functions. The compiler provides a fixit to create a shadow copy in the function body.

        func foo(var x: Int) {
        }

      will now be written as:

        func foo(x: Int) {
          var x = x
        }
      • The "none" members of imported NS_OPTIONS option sets are marked as unavailable when they are imported. Use [] to make an empty option set, instead of a None member.

      • SE-0043 landed, adding the ability to declare variables in multiple patterns in cases.

      • Renamification landed, so the Clang importer imports ObjC symbols substantially differently. Someone should expand on this point.

      • SE-0040 landed, changing attributes from using = in parameters lists to using :, aligning with function call syntax.

      • Generic typealiases are now supported, e.g.:

          typealias StringDictionary<T> = Dictionary<String, T>
          typealias IntFunction<T> = (T) -> Int
          typealias MatchingTriple<T> = (T, T, T)
          typealias BackwardTriple<T1, T2, T3> = (T3, T2, T1)

      etc.

      • The @noescape attribute has been extended to be a more general type attribute. You can now declare values of@noescape function type, e.g. in manually curried function signatures. You can now also declare local variables of@noescape type, and use @noescape in typealiases. For example, this is now valid code:
          func apply<T, U>(@noescape f: T -> U,
                           @noescape g: (@noescape T -> U) -> U) -> U {
            return g(f)
          }
      • SE-0034 has renamed the #line directive (which resets the logical source location for diagnostics and debug information) to #sourceLocation.

      • Curried function syntax has been removed, and now produces a compile-time error.

      • Generic signatures can now contain superclass requirements with generic parameter types, for example:

        func f<Food : Chunks<Meat>, Meat : Molerat>(f: Food, m: Meat) {}
      • Section markers are created in ELF binaries through special objects during link time. These objects allow for the deletion of swift.ld and the use of non-BFD linkers. A new argument to swiftc is provided to select the linker used, and the gold linker is set as the default for arm-based platforms.

      • Catch blocks in rethrows functions may now throw errors. For example:

        func process(f: () throws -> Int) rethrows -> Int {
            do {
                return try f()
            } catch is SomeError {
                throw OtherError()
            }
        }
      • Throwing closure arguments of a rethrowing function may now be optional. For example:

        func executeClosureIfNotNil(closure: (() throws -> Void)?) rethrows {
            try closure?()
        }
      • SE-0064 The Objective-C selectors for the getter or setter of a property can now be referenced with #selector. For example:

        let sel1 = #selector(getter: UIView.backgroundColor) // sel1 has type Selector
        let sel2 = #selector(setter: UIView.backgroundColor) // sel2 has type Selector
      • SE-0062: A key-path can now be formed with #keyPath. For example:

        person.valueForKeyPath(#keyPath(Person.bestFriend.lastName))

      下載

       本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
       轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
       本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!