gpt4 book ai didi

swift - 新手 : Parameter that accepts either a String or a Substring (perhaps using StringProtocol)

转载 作者:行者123 更新时间:2023-11-28 12:16:18 25 4
gpt4 key购买 nike

<分区>

我是一名经验丰富的程序员,但我最近才开始学习 Swift(第 4 版)。

我发现很难完成简单的任务,甚至像“给我这个 String 的第 4 个 Character”。

我试着写了这两个简单的函数:

// isHexCharacter returns whether a Character is hexadecimal or not
func isHexCharacter(_ c: Character) -> Bool {
switch c {
case "0", "1", "2", "3", "4", "5", "6", "7",
"8", "9", "A", "B", "C", "D", "E", "F":
return true
default:
return false
}
}

// isHexString returns whether a String (or Substring) consists
// entirely of hexadecimal characters
func isHexString(_ s: StringProtocol) -> Bool {
for c in s {
if !isHexCharacter(c) {
return false
}
}
return true
}

但是编译器咬了我:

demo.swift:20:23: error: protocol 'StringProtocol' can only be used
as a generic constraint because it has Self or associated
type requirements
func isHexString(_ s: StringProtocol) -> Bool {
^
demo.swift:21:14: error: using 'StringProtocol' as a concrete type
conforming to protocol 'Sequence' is not supported
for c in s {
^

我的问题是:

  • 我不理解编译器消息。他们的意思是什么?为什么我不能使用 StringProtocol 作为参数?我错过了什么吗?

  • 我知道可能有标准库函数完全适合我上面的工作,但这只是一个演示。我的意思是知道如何编写适用于 StringSubstring 的更复杂的函数。我怎么能那样做?

非常感谢!

更新时间:2017-09-28 08:05 UTC

按照@martin-r 的建议,现在我将 isHexString 更改为:

func isHexString<S: StringProtocol>(_ s: S) -> Bool {
for c in s {
if !isHexCharacter(c) {
return false
}
}
return true
}

效果很好!

但是,我尝试创建以下代码:

protocol Animal {
func eat()
}

class Cat : Animal {
func eat() {
print("Meow")
}
}

func animalEat(_ a: Animal) {
a.eat()
}

var kitty = Cat()
animalEat(kitty)

我不知道为什么它可以正常工作。为什么 animalEat 函数在没有泛型的情况下也能正常工作?

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