swift optionals - 1

学习是个循序渐进的过程,万事开头难. Swift说起来简单易上手,但有一些知识要反复琢磨,多加练习,才会深入理解。

Need to practise a lot and test what is Optiontal Type and how to use it very well

Optional 介绍: 

An optional value either contains a value or contains nil (no value) to indicate that a value is missing. Write a question mark (?) after the type of a value to mark the value as optional.

If a var or constant could be a nil, the var must be declared as optional

Optional is an enumeration

Optional 例子:

1. pNumber is a string constant

2. when cast it to a Int, it might be a Int or nil since some strings can not be casted, liked "good"

3. Optional binding statement is if let a = b {}

If you are sure the optional does contain a value, it can be accessed by pNumber! (Implicitly optional)

Sample code:

let pNumber = "123"

//let converterNumber = Int(possibleNumber!)

if let actualNumber = Int(pNumber) { //casting and force it to a constant. A constan

    print("\'\(pNumber)\' has an integer valuel of \(actualNumber)")

} else {

    print("\'\(pNumber)\' could not be converted to an integer")

}

转载于:https://www.cnblogs.com/iyoubo/p/4609319.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值