我习惯了制作 iPhone 应用程序,但现在我需要制作 Mac 应用程序。 因此我必须切换到 Cocoa 框架。
有没有类似于 Cocoa 中的 array.index(of: ) 的东西?
iOS 示例:
let string = "Hello.World"
let needle: Character = "."
if let idx = string.characters.index(of: needle) {
let pos = string.characters.distance(from: string.startIndex, to: idx)
print("Found \(needle) at position \(pos)")
}
else {
print("Not found")
}
我遇到问题的实际代码在这里:
func checkBoxTapped(_ sender: NSButton) {
if (sender.state == 1) {
self.selectedReferrals.append(self.referralApplicationList[sender.tag])
}
if (sender.state == 0) {
// Remove
// self.referralApplicationList[sender.tag]
// let foofoo = self.referralApplicationList.indexOf(self.referralApplicationList[sender.tag])
}
}
最佳答案
您的问题与 Cocoa 或 macOS 与 iOS 完全无关。您真正要问的是如何获得 index(of:)
Swift 数组上的函数,答案是数组中的元素需要是 Equatable
。
在您的 iOS 示例中,characters
是 String.CharacterView
的一个实例其中明确有 index(of:)
功能。
在您的 Mac 示例中,您没有提供足够的信息,selectedReferrals
变量大概是 Array
一些Referral
类型;例如[Referral]
。因为有类似的index(of:)
你的Referral
类型需要实现Equatable
协议(protocol)。否则你需要使用类似 index(where:)
的东西找到您想要的。
关于ios - cocoa 指数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47451176/