swift学习3 数据类型的可选值 optional type

swift学习3 数据类型的可选值 optional type,第1张

概述swift不仅要求类型安全,还尽力保证数据安全,未赋值的变量不允许使用 那么如果一开始不想赋值,就需要可选值定义,在类型后加问号? 输出值为 nil,这里的nil与oc中的有所区别,但基本概念都是空值 但是注意,常量不能用可选值定义 可选值之间可以相互赋值 var optVar1 :Int?print(optVar1)//nilvar optVar2 :Int? = 110print(o

swift不仅要求类型安全,还尽力保证数据安全,未赋值的变量不允许使用

那么如果一开始不想赋值,就需要可选值定义,在类型后加问号?

输出值为 nil,这里的nil与oc中的有所区别,但基本概念都是空值

但是注意,常量不能用可选值定义

可选值之间可以相互赋值

var optvar1 :Int?print(optvar1)//nilvar optvar2 :Int? = 110print(optvar2)//Optional(110)optvar1 = optvar2print(optvar1)//Optional(110)

不同的可选值之间不可以转换类型

var optvar1 :Int?var optvar2 :UInt? = 110optvar1 = Int?(optvar2) //cannot invoke initializer for type 'Int?' with an argument List of type '(UInt?)'

Int?向Int?赋值时,可以强制解析

optvar1 = optvar2!print(optvar1)//Optional(110)

Int?向Int也可以赋值,同样强制解析

var a = optvar2!print(a)//110

Int向Int?赋值,无需解析

optvar2 = a + 1print(optvar2)//Optional(111)

当我想判断optional是否有值并赋值时,可以用判断

if var abc = optvar2 {    print("abc");print(abc)}//abc 111var optvar3 : Int?if var bcd = optvar3 {    print(bcd)//无打印}if optvar2 == nil {    print("nil")}else {    print ("not nil")//not nil}

隐式可选类型,是可选类型的一个补充,用法一样,?换为!

var oprVar4 : Int! = 8var aaaa =  oprVar4print(aaaa)//8

它不需要再强制解析

可选类型要注意安全问题,因为变量不赋值,也可以调用,但是运行时会报错

var oprVar4 : Int?var aaaa =  oprVar4!print(aaaa)//Fatal error: unexpectedly found nil while unwrapPing an Optional value
总结

以上是内存溢出为你收集整理的swift学习3 数据类型的可选值 optional type全部内容,希望文章能够帮你解决swift学习3 数据类型的可选值 optional type所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://www.outofmemory.cn/web/1081798.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-27
下一篇 2022-05-27

发表评论

登录后才能评论

评论列表(0条)

保存