// Optional chaining
/*
class Person{
var residence:Residence?
}
class Residence{
var addr="Default place if you are low rank"
}
var ppl=Person()
//print(ppl.residence?.addr)
//var someaddr = ppl.residence?.addr // here someaddr is String?
//print(ppl.residence)
ppl.residence=Residence()
/* Unexpected error if you add ! in above
// ppl.residence!=Residence()
it is because if you declare it as a unwrapped value, you can't put ?
in later use
*/
var anotheraddr = ppl.residence?.addr // here anotheraddr is String
if let place = ppl.residence?.addr{
print("good you are high rank")
}else{
print("you are low rank")
}
// below model for multi level optional chaining
class Room{
var name:String
init(name:String){
self.name=name
}
}
class Address{
var room:Room?
var building:String?
var street:String?
func getAddress()->String?{
if room != nil && building != nil && street != nil {
return "\(room?.name) . \(building) . \(street)"
}else if building != nil {
return "\(building)"
}else{
return nil
}
}
}
class Apartments{
var room=[Room]()
// var room:Room?
// if you put this, below numberOfRooms will have to place a default value
//you don't have to init or default it because it already inited[Room]()
var numberOfRooms:Int{
return room.count
}
subscript(i:Int)->Room{
// room is non optional type, so you can't put ? here
get{
return room[i]
}
set{
room[i] = newValue
}
}
}
class Renter{
var liveplace:Apartments?
}
/*
End of Modeling
*/
class A{
var b:[Room]?
subscript(i:Int)->Room?{
get{
return b?[i]
}
set{
b?[i] = (newValue)!
}
}
}
*/
class C{
var b:[String]?
subscript(i:Int)->String?{
get{
return b?[i]
}
set{
b?[i] = newValue!//
/* you can't remove "!" behind newValue, otherwise below error:
error: cannot assign value of type 'String?' to type 'String'
b?[i] = newValue//
Quote sente nce from SWIFT official guide:
"The type of newValue is the same as the return value of the subscript"
*/
}
}
}
var someString:String?
var someOtherString:String?
func test(x:String?){
someString=x!
}
/*
var c = C()
var e = C()
var d = c[0]
print(d)
*/
var foo: [String]?=["foo"]
let optStr:String? = "bar"
let nonOptStr = "bar"
foo?[0] = nonOptStr
var a = -3
class C{
var a:[String]?
subscript (i:Int)->String?{
get{
if a?.indices.contains(i) ?? false {
return a?[i]
}
return nil
}
set{
if a?.indices.contains(i) ?? false, let newValue = newValue{
a?[i] = newValue
}
}
}
}