标签:
可选类型/可选链 Make-by-LJW ---转载请注明出处...
let price = p.dog?.toy?.price
p.dog?.toy?.price = 50
if let whyDog = p.dog { if let toy = whyDog.toy { toy.flying() } } // p.dog!.toy!.flying() 直接写法: p.dog?.toy?.flying()
var opa: Optional<Int> var opb: Int? var nora: Int nora = 10 print(nora) print(opb) 输出结果: 10 nil
var opb: Int? opb = 55 if let b = opb{ print(opb!) print(b) } 输出结果: 55 55
class Person { var name: String init(name:String){ self.name = name } func whoami() ->String{ print("my name is \(self.name)") return name } } var p0 : Person? var p1 : Person = Person(name: "ljw") p1.name = "zs" p1.whoami() 输出结果: my name is zs
p0!.name = "ls" p0!.whoami()
if let p = p0{ p.name = "ls" p.whoami() }
p0 = p1 p0?.name = "ls" p0?.whoami()
print(p0?.name) print(p0?.whoami()) print(p1.name) var a:String? = p0?.name p0?.name = "ww" var b:String = p1.name 输出结果: nil nil xmg
struct Student { var name:String = "ljw" var math:Double = 99.0 var chinese:Double = 99.0 var english:Double = 99.0
subscript(course:String) ->Double?{ get{ switch course{ case "math": return math case "chinese": return chinese case "english": return english default: return nil } } set{ switch course{ case "math": 因为返回的是可选类型 math = newValue! case "chinese": chinese = newValue! case "english": english = newValue! default: print("not found") } } } } var stu:Student? = Student() 可选链调用下标索引不需要., 直接在问号后面写上[]即可 print(stu?["math"]) 输出结果:Optional(99.0)
stu?.name = "ww" print(stu?.name) 输出结果:Optional("ww")
stu?["math"] = 88 print(stu?["math"]) 输出结果:Optional(88.0)
let res: Void? = stu?.name = "ljw" print(res) 输出结果:Optional(()) 代表成功.
stu = nil let res: Void? = stu?.name = "zl" print(res) 输出结果:nil 代表失败
class A { var name:String = "ljw" } class B{ var a1:A? } class C{ var b1:B = B() } class D{ var c1: C? } var a1 = A() var b1 = B() var c1 = C() var d1 = D() d1.c1 = c1 通过d直接给b赋值 由于D中的C是可选值, 所以需要在C后面加上? d1.c1?.b1.a1 = a1 通过d直接获取a中的name 其实只需要在可选值后面加上问号即可, 如果可选值不存在, 那么后面的链失效 print(d1.c1?.b1.a1?.name) 输出结果:Optional("ljw")
标签:
原文地址:http://www.cnblogs.com/ljwios/p/5506551.html