余晖落尽暮晚霞,黄昏迟暮远山寻
本站
当前位置:网站首页 > 编程知识 > 正文

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

xiyangw 2022-12-03 12:54 24 浏览 0 评论

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代码

相关推荐

前后端分离 Vue + NodeJS(Koa) + MongoDB实践

作者:前端藏经阁转发链接:https://www.yuque.com/xwifrr/gr8qaw/vr51p4写在前面闲来无事,试了一下Koa,第一次搞感觉还不错,这个项目比较基础但还是比较完整了,...

MongoDB 集群如何工作?

一、什么是“MongoDB”?“MongoDB”是一个开源文档数据库,也是领先的“NoSQL”数据库,分别用“C++”“编程语言”编写,使用带有“Schema”的各种类似JSON的文档,是也分别被认为...

三部搭建mongo,和mongo UI界面

三步搭建mongo,和mongoUI界面安装首先你需要先有一个docker的环境检查你的到docker版本docker--versionDockerversion18.03.1-ce,b...

Mongodb 高可用落地方案

此落地方案,用于实现高可用。复制集这里部署相关的复制集,用于实现MongoDB的高可用。介绍MongoDB复制集用于提供相关的数据副本,当发生硬件或者服务中断的时候,将会从副本中恢复数据,并进行自动...

一次线上事故,我顿悟了MongoDB的精髓

大家好,我是哪吒,最近项目在使用MongoDB作为图片和文档的存储数据库,为啥不直接存MySQL里,还要搭个MongoDB集群,麻不麻烦?让我们一起,一探究竟,继续学习MongoDB分片的理论与实践,...

IDEA中安装MongoDB插件-再也无要nosql manager for mongodb

大家都知道MongoDB数据库作为典型的非关系型数据库被广泛使用,但基于MongoDB的可视化管理工具-nosqlmanagerformongodb也被用的较多,但此软件收费,所以国内的破解一般...

数据库监控软件Lepus安装部署详解

Lepus安装部署一、软件介绍Lepus是一套开源的数据库监控平台,目前已经支持MySQL、Oracle、SQLServer、MongoDB、Redis等数据库的基本监控和告警(MySQL已经支持复...

YAPI:从0搭建API文档管理工具

背景最近在找一款API文档管理工具,之前有用过Swagger、APIManager、Confluence,现在用的还是Confluence。我个人一直不喜欢用Swagger,感觉“代码即文档”,让代...

Mac安装使用MongoDB

下载MongoDB包:https://www.mongodb.com/download-center解压mongodb包手动解压到/usr/local/mongodb文件夹配置Mac环境变量打开环境...

保证数据安全,不可不知道的MongoDB备份与恢复

大家在项目中如果使用MongoDB作为NOsql数据库进行存储,那一定涉及到数据的备份与恢复,下面给大家介绍下:MongoDB数据备份方法在MongoDB中我们使用mongodump命令来备...

MongoDB数据备份、还原脚本和定时任务脚本

备注:mongodump和mongorestore命令需要在MongoDB的安装目录bin下备份脚本备份格式/usr/local/mongodb/bin/mongodump -h ...

等保2.0测评:mongoDB数据库

一、MongoDB介绍MongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之间的产...

MongoDB入门实操《一》

什么是MongoDBMongoDB是一个基于分布式文件存储的数据库。由C++语言编写。旨在为WEB应用提供可扩展的高性能数据存储解决方案。MongoDB是一个介于关系数据库和非关系数据库之...

Python安装PyMongo的方法详细介绍

欢迎点击右上角关注小编,除了分享技术文章之外还有很多福利,私信学习资料可以领取包括不限于Python实战演练、PDF电子文档、面试集锦、学习资料等。前言本文主要给大家介绍的是关于安装PyMongo的...

第四篇:linux系统中mongodb的配置

建议使用普通用户进行以下操作。1、切换到普通用户odysee。2、准备mongodb安装包,自行去官网下载。3、解压安装包并重命名为mongodb4.04、配置mongodbcdmongod...

取消回复欢迎 发表评论: