gpt4 book ai didi

Swift 通用问题

转载 作者:可可西里 更新时间:2023-11-01 01:36:30 24 4
gpt4 key购买 nike

我正在关注AppleGeneric 教程https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Generics.html .

但是在教程的最后。我遇到了一些问题:

var myStack = Stack<String>()
myStack.push("a")
myStack.push("b")
myStack.push("c")

var arrayOfStrings = ["a", "b", "c"]

if allItemsMatch(myStack, arrayOfStrings) {
print("All items match.")
} else {
print("Not all items match.")
}

if allItemsMatch(myStack, arrayOfStrings) 这行,它说:

Cannot invoke 'allItemsMatch' with an argument list of type '(Stack< String>, [String])'

这是我的代码:

import UIKit

struct Stack<Element> {
var items = [Element]()
mutating func push(item: Element) {
items.append(item)
}
mutating func pop() -> Element {
return items.removeLast()
}
}

extension Stack {
var topItem: Element? {
return items.isEmpty ? nil : items[items.count - 1]
}
mutating func append(item: Element) {
self.push(item)
}
var count: Int {
return items.count
}
subscript(i: Int) -> Element {
return items[i]
}
}


func findIndex<T: Equatable>(array: [T], _ valueToFind: T) -> Int? {
for (index, value) in array.enumerate() {
if value == valueToFind {
return index
}
}
return nil
}

let doubleIndex = findIndex([3.14159, 0.1, 0.25], 9.3)
let stringIndex = findIndex(["Mike", "Malcolm", "Andrea"], "Andrea")

protocol Container {
associatedtype ItemType
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}

extension Array: Container {}

func allItemsMatch< C1: Container, C2: Container where C1.ItemType == C2.ItemType, C1.ItemType: Equatable> (someContainer: C1, _ anotherContainer: C2) -> Bool {
if someContainer.count != anotherContainer.count {
return false
}
for i in 0..<someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
return true

}

var myStack = Stack<String>()
myStack.push("a")
myStack.push("b")
myStack.push("c")

var arrayOfStrings = ["a", "b", "c"]

if allItemsMatch(myStack, arrayOfStrings) {
print("All items match.")
} else {
print("Not all items match.")
}

我是不是漏了什么地方?

最佳答案

您永远不会明确符合您的 Stack<Element>结构到你的 Container协议(protocol)。因此,Swift 严格的类型安全将阻止您将它传递给期望符合 Container 的参数。协议(protocol)(即使它隐含地符合)。

您可以明确符合您的 StackContainer通过扩展。例如:

extension Stack:Container {}

关于Swift 通用问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36887091/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com