swift关键字as,as!,as?

本文介绍了Swift中的类型转换关键字as, as!和as?的用法。as用于可担保转换,as!表示强制转换,可能在运行时失败导致程序崩溃,as?则是可选转换,允许转换失败并返回nil。" 102526774,7918400,PostgreSQL建表与修改表操作详解,"['数据库管理', 'SQL', 'PostgreSQL', '表操作']

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在学习swift开发,其中有许多在其他语言中没见过的东西,比如关键字as。

  override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        
        if segue.identifier == "ResultsSegue" {
            let resultsViewController = segue.destination as! ResultsViewController
            resultsViewController.responses = answerChosen
            
        }
    }

上面这个函数是swift中定义好的,在使用的时候需要去重写这个函数。这里不提这个函数,简单说就是传参的函数。

要想了解这个函数,可看:https://blog.youkuaiyun.com/wufeifan_learner/article/details/89083745


上述几行代码有一个十分有趣的关键字“as”,这个关键字之前没见过,所以在这里总结一下,供自己及他人参考。

 

说as是关键字,其实不准确,具体说这是个操作符。这个操作符的作用是:将派生类转换为基类

import UIKit

//number1是int类型的
var number1 = 1
print(number1)

//这里将int类型的number2转换成了Float类型
var number2 = 1 as Float
print(number2)

//利用强制转换
var number3 = 1
var number4 = (Float)(number3)
print(number3)
print(number4)

苹果官方开发手册中给了一个例子,我改写一下:

class Animal {}
class Dog: Animal {}

let a = Dog()
a as Animal

从子类到父类的转换,这样是可行的。这个转换被官方称为“Guaranteed conversion”。

  • Guaranteed conversion of a value of one type to another, whose success can be verified by the Swift compiler. For example, upcasting (i.e., converting from a class to one of its superclasses) or specifying the type of a literal expression, (e.g., 1 as Float).
  • 一个类型的值可担保转换到另一个类型,这种转换的成功可以由编译器来保证。例如:向上转换(例:从一个类转换到它的父类),或指明一个文本表达(例:将1转换成Float型)

还有一种转换方式,操作符为 as! ,被官方成为强制转换"Forced conversion"

  • Forced conversion of one value to another, whose safety cannot be guaranteed by the Swift compiler and which may cause a runtime trap. For example downcasting, converting from a class to one of its subclasses.
  • 一个值强制转换为另一个值,它的安全性不能被编译器保证,因此它可能造成运行时错误。例如向下转换,将一个类向它的派生类转换。

Swift 1.2 separates the notions of guaranteed conversion and forced conversion into two distinct operators. Guaranteed conversion is still performed with the as operator, but forced conversion now uses the as!operator. The ! is meant to indicate that the conversion may fail. This way, you know at a glance which conversions may cause the program to crash.

Swift 1.2 将可担保转换和强制转换的概念分成了两个独特的操作符。可担保转换仍保留as作为操作符,但是强制转换现在用as! 操作符。! 意味着转换可能失败。这样,你就能一眼知道那个转换可能导致程序崩溃。

class Animal {}
class Dog: Animal {}

let a: Animal = Dog()
a as Dog		// 报错,不能从Animal向Dog进行可担保转换
				// 你想用as! 代替as 么?

a as! Dog		// 强制转换可以通过编译

let d = Dog()
d as Animal		

 


还有一种转换是as?

这里?和swift中其他的?用法类似,就是可选类型,可以让某一对象值为空。

class Animal {}

class Cat: Animal {}

class Dog: Animal {
	var name = "Spot"
}

let dog: Dog? = nil
dog?.name		// 评估为nil
dog!.name		// 引发运行时错误

let animal: Animal = Cat()
animal as? Dog	// 评估为nil
animal as! Dog	// 引发运行时错误

啥意思?

就是说:第一个转换的时候,dog是Dog类型的,并且dog可以为nil,所以后面调用dog类中对象的时候应该用?,若用!则会运行时报错。因为强行调用不能为空。

第二个Animal被定义为Animal类型,并且用Cat对其进行初始化。当让猫类型的animal转换成狗类型,若失败则返回空。而下面的强制转换,若失败就直接报错抛出异常了。


所以我们的程序,segue.destination as! ResultsViewController,就是让segue.destination转换成ResultsViewController类型。而segue.destination是UIViewController的子类,ResultsViewController也是UIViewController的子类。

 

参考文献:苹果官方开发手册

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值