玖叶教程网

前端编程开发入门

Swift中的api更易于读取和维护与安全性设计及快速 #学浪计划

Swift是编程语言最新研究成果,结合数十年来构建苹果平台的经验。命名参数以干净的语法表示,这使得Swift中的api更易于读取和维护。更好的是,你甚至不需要输入分号。推断类型使代码更干净,更不容易出错,而模块则消除头并提供名称空间。为了最好地支持国际语言和表情符号,字符串是Unicode正确的,并使用基于UTF-8的编码来优化各种用例的性能。内存是使用严格的、确定性的引用计数自动管理的,从而将内存使用量保持在最低限度,而不会产生垃圾回收的开销。

Swift is the result of the latest research on programming languages, combined with decades of experience building Apple platforms. Named parameters are expressed in a clean syntax that makes APIs in Swift even easier to read and maintain. Even better, you don’t even need to type semi-colons. Inferred types make code cleaner and less prone to mistakes, while modules eliminate headers and provide namespaces. To best support international languages and emoji, Strings are Unicode-correct and use a UTF-8 based encoding to optimize performance for a wide-variety of use cases. Memory is managed automatically using tight, deterministic reference counting, keeping memory usage to a minimum without the overhead of garbage collection.

使用现代、简单的语法声明新类型。为实例属性提供默认值并定义自定义初始值设定项。

Declare new types with modern, straightforward syntax. Provide default values for instance properties and define custom initializers.

extension Player {
    mutating func updateScore(_ newScore: Int) {
        history.append(newScore)
        if highScore < newScore {
            print("\(newScore)! A new high score for \(name)! ")
            highScore = newScore
        }
    }
}

player.updateScore(50)
// Prints "50! A new high score for Tomas! "
// player.highScore == 50

使用扩展向现有类型添加功能,并减少使用自定义字符串插值的样板。

Add functionality to existing types using extensions, and cut down on boilerplate with custom string interpolations.

extension Player: Codable, Equatable {}

import Foundation
let encoder = JSONEncoder()
try encoder.encode(player)

print(player)
// Prints "Tomas, games played: 1, high score: 50”

快速扩展自定义类型以利用强大的语言功能,例如自动JSON编码和解码。

Quickly extend your custom types to take advantage of powerful language features, such as automatic JSON encoding and decoding.


let players = getPlayers()

// Sort players, with best high scores first
let ranked = players.sorted(by: { player1, player2 in
    player1.highScore > player2.highScore
})

// Create an array with only the players’ names
let rankedNames = ranked.map { $0.name }
// ["Erin", "Rosana", "Tomas"]

Perform powerful custom transformations using streamlined closures.

使用流线型闭包执行强大的自定义转换。

这些前瞻性的概念产生了一种有趣且易于使用的语言。

Swift还有许多其他特性可以使您的代码更具表现力:

功能强大且易于使用的泛型

使编写泛型代码更容易的协议扩展

一类函数和轻量级闭包语法

在一个范围或集合上快速而简洁的迭代

元组和多个返回值

支持方法、扩展和协议的结构

枚举可以具有有效负载并支持模式匹配

函数式编程模式,如map和filter

使用try/catch/throw处理本机错误

These forward-thinking concepts result in a language that is fun and easy to use.

Swift has many other features to make your code more expressive:

Generics that are powerful and simple to use

Protocol extensions that make writing generic code even easier

First class functions and a lightweight closure syntax

Fast and concise iteration over a range or collection

Tuples and multiple return values

Structs that support methods, extensions, and protocols

Enums can have payloads and support pattern matching

Functional programming patterns, e.g., map and filter

Native error handling using try / catch / throw

Designed for Safety

安全性设计

Swift消除了所有类别的不安全代码。变量总是在使用前初始化,检查数组和整数是否溢出,内存是自动管理的,对内存的独占访问可以防止许多编程错误。对语法进行了调整,使定义意图更加容易——例如,简单的三个字符关键字定义变量(var)或常量(let)。Swift在很大程度上利用了值类型,特别是对于数组和字典等常用类型。这意味着,当您复制具有该类型的内容时,您知道它不会在其他地方修改。

另一个安全特性是默认情况下Swift对象不能为零。事实上,Swift编译器将阻止您尝试生成或使用具有编译时错误的nil对象。这使得编写代码更干净、更安全,并防止应用程序中出现大量运行时崩溃。然而,在有些情况下,nil是有效和适当的。对于这些情况,Swift有一个创新的功能,称为optionals。一个可选的可能包含nil,但是Swift语法强制您使用?语法向编译器指示您理解该行为并将安全地处理它。

Swift eliminates entire classes of unsafe code. Variables are always initialized before use, arrays and integers are checked for overflow, memory is automatically managed, and enforcement of exclusive access to memory guards against many programming mistakes. Syntax is tuned to make it easy to define your intent — for example, simple three-character keywords define a variable ( var ) or constant ( let ). And Swift heavily leverages value types, especially for commonly used types like Arrays and Dictionaries. This means that when you make a copy of something with that type, you know it won’t be modified elsewhere.

Another safety feature is that by default Swift objects can never be nil. In fact, the Swift compiler will stop you from trying to make or use a nil object with a compile-time error. This makes writing code much cleaner and safer, and prevents a huge category of runtime crashes in your apps. However, there are cases where nil is valid and appropriate. For these situations Swift has an innovative feature known as optionals. An optional may contain nil, but Swift syntax forces you to safely deal with it using the ? syntax to indicate to the compiler you understand the behavior and will handle it safely.

extension Collection where Element == Player {
    // Returns the highest score of all the players,
    // or `nil` if the collection is empty.
    func highestScoringPlayer() -> Player? {
        return self.max(by: { $0.highScore < $1.highScore })
    }
}

Use optionals when you might have an instance to return from a function, or you might not.

当您可能有一个实例要从函数中返回,或者可能没有实例时,请使用选项。


if let bestPlayer = players.highestScoringPlayer() {
    recordHolder = """
        The record holder is \(bestPlayer.name),\
        with a high score of \(bestPlayer.highScore)!
        """
} else {
    recordHolder = "No games have been played yet.")
}
print(recordHolder)
// The record holder is Erin, with a high score of 271!

let highestScore = players.highestScoringPlayer()?.highScore ?? 0
// highestScore == 271

Features such as optional binding, optional chaining, and nil coalescing let you work safely and efficiently with optional values.

可选绑定、可选链接和nil合并等特性允许您安全高效地使用可选值工作。

Fast and Powerful

快速有力

From its earliest conception, Swift was built to be fast. Using the incredibly high-performance LLVM compiler technology, Swift code is transformed into optimized native code that gets the most out of modern hardware. The syntax and standard library have also been tuned to make the most obvious way to write your code also perform the best whether it runs in the watch on your wrist or across a cluster of servers.

Swift is a successor to both the C and Objective-C languages. It includes low-level primitives such as types, flow control, and operators. It also provides object-oriented features such as classes, protocols, and generics, giving Cocoa and Cocoa Touch developers the performance and power they demand.

从最早的概念开始,Swift就被打造成快速的。使用难以置信的高性能LLVM编译器技术,Swift代码被转换成优化的本机代码,最大限度地利用现代硬件。语法和标准库也经过了调整,使编写代码的最明显的方式也能获得最佳性能,无论是在手腕上的手表上运行还是在服务器集群中运行。

Swift是C语言和Objective-C语言的继承者。它包括低级原语,如类型、流控制和运算符。它还提供了面向对象的特性,如类、协议和泛型,为Cocoa和Cocoa Touch开发人员提供了所需的性能和能力。

Great First Language

伟大的第一语言

Swift可以打开编码世界的大门。事实上,它被设计成任何人的第一种编程语言,无论你是在学校还是在探索新的职业道路。对于教育工作者来说,苹果公司创造了免费课程,在教室内外教授斯威夫特。第一次编码者可以下载Swift Playgrounds,这是一款iPad上的应用程序,它使Swift代码的使用变得交互式和有趣。


Aspiring app developers can access free courses to learn to build their first apps in Xcode. And Apple Stores around the world host Today at Apple Coding & Apps sessions where you can get hands-on experience with Swift code.

有抱负的应用程序开发者可以通过免费课程学习如何在Xcode中构建他们的第一个应用程序。今天,世界各地的苹果商店都将举办苹果编码与应用程序研讨会,在那里你可以亲身体验Swift代码

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言