Changing a variable to a subclass in Swift

In Swift, if I have a base class and two classes that inherit it, which have their own properties. If I assign a variable to a base class and then change it to a subclass, I cannot access the specified properties. Here is a really stupid example. This is what I could think of. http://swiftstub.com/927736954/?v=gm

class Animal {
    let alive = true
}

class Human:Animal {
    let socks:Int = 5
}

class Dog:Animal {
    let collar = "fun"
}

var a:Animal!

var letter = "h"

switch letter {
    case "d":
        a = Dog()
    case "h":
        a = Human()
    default:
        a = Animal()
}

print(a is Human) // TRUE
print(a.socks) // :28:7: error: 'Animal' does not have a member named 'socks'

How can I first set a variable as a base class and include it in a subclass and access the properties of this subclass?

+4
source share
2 answers

You need to lower the variable. Therefore, print(a.socks)it should be replaced by

if a is Human {
  print((a as! Human).socks)
}

or with an additional variable

if let b = a as? Human {
  print(b.socks)
}

UPD:

guard:

guard let a = a as? Human
  else { return }
print(a.socks)
+5

- .

R.K. . .

, downcast:

var some : Animal?

some = Human() // or some = Dog() or some = Animal()

switch some {
case let human as Human: print("It a human with \(human.socks) socks")
case let dog as Dog: print("It a Dog! The collar says: \(dog.collar)")
default: print("It some unknown kind of animal")
}

, .

+4

Source: https://habr.com/ru/post/1609522/


All Articles