簡體   English   中英

Swift中以泛型數組作為參數的函數

[英]Function with Array of Generics as Parameter in Swift

我想做一個將泛型數組作為參數的泛型函數。 我有兩個類Animal和Bird以及兩個協議Animals&Birds,並且我的方法參數符合這兩個協議,但是我無法添加到數組中。

protocol Birds {
    var canFly: Bool {get set}
}

protocol Animals {
    var name: String {get set}
    var legs: Int {get set}
}

class Animal: Animals {
    var name: String
    var legs: Int

    init(name: String, legs: Int) {
        self.name = name
        self.legs = legs
    }
}

class Bird: Birds {
    var canFly: Bool
    init(canFly: Bool) {
        self.canFly = canFly
    }
}

func myTestGenericMethod<T>(array: [T]) where T: Animals & Birds {
    for (index, _) in array.enumerated() {
        print("At last i am able to get both Animal and Bird")
    }
}

let cat = Animal(name: "cat", legs: 4)
let dog = Animal(name: "dog", legs: 4)
let crow = Bird(canFly: true)
myTestGenericMethod(array: [dog])

myTestGenericMethod(array: [cat, dog]) // Not Able to add this to array

當您where T: Animals & Birdswhere T: Animals & Birds ,必須從Animals Birds擴展T

但是catdog是不是來自延長Animals Birds 所以這是問題。

據我了解,您希望T必須從Animals Birds擴展。 要做到這一點,我們必須有一個擴展了AnimalsBirds的基本協議。 更改一些代碼並修復它。

@objc protocol Base {
}

protocol Birds : Base {
  var canFly: Bool {get set}
}

protocol Animals : Base {
  var name: String {get set}
  var legs: Int {get set}
}

class Animal: Animals {
  var name: String
  var legs: Int

  init(name: String, legs: Int) {
    self.name = name
    self.legs = legs
  }
}

class Bird: Birds {
    var canFly: Bool
    init(canFly: Bool) {
      self.canFly = canFly
    }
  }

func myTestGenericMethod<T: Base>(array: [T]) {
  for object in array {
    if object is Bird {
      let bird = object as! Bird
      print(bird.canFly)
    } else if object is Animal {
      let animal = object as! Animal
      print(animal.name)
    }
  }
}

let cat = Animal(name: "cat", legs: 4)
let dog = Animal(name: "dog", legs: 4)
let crow = Bird(canFly: true)
myTestGenericMethod(array: [crow, cat, dog] as! [Base])
myTestGenericMethod(array: [cat, dog])

在您的代碼中where T: Animals & Birds意味着您需要T為同時符合兩種協議的實例。 但是您沒有符合這兩種協議的類。 如果創建一個實例,則可以在通用方法中使用其實例。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM