appleoneinone'seye是什么意思

文顶顶 - 博客园
最新博文发布地址:
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
正文内容加载中...
摘要: 本文主要介绍前端开发中常用的构建工具Grunt,具体包括Grunt的基本情况、安装、使用和常见插件的安装、配置和使用等内容。 1.1 Grunt简单介绍 Grunt是一套前端自动化构建工具。对于需要反复重复的任务(如压缩、编译、单元测试等),自动化构建工具可以减轻并简化我们的工作。我们只需要在 Gr
摘要: 本文主要介绍前端开发中常用的包管理工具Bower,具体包括Bower的基本情况、安装、使用和常见命令等内容,最后还介绍了依赖树管理的常见方式以及Bower采用的策略并进行了比较。 1.1 关于Bower Bower是一款优秀的包管理器,它由Twitter公司开发,支持以命令行的方式来对包进行搜索、下
摘要: 在javaScript系列 [01]-javaScript函数基础这篇文章中我已经简单介绍了JavaScript语言在函数使用中this的指向问题,虽然篇幅不长,但其实最重要的部分已经讲清楚了,这篇文章我们来单独谈一谈神秘的this,或者叫怎么也搞不清楚的指天指地指空气的this。 1.1 this
摘要: 本文输出和JSON有关的以下内容? JSON和javaScript? JSON的语法介绍? JSON的数据类型? JSON和XMLHTTPRequest? JSON的序列化和反序列化处理 1.1 JSON和javaScript JSON是一种数据交换格式。 JSON的全称是JavaScript Ob
摘要: [04]-javaScript的原型链 本文旨在花很少的篇幅讲清楚JavaScript语言中的原型链结构,很多朋友认为JavaScript中的原型链复杂难懂,其实不然,它们就像树上的一串猴子。 1.1 理解原型链 JavaScript中几乎所有的东西都是对象,我们说数组是对象、DOM节点是对象、函数
摘要: [03]-javaScript原型对象 引用: javaScript是一门基于原型的语言,它允许对象通过原型链引用另一个对象来构建对象中的复杂性,JavaScript使用原型链这种机制来实现动态代理。当试图去引用某一个属性时,它会遍历整个原型链,直到最后的节点。JavaScript专家编程·P24
摘要: [02]-javaScript对象探析 题记:多年前,以非常偶然的方式关注了微信公众号“面向对象”,本以为这个公众号主要以分享面向对象编程的干货为主,不料其乃实实在在的猿圈相亲平台。通过查看公开资料,发现该公众号俨然是在以自己的方式来帮助广大单身程序猿们通往一条真真正正的面向对象编程之路,相对而言,
摘要: [01]-javaScript函数基础 1.1 函数的创建和结构 函数的定义:函数是JavaScript的基础模块单元,包含一组语句,用于代码复用、信息隐蔽和组合调用。 函数的创建:在javaScript语言中,可以说函数是其最重要也最成功的设计。我们可以通过三种方式来创建函数。 ① 函数声明② 字
摘要: 第八章 jQuery框架Ajax模块 8.1 jQuery框架中的Ajax简介 Ajax技术的核心是XMLHTTPRequest对象,该对象是Ajax实现的关键,发送异步请求、接收服务器端的响应以及执行回调等操作都是通过XMLHTTPRequest对象来完成的。 jQuery框架对Ajax操作进行了
摘要: 第七章 jQuery框架的选择器 jQuery框架继承和优化了JavaScript访问DOM对象的特性,我们使用jQuery框架提供的api可以更加方便的操作DOM对象。 7.1 创建DOM节点 使用JavaScript原生方式创建DOM节点并添加到页面中的代码示例: 使用jQuery框架创建DOM
摘要: 第六章 jQuery框架事件处理 JavaScript以事件驱动来实现页面的交互,其核心是以消息为基础,以事件来驱动。虽然利用传统的JavaScript事件处理方式也能够完成页面交互,但jQuery框架增加并扩展了基本的事件处理机制,jQuery框架提供了更加优雅的事件处理语法,并极大的增强了事件处
摘要: 第五章 jQuery框架动画特效 5.1 jQuery动画特效说明 jQuery框架中为我们封装了众多的动画和特效方法,只需要调用对应的动画方法传递合适的参数,就能够方便的实现一些炫酷的效果,而且jQuery框架还支持自定义各种动画效果。 jQuery中的动画效果主要有以下方法 ① 显示和隐藏动画②
摘要: 第四章 jQuery框架的选择器 4.1 jQuery选择器说明 jQuery 最核心的组成部分就是选择器引擎。它完全继承了 CSS 的风格,可以对 DOM 元 素的标签名、属性名、状态等进行快速准确的选 择,而且不必担心浏览器的兼容性,写法更加简洁。 jQuery 选择器实现了 CSS1~CSS3
摘要: 第三章 jQuery框架操作CSS 3.1 jQuery框架的CSS方法 jQuery框架提供了css方法,我们通过调用该方法传递对应的参数,可以方便的来批量设置标签的CSS样式。 使用JavaScript设置标签的样式相对来说比较麻烦,而如果需要批量的设置多个标签的样式那需要写很多代码,使用jQu
摘要: 第二章 jQuery框架使用准备 2.1 jQuery框架和JavaScript加载模式对比 jQuery框架的加载模式 打印结果:window.onload——2 JavaScript的加载模式 打印结果:ready——1 ready——2 两种加载模式对比 ① 监听时机不相同 window.on
随笔 - 196
评论 - 1494Swift Blog - Apple Developer
Swift 3 interfaces with Objective-C APIs in a more powerful way than previous versions. For instance, Swift 2 mapped the id type in Objective-C to the AnyObject type in Swift, which normally can hold only values of class types. Swift 2 also provided implicit conversions to AnyObjectfor some bridged value types, such as String, Array, Dictionary, Set, and some numbers, as a convenience so that the native Swift types could be used easily with Cocoa APIs that expected NSString, NSArray, or the other container classes from Foundation. These conversions were inconsistent with the rest of the language, making it difficult to understand what exactly could be used as an AnyObject, resulting in bugs.In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type. This change makes Objective-C APIs more flexible in Swift, because Swift-defined value types can be passed to Objective-C APIs and extracted as Swift types, eliminating the need for manual “box” types. These benefits also extend to collections: Objective-C collection types NSArray, NSDictionary, and NSSet, which previously only accepted elements of AnyObject, now can hold elements of Any type. For hashed containers, such as Dictionary and Set, there’s a new type AnyHashable that can hold a value of any type conforming to the Swift Hashable protocol. In summary, the following type mappings change from Swift 2 to Swift 3:Objective-CSwift 2Swift 3idAnyObjectAnyNSArray *[AnyObject][Any]NSDictionary *[NSObject: AnyObject][AnyHashable: Any]NSSet *Set&NSObject&Set&AnyHashable&In many cases, your code will not have to change significantly in response to this change. Code that in Swift 2 relied on value types implicitly converting to AnyObject will continue to work as-is in Swift 3 by passing as Any. However, there are places where you will have to change the declared types of variables and methods and get the best experience in Swift 3. Also, if your code is explicitly using AnyObject or Cocoa classes such as NSString, NSArray, or NSDictionary, you will need to introduce more explicit casts using as NSString or as String, since the implicit conversions between the objects and value types are no longer allowed in Swift 3. The automatic migrator in Xcode will make minimal changes to keep your code compiling when moving from Swift 2 to 3, but the result may not always be the most elegant thing. This article will describe some of the changes you may need to make, as well as some pitfalls to look out for when changing your code to take advantage of id as Any.Overriding methods and conforming to protocolsWhen subclassing an Objective-C class and overriding its methods, or conforming to an Objective-C protocol, the type signatures of methods need to be updated when the parent method uses id in Objective-C. Some common examples are the NSObject class’s isEqual: method and the NSCopying protocol’s copyWithZone: method. In Swift 2, you would write a subclass of NSObject conforming to NSCopying like this:
class Foo: NSObject, NSCopying {
override func isEqual(_ x: AnyObject?) -& Bool { ... }
func copyWithZone(_ zone: NSZone?) -& AnyObject { ... }
}In Swift 3, in addition to making the naming change from copyWithZone(_:) to copy(with:), you will also need to change the signatures of these methods to use Any instead of AnyObject:
class Foo: NSObject, NSCopying {
override func isEqual(_ x: Any?) -& Bool { ... }
func copy(with zone: NSZone?) -& Any { ... }
}Untyped CollectionsProperty lists, JSON, and user info dictionaries are common in Cocoa, and Cocoa natively represents these as untyped collections. In Swift 2, it was necessary to build Array, Dictionary, or Set with AnyObject or NSObject elements for this purpose, relying on implicit bridging conversions to handle value types:
struct State {
var name: String
var abbreviation: String
var population: Int
var asPropertyList: [NSObject: AnyObject] {
var result: [NSObject: AnyObject] = [:]
result["name"] = self.name
result["abbreviation"] = self.abbreviation
result["population"] = self.population
return result
let california = State(name: "California",
abbreviation: "CA",
population: 39_000_000)
NSNotification(name: "foo", object: nil,
userInfo: california.asPropertyList)Alternatively, you could use the Cocoa container classes, such as NSDictionary:
struct State {
var name: String
var abbreviation: String
var population: Int
var asPropertyList: NSDictionary {
var result = NSMutableDictionary()
result["name"] = self.name
result["abbreviation"] = self.abbreviation
result["population"] = self.population
return result.copy()
let california = State(name: "California",
abbreviation: "CA",
population: 39_000_000)
NSNotification(name: "foo", object: nil,
userInfo: california.asPropertyList)In Swift 3, the implicit conversions are gone, so neither of the above snippets will work as is. The migrator may suggest individually converting each value using as conversions to to keep this code working, but there’s a better solution. Swift now imports Cocoa APIs as accepting collections of Any and/or AnyHashable, so we can change the collection type to use [AnyHashable: Any] instead of [NSObject: AnyObject] or NSDictionary, without changing any other code:
struct State {
var name: String
var abbreviation: String
var population: Int
var asPropertyList: [AnyHashable: Any] {
var result: [AnyHashable: Any] = [:]
result["name"] = self.name
result["abbreviation"] = self.abbreviation
result["population"] = self.population
return result
let california = State(name: "California",
abbreviation: "CA",
population: 39_000_000)
Notification(name: "foo", object: nil,
userInfo: california.asPropertyList)The AnyHashable TypeSwift’s Any type can hold any type, but Dictionary and Set require keys that are Hashable, so Any is too general. Starting with Swift 3, the Swift standard library provides a new type AnyHashable. Similar to Any, it acts as a supertype of all Hashable types, so values of String, Int, and other hashable types can be used implicitly as AnyHashable values, and the type inside an AnyHashable can be dynamically checked with the is, as!, or as? dynamic cast operators. AnyHashable is used when importing untyped NSDictionary or NSSet objects from Objective-C, but is also useful in pure Swift as a way of building heterogeneous sets or dictionaries.Explicit Conversion for Unbridged ContextsUnder certain limited circumstances, Swift cannot automatically bridge C and Objective-C constructs. For example, some C and Cocoa APIs use id * pointers as “out” or “in-out” parameters, and since Swift is not able to statically determine how the pointer is used, it cannot perform the bridging conversions on the value in memory automatically. In cases like this, the pointer will still appear as an UnsafePointer&AnyObject&. If you need to work with one of these unbridged APIs, you can use explicit bridging conversions, written explicitly using as Type or as AnyObject in your code.
@interface Foo
- (void)updateString:(NSString **)
- (void)updateObject:(id *)
func interactWith(foo: Foo) -& (String, Any) {
var string = "string" as NSString
foo.updateString(&string)
let finishedString = string as String
var object = "string" as AnyObject
foo.updateObject(&object)
let finishedObject = object as Any
return (finishedString, finishedObject)
}Additionally, Objective-C protocols are still class-constrained in Swift, so you cannot make Swift structs or enums directly conform to Objective-C protocols or use them with lightweight generic classes. You will need to explicit convert String as NSString, Array as NSArray, etc. with these protocols and APIs.AnyObject Member LookupAny does not have the same magic method lookup behavior as AnyObject. This may break some Swift 2 code that looked up a property or sent a message to an untyped Objective-C object. For example, this Swift 2 code:
func foo(x: NSArray) {
print(x[0].description)
}will complain that description is not a member of Any in Swift 3. You can convert the value with x[0] as AnyObject to get the dynamic behavior back:
func foo(x: NSArray) {
print((x[0] as AnyObject).description)
}Alternatively, force-cast the value to the concrete object type you expect:func foo(x: NSArray) {
print((x[0] as! NSObject).description)
}Swift Value Types in Objective-CAny can hold any struct, enum, tuple, or other Swift type you can define in the language. The Objective-C bridge in Swift 3 can in turn present any Swift value as an id-compatible object to Objective-C. This makes it much easier to store custom Swift value types in Cocoa containers, userInfo dictionaries, and other objects. For example, in Swift 2, you would need to either change your data types into classes, or manually box them, to attach their values to an NSNotification:
struct CreditCard { number: UInt64, expiration: NSDate }
let PaymentMade = "PaymentMade"
class Box&T& {
let value: T
init(value: T) { self.value = value }
let paymentNotification =
NSNotification(name: PaymentMade,
object: Box(value: CreditCard(number: 00_0000,
expiration: NSDate())))With Swift 3, we can do away with the box, and attach the object directly to the notification:
let PaymentMade = Notification.Name("PaymentMade")
let paymentNotification =
Notification(name: PaymentMade,
object: CreditCard(number: 00_0000,
expiration: Date()))In Objective-C, the CreditCard value will appear as an id-compatible, NSObject- conforming object that implements isEqual:, hash, and description using Swift’s Equatable, Hashable, and CustomStringConvertible implementations if they exist for the original Swift type. From Swift, the value can be retrieved by dynamically casting it back to its original type:
let paymentCard = paymentNotification.object as! CreditCard
print(paymentCard.number) Be aware that, in Swift 3.0, some common Swift and Objective-C struct types will bridge as opaque objects instead of as idiomatic Cocoa objects. For instance, whereas Int, UInt, Double, and Bool bridge to NSNumber, the other sized numeric types such as Int8, UInt16, etc. only bridge as opaque objects. Cocoa structs such as CGRect, CGPoint, and CGSize also bridge as opaque objects even though most Cocoa API that works with them as objects expects them boxed in NSValue instances. If you see errors like unrecognized selector sent to _SwiftValue, that indicates that Objective-C code is trying to invoke a method on an opaque Swift value type, and you may need to manually box that value in an instance of the class the Objective-C code expects.One particular issue to look out for is Optionals. A Swift Any can hold anything, including an Optional, so it becomes possible to pass a wrapped Optional to an Objective-C API without checking it first, even if the API is declared as taking a nonnull id. This will generally manifest as a runtime error involving _SwiftValue rather than a compile-time error. Swift 3.0.1 included in Xcode 8.1 beta handles number types, Objective-C structs, and Optionals transparently by implementing these proposals that address the aforementioned limitations in NSNumber, NSValue, and Optional bridging:To avoid forward compatibility problems, you should not rely on implementation details of opaque objects of the _SwiftValue class, since future versions of Swift may allow more Swift types to bridge to idiomatic Objective-C classes.Linux PortabilitySwift programs running on Linux with the Swift Core Libraries use a version of Foundation natively written in Swift, without an Objective-C runtime to bridge to. id-as-Any allows the Core Libraries to use the native Swift Any and standard library value types directly, while remaining compatible with code on Apple platforms using the Objective-C Foundation implementation. Since Swift does not interoperate with Objective-C on Linux, there is no support for bridging conversions such as string as NSString or value as AnyObject. Swift code that intends to be portable across Cocoa and the Swift Core Libraries should use the value types exclusively.Learning Moreid-as-Any is a great example of a Swift language improvement inspired by user feedback with earlier versions of Swift and refined by review from the open Swift Evolution process. If you want to learn more about the motivations and design decisions behind id-as-Any, the original Swift Evolution proposals are available on GitHub in the swift-evolution repository:The net result is that Swift is a more consistent language, and Cocoa APIs become more powerful when used from Swift.
At WWDC 2016 we announced Swift Playgrounds, a brand new iPad app that teaches core coding concepts using Swift. In addition to the great content Apple provides with the app, we are excited to see what the community of Swift developers will build and share. We presented an in-depth session at WWDC entitled
that shows how to make your own `.playgroundbook` files for iPad, with multiple pages, always-running live views, and gorgeous cut scenes.During this WWDC session we also demonstrated controlling a Sphero SPRK+ robot on stage, driven by Swift Playgrounds on iPad. Because code in Swift Playgrounds has access to the iOS SDK, including the CoreBluetooth framework, you can write programs that can completely control devices such as these robots. We've updated the playground we demonstrated at WWDC so you can see how it works, and even extend it further to teach your robot new tricks. The playground is included in this post and can be shared to an iPad running Swift Playgrounds using iCloud, AirDrop, email, and many other methods.When you run the code on the first page of the playground you will see a touch interface to manually drive the Sphero robot around the room. Be careful, it can get going really fast! Tapping the Next Page glyph at the top of the playground moves to additional pages. Here you have access to a simple API that enables you to use code to control the robot, making it easy to write short programs that move the robot in a square, figure eight, or any other design you can dream up.To run this playground, you will need the Swift Playgrounds app and iOS 10 running on an iPad with a 64-bit chip. You will also need a Sphero robot capable of Bluetooth LE, like the , or the new . As long as the robot is nearby, the playground will find it and let you control it using Swift Playgrounds on your iPad.You can download .
If your app communicates with a web application, information returned from the server is often formatted as . You can use the Foundation framework’s
class to convert JSON into Swift data types like Dictionary, Array, String, Number, and Bool. However, because you can’t be sure of the structure or values of JSON your app receives, it can be challenging to deserialize model objects correctly. This post describes a few approaches you can take when working with JSON in your apps.Extracting Values from JSONThe JSONSerialization class method jsonObject(with:options:) returns a value of type Any and throws an error if the data couldn’t be parsed.import Foundation
let data: Data
let json = try? JSONSerialization.jsonObject(with: data, options: [])Although valid JSON , a response from a web application typically encodes an object or array as the top-level object. You can use optional binding and the as? type cast operator in an if or guard statement to extract a value of known type as a constant. To get a Dictionary value from a JSON object type, conditionally cast it as [String: Any]. To get an Array value from a JSON array type, conditionally cast it as [Any] (or an array with a more specific element type, like [String]). You can extract a dictionary value by key or an array value by index using type cast optional binding with subscript accessors or pattern matching with enumeration.
if let dictionary = jsonWithObjectRoot as? [String: Any] {
if let number = dictionary["someKey"] as? Double {
for (key, value) in dictionary {
if let nestedDictionary = dictionary["anotherKey"] as? [String: Any] {
if let array = jsonWithArrayRoot as? [Any] {
if let firstObject = array.first {
for object in array {
for case let string as String in array {
}Swift’s built-in language features make it easy to safely extract and work with JSON data decoded with Foundation APIs — without the need for an external library or framework.Creating Model Objects from Values Extracted from JSONSince most Swift apps follow the
design pattern, it is often useful to convert JSON data to objects that are specific to your app’s domain in a model definition.For example, when writing an app that provides search results for local restaurants, you might implement a Restaurant model with an initializer that accepts a JSON object and a type method that makes an HTTP request to a server’s /search endpoint and then asynchronously returns an array of Restaurant objects.Consider the following Restaurant model:import Foundation
struct Restaurant {
enum Meal: String {
case breakfast, lunch, dinner
let name: String
let location: (latitude: Double, longitude: Double)
let meals: Set&Meal&
}A Restaurant has a name of type String, a location expressed as a coordinate pair, and a Set of meals containing values of a nested Meal enumeration.Here’s an example of how a single restaurant may be represented in a server response:{
"name": "Caffè Macs",
"coordinates": {
"lat": 37.330576,
"lng": -122.029739
"meals": ["breakfast", "lunch", "dinner"]
}Writing an Optional JSON InitializerTo convert from a JSON representation to a Restaurant object, write an initializer that takes an Any argument that extracts and transforms data from the JSON representation into properties.extension Restaurant {
init?(json: [String: Any]) {
guard let name = json["name"] as? String,
let coordinatesJSON = json["coordinates"] as? [String: Double],
let latitude = coordinatesJSON["lat"],
let longitude = coordinatesJSON["lng"],
let mealsJSON = json["meals"] as? [String]
return nil
var meals: Set&Meal& = []
for string in mealsJSON {
guard let meal = Meal(rawValue: string) else {
return nil
meals.insert(meal)
self.name = name
self.coordinates = (latitude, longitude)
self.meals = meals
}If your app communicates with one or more web services that do not return a single, consistent representation of a model object, consider implementing several initializers to handle each of the possible representations.In the example above, each of the values are extracted into constants from the passed JSON dictionary using optional binding and the as? type casting operator. For the name property, the extracted name value is simply assigned as-is. For the coordinate property, the extracted latitude and longitude values are combined into a tuple before assignment. For the meals property, the extracted string values are iterated over to construct a Set of Meal enumeration values.Writing a JSON Initializer with Error HandlingThe previous example implements an optional initializer that returns nil if deserialization fails. Alternatively, you can define a type conforming to the Error protocol and implement an initializer that throws an error of that type whenever deserialization fails.enum SerializationError: Error {
case missing(String)
case invalid(String, Any)
extension Restaurant {
init(json: [String: Any]) throws {
guard let name = json["name"] as? String else {
throw SerializationError.missing("name")
guard let coordinatesJSON = json["coordinates"] as? [String: Double],
let latitude = coordinatesJSON["lat"],
let longitude = coordinatesJSON["lng"]
throw SerializationError.missing("coordinates")
let coordinates = (latitude, longitude)
guard case (-90...90, -180...180) = coordinates else {
throw SerializationError.invalid("coordinates", coordinates)
guard let mealsJSON = json["meals"] as? [String] else {
throw SerializationError.missing("meals")
var meals: Set&Meal& = []
for string in mealsJSON {
guard let meal = Meal(rawValue: string) else {
throw SerializationError.invalid("meals", string)
meals.insert(meal)
self.name = name
self.coordinates = coordinates
self.meals = meals
}Here, the Restaurant type declares a nested SerializationError type, which defines enumeration cases with associated values for missing or invalid properties. In the throwing version of the JSON initializers, rather than indicating failure by returning nil, an error is thrown to communicate the specific failure. This version also performs validation of input data to ensure that coordinates represents a valid geographic coordinate pair and that each of the names for meals specified in the JSON correspond to Meal enumeration cases.Writing a Type Method for Fetching ResultsA web application endpoint often returns multiple resources in a single JSON response. For example, a /search endpoint may return zero or more restaurants that match the requested query parameter and include those representations along with other metadata:{
"query": "sandwich",
"results_count": 12,
"page": 1,
"results": [
"name": "Caffè Macs",
"coordinates": {
"lat": 37.330576,
"lng": -122.029739
"meals": ["breakfast", "lunch", "dinner"]
}You can create a type method on the Restaurant structure that translates a query method parameter into a corresponding request object and sends the HTTP request to the web service. This code would also be responsible for handling the response, deserializing the JSON data, creating Restaurant objects from each of the extracted dictionaries in the "results" array, and asynchronously returning them in a completion handler.extension Restaurant {
private let urlComponents: URLComponents
private let session: URLSession
static func restaurants(matching query: String, completion: ([Restaurant]) -& Void) {
var searchURLComponents = urlComponents
searchURLComponents.path = "/search"
searchURLComponents.queryItems = [URLQueryItem(name: "q", value: query)]
let searchURL = searchURLComponents.url!
session.dataTask(url: searchURL, completion: { (_, _, data, _)
var restaurants: [Restaurant] = []
if let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] {
for case let result in json["results"] {
if let restaurant = Restaurant(json: result) {
restaurants.append(restaurant)
completion(restaurants)
}).resume()
}A view controller can call this method when the user enters text into a search bar to populate a table view with matching restaurants:import UIKit
extension ViewController: UISearchResultsUpdating {
func updateSearchResultsForSearchController(_ searchController: UISearchController) {
if let query = searchController.searchBar.text, !query.isEmpty {
Restaurant.restaurants(matching: query) { restaurants in
self.restaurants = restaurants
self.tableView.reloadData()
}Separating concerns in this way provides a consistent interface for accessing restaurant resources from view controllers, even when the implementation details about the web service change.Reflecting on ReflectionConverting between representations of the same data in order to communicate between different systems is a tedious, albeit necessary, task for writing software.Because the structure of these representations can be quite similar, it may be tempting to create a higher-level abstraction to automatically map between these different representations. For instance, a type might define a mapping between snake_case JSON keys and camelCase property names in order to automatically initialize a model from JSON using the Swift reflection APIs, such as .However, we’ve found that these kinds of abstractions tend not to offer significant benefits over conventional usage of Swift language features, and instead make it more difficult to debug problems or handle edge cases. In the example above, the initializer not only extracts and maps values from JSON, but also initializes complex data types and performs domain-specific input validation. A reflection-based approach would have to go to great lengths in order to accomplish all of these tasks. Keep this in mind when evaluating the available strategies for your own app. The cost of small amounts of duplication may be significantly less than picking the incorrect abstraction.
Swift 3 beta was just released as part of Xcode 8 beta and includes numerous enhancements, many contributed by the open source community. The primary goal of Swift 3 is to implement the last major source changes necessary to allow Swift to coalesce as a consistent language throughout, resulting in a much more stable syntax for future releases.Swift syntax and API renaming changes in Swift 3 make the language feel more natural, and provide an even more Swift-y experience when calling Cocoa frameworks. Popular frameworks Core Graphics and Grand Central Dispatch have new, much cleaner interfaces in Swift. This release also improves build performance, and includes many small fixes that will make it more enjoyable to use every day. includes a migrator for Swift files and playgrounds to help you move your existing code to Swift 3.Swift 2.3In addition to Swift 3, Xcode 8 supports development with Swift 2.3, a minor update to the Swift 2.2 language built to work with the new SDKs for macOS Sierra, iOS 10, tvOS 10, and watchOS 3. This is intended to allow developers to immediately move to these latest SDKs, even for projects that may be late in development with Swift 2.2 and not yet ready to move to Swift 3. Xcode 8 can migrate your code to the new Swift 2.3 changes, primarily related to nullability clarity that's been added to the new SDKs. For instance:Swift 2.2 Core Image code without the new SDK nullability definition:let image = CIImage(MTLTexture: texture, options: options)Swift 2.3 code makes the failable initializer more clear:if let image = CIImage(MTLTexture: texture, options: options)Or:let image = CIImage(MTLTexture: texture, options: options)!Swift 3 is the primary development language supported within Xcode 8 so there are a couple notes to consider if you chose to continue using Swift 2.3. First, Swift 2.3 and Swift 3 are not binary compatible so your app's entire code base needs to pick one version of Swift. Both versions are fully supported by the compiler, SDKs, and debugger, but other features of the IDE may not work with Swift 2.3. For instance, Playgrounds in Xcode only work with Swift 3, and notably the Swift Playgrounds app for iPad also uses Swift 3. Xcode project templates all use Swift 3, and all documentation is presented in a format appropriate for Swift 3.When Xcode 8 is GM later this year, you will be able to submit your apps to the App Store written in either Swift 3.0 or 2.3. The changes in Swift 3 represent the future of the Swift language, and we strongly encourage you to budget time to migrate your Swift code to version 3. Even if you first migrate to Swift 2.3 in the interim, you can later run the Xcode 8 migrator to move from Swift 2.3 to Swift 3.
Xcode 7.3 beta 3 adds interactive iOS and OS X playgrounds that allow you to click, drag, type, and otherwise interact with the user interfaces you code into your playground. These interfaces react just as they would within a full application. Interactive playgrounds help you to quickly prototype and build your applications, and simply provide another great way to interact with your code.Any view or view controller that is assigned to the liveView property of the XCPlaygroundPage is automatically made interactive, and since it runs within a playground you get all the usual playground results. You can experiment with gesture recognizers, see how UITableView creates and dequeues cells as you scroll, or interact with a complex 3D scene in SceneKit.Sample playgroundBelow is an iOS playground that uses UIKit Dynamics to create a fully-interactive and customizable , perfect for your desktop.
Swift is now open source. Today Apple launched the open source Swift community, as well as amazing new tools and resources including: – a site dedicated to the open source Swift communityPublic source code repositories at A new Swift package manager project for easily sharing and building codeA Swift-native core libraries project with higher-level functionality above the standard libraryPlatform support for all Apple platforms as well as LinuxNow anyone can download the code and in-development builds to see what the team is up to. More advanced developers interested in contributing to the project can file bugs, participate in the community, and contribute their own fixes and enhancements to make Swift even better. For production App Store development you should always use the stable releases of Swift included in Xcode, and this remains a requirement for app submission.Swift.orgSwift.org is an entirely new site dedicated to open source Swift. This site hosts resources for the community of developers that want to help evolve Swift, contribute fixes, and most importantly, interact with each other. Swift.org hosts:A bug reporting and tracking systemMailing listsA blog dedicated to the engineering of SwiftCommunity guidelinesGetting started tutorialsContributing instructionsDocumentation on SwiftDeveloper and API design guidelinesSwift.org is where the daily engineering work for Swift will take place, as the community of developers work together to bring Swift to new platforms, add new features, and continually evolve our favorite language.Source CodeApple has a new home on GitHub located at
where you can find all the source code for the Swift project. The public repositories include the Swift compiler, LLDB debugger and REPL, the standard and core libraries, the package manager, and other supporting projects.GitHub is already an incredibly popular place for developers to collaborate. It is easy to view the source code right on the website, or quickly check-out the code to your machine. And when you have a patch to contribute, we accept pull requests.Swift Package ManagerToday we also launched a brand new project: the Swift Package Manager. This early-stage project will be developed in the open from the outset. The repository is in a very early state, and together we will define what a great package manager should do and how we can make it intuitive to use, and give it the power it needs to scale across the many platforms where we expect Swift to prosper.Core LibrariesApple has long provided a rich collection of frameworks that provide higher-level functionality commonly required across a wide variety of software. Frameworks such as Foundation, libdispatch, and XCTest make it much easier to write complex programs, and we wanted to be sure that developers get those same benefits as they take their Swift skills to new platforms. Whether writing apps for iPhone or Mac, or building a new cloud service on Linux, the Swift core libraries will give you building blocks you can count on.PlatformsOpen source Swift runs on a Mac, and is capable of building apps for OS X, iOS, watchOS, and tvOS. Swift.org also offers a Linux version of Swift, complete with a Linux toolset including package manager support, the LLDB debugger, and the REPL. We’re excited to see the community bring Swift to even more new places. As students and professionals learn to program in Swift, each new platform and use case opens new opportunities for them across the technology industry.Getting StartedIt is easy to get started. Swift.org hosts binary downloads of the compilers and command line tools for the Apple and Linux platforms so you can be up and running quickly. The latest version of Xcode supports an alternate toolchain option specifically designed to make it simple to try out the latest open source builds of Swift from within Xcode. And Swift.org has great getting started guides to walk you through the process of setting up your environment to work with open source Swift.
New in Xcode 7.1 is the ability to embed file, image, and color literals into your playground’s code. Literals are the actual values of your data represented in their native format, directly within the Xcode editor. For instance, there’s no need to type “myImage.jpg” in the editor – just drag your image from the Finder and the actual image will appear in-line with your code. Instead of showing RGB values to indicate color, the playground will render a color swatch. Literals in playgrounds behave similarly to code you would otherwise hand-author in regular Swift code, but are rendered in a much more useful manner.In addition to looking cool, literals can also make editing resources much faster. You can use the color picker to quickly choose a different color from the palette. Drag-and-drop files from the Finder into your playground code to start using them immediately. You can even add a literal at your current cursor position by selecting Editor & Insert File, Image, or Color Literal. Double-clicking a literal allows you to easily choose another value.Resources are copied into your playground’s resources directory if needed, so everything your playground requires is included within the document. Because literals are part of your code, you can also copy, paste, move, and delete them exactly how you would any source code.Literals in Swift CodeLiterals translate into platform-specific types, the defaults of which are listed below:Object LiteralOS XiOS and tvOSColorNSColorUIColorFileNSURLNSURLImageNSImageUIImageTo get the full in-line presentation experience of literals, you must be in a playground. However, if you copy and paste code that uses literals into your main Swift source code, the pasted code will work as expected and Xcode will simply render the literals as plain text.To get you started with literals we’ve included a very short playground in this blog post. Download the latest
a try.Additional DocumentationDocumentation accompanying Xcode 7.1 beta 3 includes an updated
with new information on the many powerful features in playgrounds, including new content on literals. Here are direct links to the relevant sub-pages: , , and .Below is a screenshot demonstrating how literals appear within Xcode 7.1:
Swift 2 is ready for the world. You can now submit your apps that take advantage of the latest features in Swift 2 that make code more readable and powerful, including guard, the new error handling model, and availability controls.Make sure to build your apps with
and test with the GM seed of , and the final versions of
and .Xcode 7 and OS X El CapitanOS X El Capitan requires Xcode 7, which includes Swift 2, native support for System Integrity Protection (SIP), app thinning, as well as the latest SDKs. When running Xcode 7 you may notice a number of syntactical changes need to be applied to your Swift 1.2 code. To help in your migration to Swift 2, Xcode 7 includes a helpful tool to re-write older Swift code for you. Just select the menu item Edit > Convert > To Latest Swift Syntax and Xcode will migrate your code to the latest Swift API and syntax.If your code is in the late stages of development and you must stay on Xcode 6 for a little while, you will need to continue to use OS X Yosemite as your development OS. The combination of OS X El Capitan and Xcode 6 is not supported for App Store submission due to significant changes in the underlying architecture. If you need to install OS X Yosemite on another partition or external hard drive, you can download OS X Yosemite from the App Store and
to install it. Also note that Xcode 7 is supported on both OS X El Capitan and Yosemite.
In Xcode 6.3 we added the new
language feature for Objective-C. This feature gave Objective-C a way to express the same sorts of null and non-null API contracts that Optionals provide in Swift. Xcode 7 continues to make communication between Objective-C and Swift more natural by introducing a lightweight generics model for Objective-C. Generics enable the two languages to safely understand and share collections containing specific kinds of elements.These features are useful for anyone writing apps that contain both Swift and Objective-C code. But there’s a much larger collection of Objective-C code that app developers use every day: the frameworks that make up the Apple SDKs. To improve the experience of working with Swift and with Objective-C, we made a company-wide effort to provide this information in our SDK headers. In Xcode 7 you’ll find that nearly all of the common frameworks now specify the nullability of their APIs and the elements of their collection types. This takes our Swift interface from this:class UIView : UIResponder {
init!(frame: CGRect)
var superview: UIView! { get }
var subviews: [AnyObject]! { get }
var window: UIWindow! { get }
func isDescendantOfView(view: UIView!) -& Bool
func viewWithTag(tag: Int) -& UIView!
var constraints: [AnyObject]! { get }
}To this:class UIView : UIResponder {
init(frame: CGRect)
var superview: UIView? { get }
var subviews: [UIView] { get }
var window: UIWindow? { get }
func isDescendantOfView(view: UIView) -& Bool
func viewWithTag(tag: Int) -& UIView?
var constraints: [NSLayoutConstraint] { get }
}The last piece of the puzzle is the Xcode 7 tool to convert your code to Swift 2. This tool lives in Xcode under the Edit menu as Convert & To Latest Swift Syntax. The tool takes a project that uses Swift 1.2 and applies the necessary edits to turn your code into valid Swift 2 code. These changes account for the improved header information. For instance, if you are overriding a method whose parameter and result types are now more precise, the migrator will update your method to match.The improvements to Objective-C were detailed at WWDC in
starting at the 14:30 mark. Note that this video uses the Xcode 6.3 __nullable syntax as opposed to the updated syntax in Xcode 7 that uses _Nullable. For more information on nullability annotations, see the blog post . For more information on Swift 2 and Objective-C lightweight generics, see the .
Swift provides a performant, Unicode-compliant string implementation as part of its Standard Library. In Swift 2, the String type no longer conforms to the CollectionType protocol, where String was previously a collection of Character values, similar to an array. Now, String provides a characters property that exposes a character collection view.Why the change? Although it may seem natural to model a string as a collection of characters, the String type behaves quite differently from collection types like Array, Set, or Dictionary. This has always been true, but with the addition of protocol extensions to Swift 2 these differences made it necessary to make several fundamental changes.Different Than the Sum of Its PartsWhen you add an element to a collection, you expect that the collection will contain that element. That is, when you append a value to an array, the array then contains that value. The same applies to a dictionary or a set. However, when you append a combining mark character to a string, the contents of the string itself change.Consider the string cafe, which has four characters: c, a, f, and e:var letters: [Character] = ["c", "a", "f", "e"]
var string: String = String(letters)
print(letters.count)
print(string)
print(string.characters.count) If you append the combining acute accent character U+0301 ? the string still has four characters, but the last character is now é:let acuteAccent: Character = "\u{0301}"
string.append(acuteAccent)
print(string.characters.count)
print(string.characters.last!) The string’s characters property does not contain the original lowercase e, nor does it contain the combining acute accent ? that was just appended. Instead, the string now contains a lowercase “e” with acute accent é:string.characters.contains("e")
string.characters.contains("?")
string.characters.contains("é") If we were to treat strings like any other collection, this result would be as surprising as adding UIColor.redColor() and UIColor.greenColor() to a set and the set then reporting that it contains UIColor.yellowColor().Judged by the Contents of Its CharactersAnother difference between strings and collections is the way they determine equality.Two arrays are equal only if both have the same count, and each pair of elements at corresponding indices are equal.Two sets are equal only if both have the same count, and each element contained in the first set is also contained in the second.Two dictionaries are equal only if they have the same set of key, value pairs.However, String determines equality based on being canonically equivalent. Characters are canonically equivalent if they have the same linguistic meaning and appearance, even if they are composed from different Unicode scalars behind the scenes.Consider the Korean writing system, which consists of 24 letters, or Jamo, representing individual consonants and vowels. When written out these letters are combined into characters for each syllable. For example, the character “?” ([ga]) is composed of the letters “?” ([g]) and “?” [a]. In Swift, strings are considered equal regardless of whether they are constructed from decomposed or precomposed character sequences:let decomposed = "\u{1100}\u{1161}"
let precomposed = "\u{AC00}"
decomposed == precomposed Again, this behavior differs greatly from any of Swift’s collection types. It would be as surprising as an array with values ? and ? being considered equal to ?.Depends on Your Point of ViewStrings are not collections. But they do provide views that conform to CollectionType:characters is a collection of Character values, or .unicodeScalars is a collection of .utf8 is a collection of
code units.utf16 is a collection of
code units.If we take the previous example of the word “café”, comprised of the decomposed characters [ c, a, f, e ] and [ ? ], here's what the various string views would consist of:The characters property segments the text into extended grapheme clusters, which are an approximation of user-perceived characters (in this case: c, a, f, and é). Because a string must iterate through each of its positions within the overall string (each position is called a code point) in order to determine character boundaries, accessing this property is executed in linear O(n) time. When processing strings that contain human-readable text, high-level locale-sensitive Unicode algorithms, such as those used by the localizedStandardCompare(_:) method and the localizedLowercaseString property, should be preferred to character-by-character processing.The unicodeScalars property exposes the underlying scalar values stored in the string. If the original string were created with the precomposed character é instead of the decomposed e + ?, this would be reflected by the Unicode scalars view. Use this API when you are performing low-level manipulation of character data.The utf8 and utf16 properties provide code points for the UTF–8 and UTF–16 representations, respectively. These values correspond to the actual bytes written to a file when translated to and from a particular encoding. UTF-8 code units are used by many POSIX string processing APIs, whereas UTF-16 code units are used throughout Cocoa & Cocoa Touch to represent string lengths and offsets.For more information about working with Strings and Characters in Swift, read
Today at WWDC, we announced Swift 2.0.
This new version has even better performance, a new error handling API, and first-class support for availability checking. And platform APIs feel even more natural in Swift with enhancements to the Apple SDKs.Open SourceIn addition to new features, the big news is that Apple will be making Swift open source later this year. We are all incredibly excited about this, and look forward to giving you a lot more information as the open source release gets nearer. Here is what we can tell you so far:Swift source code will be released under an OSI-approved permissive license.Contributions from the community will be accepted — and encouraged.At launch we intend to contribute ports for OS X, iOS, and Linux.Source code will include the Swift compiler and standard library.We think it would be amazing for Swift to be on all your favorite platforms.We are excited about the opportunities an open source Swift creates for our industry. Baked-in safety features combined with excellent speed mean it has the chance to dramatically improve software versus using C-based languages. Swift is packed with modern features, it’s fun to write, and we believe it will get used in a lot of places. Together, we have an exciting road ahead.New FeaturesSwift 2.0 also includes a lot of new language features and refinements. Expect to see blog posts exploring the features in more depth, and be sure to watch for the WWDC sessions covering these topics all this week. A few of the new features include:Error handling model: The new error handling model in Swift 2.0 will instantly feel natural, with familiar try, throw, and catch keywords. Best of all, it was designed to work perfectly with the Apple SDKs and NSError. In fact, NSError conforms to a Swift’s ErrorType. You’ll definitely want to watch the WWDC session on What’s New in Swift to hear more about it.Availability: Using the latest SDKs ensures you get access to new features and information about platform changes. But sometimes you still need to target an older OS, and Swift makes doing so much easier and safer. The Swift compiler now shows an error when you use an API that is too new for your target OS, and #available blocks can safely wrap lines of code to only run when on the right OS versions.Protocol extensions: Swift is very focused on protocol-oriented development — there’s even a session on the topic at WWDC 2015. Swift 2.0 adds protocol extensions, and the standard library itself uses them extensively. Where you used to use global functions, Swift 2.0 now adds methods to common types so functions chain naturally, and your code is much more readable.Swift-er SDKs: Swift 2 works even better with the Apple SDKs, thanks in part to two new features in Objective-C: nullability annotations and generics. The SDKs have been updated to annotate API that cannot return nil so you don’t need to use optionals as often. And with a true generics system employed by the SDKs you can more often preserve detailed type information in your Swift 2 code.Learn moreThis is just a taste of what’s new in Swift 2. You can download the latest version of The Swift Programming Language from the iBooks Store, and be sure to watch the WWDC sessions live streamed and on video throughout the week. And to read more, visit
A primary focus when designing Swift was improving the memory safety of the programming model. There are a lot of aspects of memory safety, so this post will start slow and cover a simple case: how to make sure that variables are initialized with a value before they are used. The Swift ApproachVariables are considered “safe” when the developer can be sure that there will be a valid value ready to use before any code tries to access it. Languages take several different approaches to this kind of safety. Some, like C, put the burden entirely on the programmer to employ safe programming techniques — a powerful approach, but riddled with risk. C++ and Objective-C improve the situation by enforcing some mandatory patterns, while other languages take extreme measures by requiring initialization at the point of definition.The primary technique employed by Swift is to use our advanced compiler to perform dataflow analysis of the code. The compiler then enforces that each variable was initialized before it is used, a strategy known as . Languages such as Java and C# (among others) are known to also employ this technique. Swift uses an extended version of this approach for a broad range of variables.Definitive Initialization of Local VariablesSwift applies the rules of definitive initialization in many contexts, but the simplest use is for local variables. Definitive initialization gives you more flexibility than a “implicit default initialization” rule (see below) would, because it allows you to write this code:var myInstance : MyClass
if x & 42 {
myInstance = MyClass(intValue: 13)
myInstance = MyClass(floatValue: 92.3)
myInstance.printIt()Here the compiler can prove that both sides of the if statement are guaranteed to initialize myInstance, which proves that the method call can’t use uninitialized memory.Definitive initialization is a powerful approach, but it is only really useful if it is reliable and predictable. One place that this can lead to surprise is when you have more complex control flow, for example like this:var myInstance : MyClass
if x & 10 {
myInstance = MyClass(intValue: 13)
if x & 42 {
myInstance.printIt()
}In this case, the compiler will tell you: “Variable myInstance used before initialized” on the call to printIt(). This is because the compiler does not track the correlation between the predicates in the if conditions. While we could teach the compiler to handle individual specific cases like this one, it is impossible to handle all cases (doing so is equivalent to the ) so we opted to keep the compiler’s rules simple and predictable.Swift makes it extremely easy to initialize a variable. In fact, it is shorter to declare a variable as var x = 0 giving the variable the initial value 0 than it is to declare the uninitialized variable var x : Int. Swift favors explicitness of initialization whenever possible. There are also more powerful ways to initialize a variable when the situation calls for it using init(). For comprehensive information you can read the chapter "" in The Swift Programming Language.Other ApproachesIn addition to definitive initialization, Swift also employs additional approaches in focused areas of the language. You may have used these techniques in other languages, so we wanted to cover them briefly in this post. Each has some drawbacks, so they aren’t used as Swift’s primary approach:Leave safety to the programmer: Given the prevalence of C, it was important to understand the pros and cons of simply leaving safety up to the developer. Unfortunately, use of an uninitialized value in C produces , often leading to runtime explosions. C relies on the programmer to never make a mistake. Given that our goal was to make Swift “safe by default,” this approach was quickly discarded for general use. However, APIs like UnsafePointer allow you to explicitly opt-in to unsafety when this power is absolutely necessary.Implicit Default Initialization: Values could be ensured to be safe by having the compiler implicitly initialize them, for example by setting a “zero value” like Objective-C does for instance variables, or by running default initializers like in C++. We explored this approach in depth, but ultimately decided against its broad use because:This doesn’t work for cases that have no legal initial value, e.g. protocols with no init() requirement, and non-nullable references to classes, which are pervasive in Swift.Even for primitive types like integers 0 is often the wrong value. That’s one reason setting the initial value is so easy in Swift. This also makes the code more obvious for those who will maintain it, as well as defining away a potential error of omission, e.g. when -1 is the right sentinel to use.Note that default initialization to nil is clearly the right answer for nullable values so all values of Optional and ImplicitlyUnwrappedOptional type automatically initialize to nil by default.Require an initializer at definition. Put the burden on the developer to always provide an initial value at the time the variable is defined, meaning that var x : Int would be illegal without an initializer. While this is a common approach among functional languages, we considered this to be too heavy of a requirement because it enforces a very strict programming style, which gets in the way of expressing natural patterns.
Like many other languages, Swift allows a class to override methods and properties declared in its superclasses. This means that the program has to determine at runtime which method or property is being referred to and then perform an indirect call or indirect access. This technique, called dynamic dispatch, increases language expressivity at the cost of a constant amount of runtime overhead for each indirect usage. In performance sensitive code such overhead is often undesirable. This blog post showcases three ways to improve performance by eliminating such dynamism: final, private, and Whole Module Optimization.Consider the following example:class ParticleModel {
var point = ( 0.0, 0.0 )
var velocity = 100.0
func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
var p = ParticleModel()
for i in stride(from: 0.0, through: 360, by: 1.0) {
p.update((i * sin(i), i), newV:i*1000)
}As written, the compiler will emit a dynamically dispatched call to:Call update on p.Call updatePoint on p.Get the property point tuple of p.Get the property velocity of p.This might not be what you would expect when looking at this code. The dynamic calls are necessary because a subclass of ParticleModel might override point or velocity with a computed property or override updatePoint() or update() with new implementations.In Swift, dynamic dispatch calls are implemented by looking up a function from a method table and then performing an indirect call. This is slower than performing a direct call. Additionally, indirect calls also prevent many compiler optimizations, making the indirect call even more expensive. In performance critical code there are techniques you can use to restrict this dynamic behavior when it isn’t needed to improve performance.Use final when you know that a declaration does not need to be overridden.The final keyword is a restriction on a class, method, or property that indicates that the declaration cannot be overridden. This allows the compiler to safely elide dynamic dispatch indirection. For instance, in the following point and velocity will be accessed directly through a load from the object’s stored property and updatePoint() will be called via a direct function call. On the other hand, update() will still be called via dynamic dispatch, allowing for subclasses to override update() with customized functionality.class ParticleModel {
final var point = ( x: 0.0, y: 0.0 )
final var velocity = 100.0
final func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}It is possible to mark an entire class as final by attaching the attribute to the class itself. This forbids subclassing the class, implying that all functions and properties of the class are final as well.final class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
}Infer final on declarations referenced in one file by applying the private keyword.Applying the private keyword to a declaration restricts the visibility of the declaration to the current file. This allows the compiler to find all potentially overriding declarations. The absence of any such overriding declarations enables the compiler to infer the final keyword automatically and remove indirect calls for methods and property accesses.Assuming there is no class overriding ParticleModel in the current file, the compiler can replace all dynamically dispatched calls to private declarations with direct calls.class ParticleModel {
private var point = ( x: 0.0, y: 0.0 )
private var velocity = 100.0
private func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
}As in the previous example, point and velocity are accessed directly and updatePoint() is called directly. Again, update() will be invoked indirectly due to update() not being private.Just like with final, it is possible to apply the private attribute to the class declaration itself causing the class to be private and thus all of the properties and methods of the class as well.private class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
}Use Whole Module Optimization to infer final on internal declarations.Declarations with internal access (the default if nothing is declared) are only visible within the module where they are declared. Because Swift normally compiles the files that make up a module separately, the compiler cannot ascertain whether or not an internal declaration is overridden in a different file. However, if Whole Module Optimization is enabled, all of the module is compiled together at the same time. This allows the compiler to make inferences about the entire module together and infer final on declarations with internal if there are no visible overrides.Let’s go back to the original code snippet, this time adding some extra public keywords to ParticleModel.public class ParticleModel {
var point = ( x: 0.0, y: 0.0 )
var velocity = 100.0
func updatePoint(newPoint: (Double, Double), newVelocity: Double) {
point = newPoint
velocity = newVelocity
public func update(newP: (Double, Double), newV: Double) {
updatePoint(newP, newVelocity: newV)
var p = ParticleModel()
for i in stride(from: 0.0, through: times, by: 1.0) {
p.update((i * sin(i), i), newV:i*1000)
}When compiling this snippet with Whole Module Optimization the compiler can infer final on the properties point, velocity, and the method call updatePoint(). In contrast, it can not be inferred that update() is final since update() has public access.
Xcode 6.3 beta 3 adds even more to the new playgrounds format introduced in the last beta. The Xcode Project Navigator now lets you easily access a new Sources folder that includes additional Swift code, as well as the Resources folder.Playgrounds and the Project NavigatorPlaygrounds are now represented within Xcode as a bundle with a disclosure triangle that reveals Resources and Sources folders when clicked. These folders contain additional content that is easily accessible from your playground’s main Swift code. To see these folders, choose View > Navigators > Show Project Navigator (or just hit Command-1).It is easy to drag-and-drop images and other content into the Resources folder. You may want to go back and look at the DemoNewFormat.playground file from the
for another example of how these resources are stored and used (using the latest Xcode 6.3 beta 3).Sources FolderThe Sources folder is new in Xcode 6.3 beta 3. This folder contains additional Swift source files that your main playground code can easily access. Putting extra supporting .swift files into the Sources folder makes it easy to keep your playground clean and readable. Code in the Sources folder also gains a big performance benefit because this code is compiled once, and is not run in the same interactive manner as the main playground code. This allows curriculum and sample code authors to create even more interactive and exciting playgrounds while the visible code remains approachable for the reader.Mandelbrot ExampleHere’s an example playground that calculates the complex and beautiful Mandelbrot set. This playground uses the Sources folder to demonstrate the power and added performance that it enables. To see the inner workings of , examine the code within the Sources folder.
One of the great things about Swift is that it transparently interoperates with Objective-C code, both existing frameworks written in Objective-C and code in your app. However, in Swift there’s a strong distinction between optional and non-optional references, e.g. NSView vs. NSView?, while Objective-C represents boths of these two types as NSView *. Because the Swift compiler can’t be sure whether a particular NSView * is optional or not, the type is brought into Swift as an implicitly unwrapped optional, NSView!.In previous Xcode releases, some Apple frameworks had been specially audited so that their API would show up with proper Swift optionals. Xcode 6.3 supports this for your own code with a new Objective-C language feature: nullability annotations.The Core: _Nullable and _NonnullAt the core of this feature we have two new type annotations: _Nullable and _Nonnull. As you might expect, a _Nullable pointer may have a NULL or nil value, while a _Nonnull one should not. The compiler will tell you if you try to break the rules.@interface AAPLList : NSObject &NSCoding, NSCopying&
- (AAPLListItem * _Nullable)itemWithName:(NSString * _Nonnull)
@property (copy, readonly) NSArray * _Nonnull allI
[self.list itemWithName:nil]; You can use _Nullable and _Nonnull almost anywhere you can use the normal C const keyword, though of course they have to apply to a pointer type. However, in the common case there’s a much nicer way to write these annotations: within method declarations you can use the non-underscored forms nullable and nonnull immediately after an open parenthesis, as long as the type is a simple object or block pointer.- (nullable AAPLListItem *)item}

我要回帖

更多关于 one day an apple 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信