Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
280 views
in Technique[技术] by (71.8m points)

Swift: 'Hashable.hashValue' is deprecated as a protocol requirement;

I've been facing following issue (it's just a warning) with my iOS project.

'Hashable.hashValue' is deprecated as a protocol requirement; conform type 'ActiveType' to 'Hashable' by implementing 'hash(into:)' instead

  • Xcode 10.2
  • Swift 5

Source Code:

public enum ActiveType {
    case mention
    case hashtag
    case url
    case custom(pattern: String)

    var pattern: String {
        switch self {
        case .mention: return RegexParser.mentionPattern
        case .hashtag: return RegexParser.hashtagPattern
        case .url: return RegexParser.urlPattern
        case .custom(let regex): return regex
        }
    }
}

extension ActiveType: Hashable, Equatable {
    public var hashValue: Int {
        switch self {
        case .mention: return -1
        case .hashtag: return -2
        case .url: return -3
        case .custom(let regex): return regex.hashValue
        }
    }
}

enter image description here

Any better solution? The warning itself suggesting me to implement 'hash(into:)' but I don't know, how?

Reference: ActiveLabel

question from:https://stackoverflow.com/questions/55395207/swift-hashable-hashvalue-is-deprecated-as-a-protocol-requirement

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the warning says, now you should implement the hash(into:) function instead.

func hash(into hasher: inout Hasher) {
    switch self {
    case .mention: hasher.combine(-1)
    case .hashtag: hasher.combine(-2)
    case .url: hasher.combine(-3)
    case .custom(let regex): hasher.combine(regex) // assuming regex is a string, that already conforms to hashable
    }
}

TIP: you don't need to make the enum explicitly conforms to Equatable because Hashable extends it.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...