Swift:协议vs.结构vs.类 [英] Swift: Protocol vs. Struct vs. Class

查看:188
本文介绍了Swift:协议vs.结构vs.类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开始学习Swift语言,无法围绕协议,结构和类包装我的头。

I am starting to learn the Swift language and am having trouble wrapping my head around Protocols, Structs and Classes.

我来自Android的编程,所以我相信Swift协议基本上是Java接口?

I come from the Android side of programming, so I believe that Swift Protocols are basically Java Interfaces?

这些都是正确的用例?

推荐答案

这些类比不是完全正确的,但这是它的理解,因为我理解它

These analogies are not "exactly" correct, but this is the gist of it as I understand it


  1. 是,协议实际上类似于接口

  1. Yes, Protocols are effectively like interfaces

类是Java / Android中的类,几乎任何其他语言

Classes are classes, like in Java/Android, and pretty much any other language

结构类似类,但是当它们从一个变量/函数传递到另一个变量时,它们被传递by-value(复制)。
如果你熟悉C#,它的结构的实现非常相似。

Structs are like classes, but they are passed by-value (copied) when passing them from one variable/function to another. If you're familiar with C# at all, it's implementation of structs is very similar.

class Foo {
   ...
}

let x = Foo()
let z = x 

此时x和z在内存中的同一个对象,只有一个 Foo 对象

At this point x and z both refer to the same Object in memory, there is only one Foo object

struct Bar {
   ...
}

let a = Bar()
let b = a 

分配b时,复制a(考虑基本上复制内存块)。此时,在内存中有两个独立的 Bar 对象,并且修改一个不会影响另一个。

When assigning b, a is copied (think of basically copying the memory block). At this point, there are two independent Bar objects in memory and modifying one doesn't affect the other.

为什么这很有用?有时你不想要一个共享引用,但主要是出于性能原因。因为结构体不必都引用同一个对象,所以它们不必在堆上分配。它们通常可以在堆栈上被分配,这更快地被更多地分配。结构体数组可以实现为一个大的连续的内存块,这意味着如果你想遍历所有的CPU缓存,它是非常友好的。

Why is this useful? Sometimes you don't want a shared reference, but mostly for performance reasons. Because structs don't have to all refer to the same object, they don't have to be allocated on the heap. They can instead often be allocated on the stack, which is much faster. Also arrays of structs can be implemented as one big contiguous block of memory which means it's much friendlier on the CPU cache if you want to iterate through it all.

Swift isn' t垃圾收集,但是对于像C#这样的垃圾收集语言,这意味着垃圾收集器不必处理它可能拥有的很多对象。即使在swift中,结构体复制意味着它可以避免为ARC创建后面的 Retain / Release 帮助很多。

Swift isn't garbage collected, but for garbage collected languages like C# this can mean the garbage collector doesn't have to deal with a lot of objects that it might otherwise have to. Even in swift the struct copying means it can avoid doing the Retain/Release behind the scenes neccessary for ARC, which can help a lot.

结构体的主要用例是当你有很多不可变的简单数据,如Vector(一组3个浮点值)

The primary use case for structs is when you have lots of immutable "simple data" like a Vector (set of 3 floating point values)

这篇关于Swift:协议vs.结构vs.类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆