1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

AnyとAnyObjectについて

Last updated at Posted at 2024-01-14

Any型

Any型の変数や定数にはどんな型の値も代入することができる。

異なる型のデータが混在する可能性があり、配列に数値(Int型)が存在するか確認する。

コード例
var mixedArray: [Any] = [1, "soccer",2,3, "baseball",4]

for element in mixedArray {
    if let number = element as? Int {
        print("数値:\(number)")
    } else {
        print("数値ではありません。")
    }
}

AnyObject

AnyObjectは全てのクラス型のインスタンスを表すことができる。

Animalクラス、Dogクラス、Catクラスのインスタンスを同じ変数に格納できる。

コード例
class Animal {
    var name: String
    
    init(name: String) {
        self.name = name
    }
    
    func makeSound() {
        print("Animal sound")
    }
}
//Animalを継承
class Dog: Animal {
    override func makeSound() {
        print("Woof!")
    }
}
//Animalを継承
class Cat: Animal {
    override func makeSound() {
        print("Meow!")
    }
}

// AnyObject型の変数に異なるクラスのインスタンスを代入できる
var anyObjectInstance: AnyObject

// Animalクラスのインスタンスを代入
anyObjectInstance = Animal(name: "Generic Animal")
anyObjectInstance.makeSound()  // Animal sound

// Dogクラスのインスタンスを代入
anyObjectInstance = Dog(name: "Buddy")
anyObjectInstance.makeSound()  // Woof!

// Catクラスのインスタンスを代入
anyObjectInstance = Cat(name: "Whiskers")
anyObjectInstance.makeSound()  // Meow!

Class-only Protocolは": class"じゃなくて": AnyObject"で宣言らしい

Class-only Protocolとは。。

1
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?