初始化的目的是什么!初始化失败? [英] What is the purpose of the init! failable initializer?

查看:305
本文介绍了初始化的目的是什么!初始化失败?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Apple Swift编程语言指南提到了init的存在!初始化程序,但未提供任何示例. (在此页面 中搜索)

The Apple Swift Programming Language guide mentions the existence of the init! initializer, but does not provide any example for it. (Search for init! in this page)

我了解使用init声明的普通故障初始化程序的用法,但是我无法获得该版本的需求.它需要什么?有人可以举个例子吗?

I understand the use of a normal failable initializer declared with init?, but I fail to get the need of this other version. What is it needed for? Can somebody provide an example?

推荐答案

这有两个目的:

  • 在导入Swift不知道的Cocoa API时.如果Swift不知道初始化器是否可以返回nil,它将使用!对其进行注释.这样开发人员便知道其中可能隐藏着零,而不必强迫开发人员在实际上没有理由的情况下测试零.

  • When importing Cocoa APIs that Swift doesn't know about. If Swift does not know if an initializer can return nil or not, it annotates it with ! so that the developer knows there might be a nil hiding there, without forcing the dev to test for nil if there's actually no reason to.

出于相同的原因,在其他情况下也使用了隐式展开的可选(在某些情况下,您可能愿意为了更方便地而使用编译时安全性).

For the same reasons implicitly-unwrapped optionals are used in other contexts (you may be willing to trade compile-time safety for added convenience in some cases).

这篇关于初始化的目的是什么!初始化失败?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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