swift Extensions官方文档翻译

Extensions add new functionality to an existing class,structure,enumeration,or protocol type. This includes the ability to extend types for which you do not have access to the original source code (known as retroactive modeling). Extensions are similar to categories in Objective-C. (Unlike Objective-C categories,Swift extensions do not have names.)
Extensions 为现有类添加结构体(structure),枚举(enumeration),协议(protocol),这使你可以在不能访问源码的情况下扩展功能(又称逆向建模)。它和OC中的categories类似,但是它没有名字

Extensions in Swift can:
1.Add computed properties and computed type properties
2.Define instance methods and type methods
3.Provide new initializers
4.Define subscripts
5.Define and use new nested types
6.Make an existing type conform to a protocol
用处:
1.添加计算属性和计算类属性
2.定义实例方法和类方法
3.提供新的构造方法
4.定义subscripts(下标?)
5.定义和使用新的内部类
6.是现有类实现一个协议

In Swift,you can even extend a protocol to provide implementations of its requirements or add additional functionality that conforming types can take advantage of. For more details,see Protocol Extensions.
在swift中,你甚至可以为协议提供扩展功能,这样实现类就可以实现新的需求或者添加额外的方法(Protocol Extensions)。

NOTE
Extensions can add new functionality to a type,but they cannot override existing functionality.
注意
Extensions 可以添加新的方法,但是不可以重写

Extension Syntax(语法)

Declare extensions with the extension keyword:
使用extension 关键字声明Extensions

extension SomeType {
    // new functionality to add to SomeType goes here
}

An extension can extend an existing type to make it adopt one or more protocols. Where this is the case,the protocol names are written in exactly the same way as for a class or structure:
一个Extensions 可以为现有类实现一个或多个协议,这种情况下,写法和类、结构体一样

extension SomeType: SomeProtocol,AnotherProtocol {
    // implementation of protocol requirements goes here
}

Adding protocol conformance in this way is described in Adding Protocol Conformance with an Extension.
这种方式添加协议,可参考 Adding Protocol Conformance with an Extension.

NOTE
If you define an extension to add new functionality to an existing type,the new functionality will be available on all existing instances of that type,even if they were created before the extension was defined.
注意
如果你为现有类添加了一个新的Extensions,包含新的功能,即便是创建该类的对象在定义扩展之前,该对象也有扩展的功能。

Computed Properties(计算属性)

Extensions can add computed instance properties and computed type properties to existing types. This example adds five computed instance properties to Swift’s built-in Double type,to provide basic support for working with distance units:
Extensions可以为现有类添加计算实例属性和计算类属性,这个示例为swift内置的Double类添加了5个计算示例属性,添加了距离单位功能。

extension Double {
    var km: Double { return self * 1_000.0 }
    var m: Double { return self }
    var cm: Double { return self / 100.0 }
    var mm: Double { return self / 1_000.0 }
    var ft: Double { return self / 3.28084 }
}
let oneInch = 25.4.mm
print("One inch is \(oneInch) meters")
// prints "One inch is 0.0254 meters"
let threeFeet = 3.ft
print("Three feet is \(threeFeet) meters")
// prints "Three feet is 0.914399970739201 meters"

These computed properties express that a Double value should be considered as a certain unit of length. Although they are implemented as computed properties,the names of these properties can be appended to a floating-point literal value with dot syntax,as a way to use that literal value to perform distance conversions.
这些计算属性使一个double类型的值作为长度的某个单位,尽管他们作为计算属性,浮点字面值,也可以用点语法,来调用它们,通过这种方式使字面值实现距离转换。

In this example,a Double value of 1.0 is considered to represent “one meter”. This is why the m computed property returns self—the expression 1.m is considered to calculate a Double value of 1.0.
在这个例子中,double类型1.0代表”1米”,这是m计算属性return self的原因—表达式1.m,其实是对double值1.0的计算。

Other units require some conversion to be expressed as a value measured in meters. One kilometer is the same as 1,000 meters,so the km computed property multiplies the value by 1_000.00 to convert into a number expressed in meters. Similarly,there are 3.28084 feet in a meter,and so the ft computed property divides the underlying Double value by 3.28084,to convert it from feet to meters.
其他的距离单位需要一些转换,以单位米为标准,1KM=1000m,所以km计算属性是通过乘以1000,来得到以米为单位的结果。类似的,1m=3.28084ft

These properties are read-only computed properties,and so they are expressed without the get keyword,for brevity. Their return value is of type Double,and can be used within mathematical calculations wherever aDouble is accepted:
这些计算属性都是只读的,为了简洁,所以没有get关键字。返回值是Double类型,只要是double类型,可以在任何地方,使用这些数学计算。

let aMarathon = 42.km + 195.m
print("A marathon is \(aMarathon) meters long")
// prints "A marathon is 42195.0 meters long”

NOTE
Extensions can add new computed properties,but they cannot add stored properties,or add property observers to existing properties.
注意
Extensions 可以添加新的计算属性,但他不可以添加存储属性,或者添加新的属性来监听现有属性

Initializers(构造方法)

Extensions can add new initializers to existing types. This enables you to extend other types to accept your own custom types as initializer parameters,or to provide additional initialization options that were not included as part of the type’s original implementation.
Extensions 可以为现有类添加构造方法,这使你可以新的构造方法传递参数,或者为构造方法提供其他的选项。

Extensions can add new convenience initializers to a class,but they cannot add new designated initializers or deinitializers to a class. Designated initializers and deinitializers must always be provided by the original class implementation.
Extensions可以为一个类添加一个便捷的构造方法,但是不可以添加指定初始化器(designated initializer),指定初始化器只能被初始类实现。

NOTE
If you use an extension to add an initializer to a value type that provides default values for all of its stored properties and does not define any custom initializers,you can call the default initializer and memberwise initializer for that value type from within your extension’s initializer.

This would not be the case if you had written the initializer as part of the value type’s original implementation,as described in Initializer Delegation for Value Types.

注意
如果你为一个值类型添加一个带有初始化器的扩展,以为所有的存数属性提供默认值,并且不定义自定义初始化器,你可以从你的扩展的初始化中调用该值类型的默认的初始化器和成员逐一初始化器。

不包含这种情况,你已经重写了该值类型的初始化器。参考 INITIALIZER DELEGATION FOR VALUE TYPES.

The example below defines a custom Rect structure to represent a geometric rectangle. The example also defines two supporting structures called Size and Point,both of which provide default values of 0.0 for all of their properties:
示例中自定义了一个Rect结构体来描述一个矩形,也同时定义了Size,Point结构体,所有的属性默认值是0.0

struct Size {
    var width = 0.0,height = 0.0
}
struct Point {
    var x = 0.0,y = 0.0
}
struct Rect {
    var origin = Point()
    var size = Size()
}

Because the Rect structure provides default values for all of its properties,it receives a default initializer and a memberwise initializer automatically,as described in Default Initializers. These initializers can be used to create new Rect instances:
因为Rect为其所有的属性提供了默认值,所以它可以自动提供指定初始化器和属性逐一初始化器,参考Default Initializers。可以通过这些初始化器创建一个Rect实例:
let defaultRect = Rect()
let memberwiseRect = Rect(origin: Point(x: 2.0,y: 2.0),
size: Size(width: 5.0,height: 5.0))
You can extend the Rect structure to provide an additional initializer that takes a specific center point and size:
你可以添加一个Extensions 为其添加一个通过center和size创建一个Rect的初始化方法:

extension Rect {
    init(center: Point,size: Size) {
        let originX = center.x - (size.width / 2)
        let originY = center.y - (size.height / 2)
        self.init(origin: Point(x: originX,y: originY),size: size)
    }
}

This new initializer starts by calculating an appropriate origin point based on the provided center point andsize value. The initializer then calls the structure’s automatic memberwise initializer init(origin:size:),which stores the new origin and size values in the appropriate properties:

let centerRect = Rect(center: Point(x: 4.0,y: 4.0),size: Size(width: 3.0,height: 3.0))
// centerRect's origin is (2.5,2.5) and its size is (3.0,3.0)

NOTE
If you provide a new initializer with an extension,you are still responsible for making sure that each instance is fully initialized once the initializer completes.
注意
在扩展的初始化方法中,调用原始初始化方法。

Methods(方法)

Extensions can add new instance methods and type methods to existing types. The following example adds a new instance method called repetitions to the Int type:
Extensions可以为现有类添加实例方法和类方法,实例为Int类添加了一个叫repetitions的实例方法。

extension Int {
    func repetitions(task: () -> Void) { for _ in 0..<self { task() } } }

The repetitions(_:) method takes a single argument of type () -> Void,which indicates a function that has no parameters and does not return a value.
repetitions(_:)只有一个参数() -> Void,并且这个参数(函数/闭包)没有参数和返回值

After defining this extension,you can call the repetitions(_:) method on any integer number to perform a task that many number of times:
在定义了这个Extension之后,任何整数类型(值为3)调用repetitions(_:)都会调用task对应的次数(3次)

3.repetitions({
    print("Hello!")
})
// Hello!
// Hello!
// Hello!

Use trailing closure syntax to make the call more succinct:
使用尾随闭包语法,使其更简洁:

3.repetitions {
    print("Goodbye!")
}
// Goodbye!
// Goodbye!
// Goodbye!

Mutating Instance Methods(用Mutating修饰的实例方法)

Instance methods added with an extension can also modify (or mutate) the instance itself. Structure and enumeration methods that modify self or its properties must mark the instance method as mutating,just like mutating methods from an original implementation.
通过extension添加的实例方法也可以修改实例本身,结构体和枚举的方法必须用mutating来修饰,就像原始实现一样。

The example below adds a new mutating method called square to Swift’s Int type,which squares the original value:
下面的方法得出原始值的平方:

extension Int {
    mutating func square() {
        self = self * self
    }
}
var someInt = 3
someInt.square()
// someInt is now 9

Subscripts(下标/索引)

Extensions can add new subscripts to an existing type. This example adds an integer subscript to Swift’s built-in Int type. This subscript [n] returns the decimal digit n places in from the right of the number:

Extensions可以为现有类添加新的下标语义,实例中是从右边开始:

123456789[0] returns 9
123456789[1] returns 8

…and so on:

extension Int {
    subscript(var digitIndex: Int) -> Int {
        var decimalBase = 1
        while digitIndex > 0 {
            decimalBase *= 10
            --digitIndex
        }
        return (self / decimalBase) % 10
    }
}
746381295[0]
// returns 5
746381295[1]
// returns 9
746381295[2]
// returns 2
746381295[8]
// returns 7

If the Int value does not have enough digits for the requested index,the subscript implementation returns 0,as if the number had been padded with zeros to the left:
如果Int值得位数小于索引值,就会返回0,就像在int值的左边添加了0一样:

746381295[9]
// returns 0,as if you had requested:
0746381295[9]
Nested Types(内部类)

Extensions can add new nested types to existing classes,structures and enumerations:
Extensions可以在类,结构体,枚举中添加添加内部类:

extension Int {
    enum Kind {
        case Negative,Zero,Positive
    }
    var kind: Kind {
        switch self {
        case 0:
            return .Zero
        case let x where x > 0:
            return .Positive
        default:
            return .Negative
        }
    }
}

This example adds a new nested enumeration to Int. This enumeration,called Kind,expresses the kind of number that a particular integer represents. Specifically,it expresses whether the number is negative,zero,or positive.

This example also adds a new computed instance property to Int,called kind,which returns the appropriateKind enumeration case for that integer.

The nested enumeration can now be used with any Int value:

func printIntegerKinds(numbers: [Int]) {
    for number in numbers {
        switch number.kind {
        case .Negative:
            print("- ",terminator: "")
        case .Zero:
            print("0 ",terminator: "")
        case .Positive:
            print("+ ",terminator: "")
        }
    }
    print("")
}
printIntegerKinds([3,19,-27,0,-6,7])
// prints "+ + - 0 - 0 +"

This function,printIntegerKinds,takes an input array of Int values and iterates over those values in turn. For each integer in the array,the function considers the kind computed property for that integer,and prints an appropriate description.

NOTE number.kind is already known to be of type Int.Kind. Because of this,all of the Int.Kind case values can be written in shorthand form inside the switch statement,such as .Negative rather thanInt.Kind.Negative. 注意 简写

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


软件简介:蓝湖辅助工具,减少移动端开发中控件属性的复制和粘贴.待开发的功能:1.支持自动生成约束2.开发设置页面3.做一个浏览器插件,支持不需要下载整个工程,可即时操作当前蓝湖浏览页面4.支持Flutter语言模板生成5.支持更多平台,如Sketch等6.支持用户自定义语言模板
现实生活中,我们听到的声音都是时间连续的,我们称为这种信号叫模拟信号。模拟信号需要进行数字化以后才能在计算机中使用。目前我们在计算机上进行音频播放都需要依赖于音频文件。那么音频文件如何生成的呢?音频文件的生成过程是将声音信息采样、量化和编码产生的数字信号的过程,我们人耳所能听到的声音频率范围为(20Hz~20KHz),因此音频文件格式的最大带宽是20KHZ。根据奈奎斯特的理论,音频文件的采样率一般在40~50KHZ之间。奈奎斯特采样定律,又称香农采样定律。...............
前言最近在B站上看到一个漂亮的仙女姐姐跳舞视频,循环看了亿遍又亿遍,久久不能离开!看着小仙紫姐姐的蹦迪视频,除了一键三连还能做什么?突发奇想,能不能把舞蹈视频转成代码舞呢?说干就干,今天就手把手教大家如何把跳舞视频转成代码舞,跟着仙女姐姐一起蹦起来~视频来源:【紫颜】见过仙女蹦迪吗 【千盏】一、核心功能设计总体来说,我们需要分为以下几步完成:从B站上把小姐姐的视频下载下来对视频进行截取GIF,把截取的GIF通过ASCII Animator进行ASCII字符转换把转换的字符gif根据每
【Android App】实战项目之仿抖音的短视频分享App(附源码和演示视频 超详细必看)
前言这一篇博客应该是我花时间最多的一次了,从2022年1月底至2022年4月底。我已经将这篇博客的内容写为论文,上传至arxiv:https://arxiv.org/pdf/2204.10160.pdf欢迎大家指出我论文中的问题,特别是语法与用词问题在github上,我也上传了完整的项目:https://github.com/Whiffe/Custom-ava-dataset_Custom-Spatio-Temporally-Action-Video-Dataset关于自定义ava数据集,也是后台
因为我既对接过session、cookie,也对接过JWT,今年因为工作需要也对接了gtoken的2个版本,对这方面的理解还算深入。尤其是看到官方文档评论区又小伙伴表示看不懂,所以做了这期视频内容出来:视频在这里:本期内容对应B站的开源视频因为涉及的知识点比较多,视频内容比较长。如果你觉得看视频浪费时间,可以直接阅读源码:goframe v2版本集成gtokengoframe v1版本集成gtokengoframe v2版本集成jwtgoframe v2版本session登录官方调用示例文档jwt和sess
【Android App】实战项目之仿微信的私信和群聊App(附源码和演示视频 超详细必看)
用Android Studio的VideoView组件实现简单的本地视频播放器。本文将讲解如何使用Android视频播放器VideoView组件来播放本地视频和网络视频,实现起来还是比较简单的。VideoView组件的作用与ImageView类似,只是ImageView用于显示图片,VideoView用于播放视频。...
采用MATLAB对正弦信号,语音信号进行生成、采样和内插恢复,利用MATLAB工具箱对混杂噪声的音频信号进行滤波
随着移动互联网、云端存储等技术的快速发展,包含丰富信息的音频数据呈现几何级速率增长。这些海量数据在为人工分析带来困难的同时,也为音频认知、创新学习研究提供了数据基础。在本节中,我们通过构建生成模型来生成音频序列文件,从而进一步加深对序列数据处理问题的了解。
基于yolov5+deepsort+slowfast算法的视频实时行为检测。1. yolov5实现目标检测,确定目标坐标 2. deepsort实现目标跟踪,持续标注目标坐标 3. slowfast实现动作识别,并给出置信率 4. 用框持续框住目标,并将动作类别以及置信度显示在框上
数字电子钟设计本文主要完成数字电子钟的以下功能1、计时功能(24小时)2、秒表功能(一个按键实现开始暂停,另一个按键实现清零功能)3、闹钟功能(设置闹钟以及到时响10秒)4、校时功能5、其他功能(清零、加速、星期、八位数码管显示等)前排提示:前面几篇文章介绍过的内容就不详细介绍了,可以看我专栏的前几篇文章。PS.工程文件放在最后面总体设计本次设计主要是在前一篇文章 数字电子钟基本功能的实现 的基础上改编而成的,主要结构不变,分频器将50MHz分为较低的频率备用;dig_select
1.进入官网下载OBS stdioOpen Broadcaster Software | OBS (obsproject.com)2.下载一个插件,拓展OBS的虚拟摄像头功能链接:OBS 虚拟摄像头插件.zip_免费高速下载|百度网盘-分享无限制 (baidu.com)提取码:6656--来自百度网盘超级会员V1的分享**注意**该插件必须下载但OBS的根目录(应该是自动匹配了的)3.打开OBS,选中虚拟摄像头选择启用在底部添加一段视频录制选择下面,进行录制.
Meta公司在9月29日首次推出一款人工智能系统模型:Make-A-Video,可以从给定的文字提示生成短视频。基于**文本到图像生成技术的最新进展**,该技术旨在实现文本到视频的生成,可以仅用几个单词或几行文本生成异想天开、独一无二的视频,将无限的想象力带入生活
音频信号叠加噪声及滤波一、前言二、信号分析及加噪三、滤波去噪四、总结一、前言之前一直对硬件上的内容比较关注,但是可能是因为硬件方面的东西可能真的是比较杂,而且需要渗透的东西太多了,所以学习进展比较缓慢。因为也很少有单纯的硬件学习研究,总是会伴随着各种理论需要硬件做支撑,所以还是想要慢慢接触理论学习。但是之前总找不到切入点,不知道从哪里开始,就一直拖着。最近稍微接触了一点信号处理,就用这个当作切入点,开始接触理论学习。二、信号分析及加噪信号处理选用了matlab做工具,选了一个最简单的语音信号处理方
腾讯云 TRTC 实时音视频服务体验,从认识 TRTC 到 TRTC 的开发实践,Demo 演示& IM 服务搭建。
音乐音频分类技术能够基于音乐内容为音乐添加类别标签,在音乐资源的高效组织、检索和推荐等相关方面的研究和应用具有重要意义。传统的音乐分类方法大量使用了人工设计的声学特征,特征的设计需要音乐领域的知识,不同分类任务的特征往往并不通用。深度学习的出现给更好地解决音乐分类问题提供了新的思路,本文对基于深度学习的音乐音频分类方法进行了研究。首先将音乐的音频信号转换成声谱作为统一表示,避免了手工选取特征存在的问题,然后基于一维卷积构建了一种音乐分类模型。
C++知识精讲16 | 井字棋游戏(配资源+视频)【赋源码,双人对战】
本文主要讲解如何在Java中,使用FFmpeg进行视频的帧读取,并最终合并成Gif动态图。
在本篇博文中,我们谈及了 Swift 中 some、any 关键字以及主关联类型(primary associated types)的前世今生,并由浅及深用简明的示例向大家讲解了它们之间的奥秘玄机。