问题描述
在ObjectiveC中我们创建对象,如
In ObjectiveC we create objects like
-(instancetype)init()
{
return [super init]; // Here it returns initialised value
}
Class *obj = [[Class alloc]init]
但swift初始化器不会返回任何值。
But swift initialiser wont return any value.
init()
{
super.init()
}
let obj = Class()
现在swift初始化器如何将实例返回到变量 obj
?。
Now how swift initialiser returns the instance to variable obj
?.
如何在swift中发生 分配和初始化 ?
How the allocation and initialisation occurs in swift?
推荐答案
这只是一个惯例。 Swift初始化器设置一个有效的实例,理论上无法返回任何其他有效实例,因此明确返回没有任何意义。
It's just a convention. Swift initialiser sets up a valid instance and could not theoretically return anything other that a valid instance, so there's no point in explicit return.
所以(从我的观点来看)分配&初始化序列如下所示:
So (from my point of view) allocation & initialisation sequence looks like this:
- 运行时分配所请求类的实例
- 使用 self 设置为已分配的实例
- 初始化程序执行设置
- 运行时将初始化的实例返回给客户端代码
- Runtime allocates instance of requested class
- Initializer is called with
self
set to allocated instance - Initializer performs setup
- Runtime returns initialised instance to client code
虽然这种做法打破了一些有用的Objective-C模式,比如初始化者返回 nil
错误,实例化总是成功的保证允许编译器执行一些优化。同样没有丢弃初始化者返回 nil
,实际上不可能从语言中删除 nil
,如果初始化者是返回期权。
Although this approach breaks some useful Objective-C patterns like initialisers returning nil
on error, the guarantee that instantiation always succeeds allows compiler to perform some optimisations. Also without dropping initialisers returning nil
it would be impossible to actually remove nil
from language, it would seem weird if initialisers were returning optionals.
这篇关于Swift vs ObjC初始化过程?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!