LoginSignup
38
21

More than 5 years have passed since last update.

iOS 12のSDKから`hashValue`の値が変わりました

Posted at

iOS 12のSDKからhashValueの値が変わりました

Xcode 10で利用されるiOS 12のSDKでビルドしたアプリのhashValueの値が、Xcode 10より前にビルドした時の値と異なる値になっているようです。

Xcode 9.4.1

Int

自身の値がhashValueの値。

例: 5.hashValue なら 5

Bool

true なら 1false なら 0

Enum

caseの順番がhashValueの値。

enum Foo {
    case 🐶
    case 🐱
    case 🐭
}

print(Foo.🐱.hashValue) // 1

Xcode 10

Int

自身の値とは異なる値。

例: 5.hashValue は、-1168890137408403414 など。 (実行のたびに変わるようです)

Bool

Intと同様。

Enum

Intと同様。

対応方法

本来の使い方で hashValue を利用している場合は影響を受けないとは思いますが、誤った使用方法をしている場合は対応が必要です。

Int

.hashValueを削除する。

例: 5.hashValue なら 5

Bool

三項演算子で書き換える。

let flag = true

// Before
let value = flag.hashValue

// After
let value = flag ? 1 : 0

Enum

RawValueIntを指定する。

// Before
enum Foo {
    case 🐶
    case 🐱
    case 🐭
}

print(Foo.🐱.hashValue) // 1

// After
enum Foo: Int {
    case 🐶
    case 🐱
    case 🐭
}

print(Foo.🐱.rawValue) // 1

既にRawValueに別の型が使用されていたり、Associated Valueを利用している場合は、computed propertyInt を返すプロパティを追加すると対応が簡単です。

enum Foo {
    case 🐶(name: String)
    case 🐱(name: String)
    case 🐭(name: String)

    var index: Int {
        switch self {
        case .🐶: return 0
        case .🐱: return 1
        case .🐭: return 2
    }
}

まとめ

Xcode 10でアプリをビルドする際は一度、.hashValueで検索をかけて、誤った使い方をしている部分がないかチェックをし、もしあった場合は上記のような対応をすると良いと思います。

38
21
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
38
21