2017-11-15 11 views
0

私はSQLite.swiftライブラリを使用しています。式<Int>を式<AnyObject>に変換できません

私は辞書がそれらをホストしたいと思います、だから、私は、いくつかのExpression秒を持っている

let idColumn = Expression<Int>("id") 
let nameColumn = Expression<String>("name") 

let columns: [String: Expression<AnyObject>] = [ 
    "id": idColumn, 
    "name": nameColumn 
] 

をしかし、私は、コンパイラのエラーを取得:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<AnyObject>' 

このエラーはなぜですか?なぜIntタイプはAnyObjectにできないのですか?

私はまた、代わりにAnyObjectのいずれか試してみました:

let columns: [String: Expression<Any>] = [ 
     "id" : idColumn, 
     "name": nameColumn 
    ] 

同様のエラーが表示さ:

Cannot convert value of type 'Expression<Int>' to expected dictionary value type 'Expression<Any>' 

私はこのことを理解していない...誰かが私に説明してもらえますか?

+0

「式」と「式」は異なるタイプであり、キャストは制限付きジェネリックタイプでは機能しません。 'idColumn'と' nameColumn'の両方を 'Expression 'と宣言してみませんか? –

+0

私はSQLite.swift(またはSQLite)に関する経験はありませんが、これは['cast(_:)'](https://github.com/stephencelis/SQLite.swift/blob/master/Sources/ SQLite/Typed/Expression.swift#L141)関数はのためのものです。 Generics [一般的なケースでは不変である](https://stackoverflow.com/q/41976844/2976878)。 – Hamish

+1

ジェネリックは一般にパラメータ化された型で共変しないためです。継承/多型は適用されません。 – matt

答えて

0

IntおよびStringのタイプはAnyObjectに変換できます。しかし、一般的な型にラップされている場合は適用されません。Expression<Int>Expression<AnyObject>に変換できません。スウィフトがどのように働くかそれが今日(スウィフト4)です:

以外にも
// OK 
let i: Int = 1 
let i2 = i as AnyObject 

// Error: cannot convert value of type 'S<Int>' to type 'S<AnyObject>' in coercion 
struct S<T> { } 
let s = S<Int>() 
let s2 = s as S<AnyObject> 

、それは、あなたが辞書から抽出します式はその列の型を失ってしまうだろう場合でも:あなたはSQLite.swiftで直接それらを使用することができませんでした、あなたのother questionのように

3

あなたの期待は間違っています。あなたが期待するのは、スウィフト言語の仕組みではありません。

A generic type specialized to a subtype is not polymorphic with respect to the same generic type specialized to a supertype. For example, suppose we have a simple generic struct along with a class and its subclass:

struct Wrapper<T> { 
} 
class Cat { 
} 
class CalicoCat : Cat { 
} 

Then you can’t assign a Wrapper specialized to CalicoCat where a Wrapper specialized to Cat is expected:

let w : Wrapper<Cat> = Wrapper<CalicoCat>() // compile error 

は技術的には、私たちはジェネリックがそのパラメータ化された型に共変されていないことを言う:私はちょうど私が私の本の中で与える例を繰り返します。このルールには例外があります - オプションは明白ですが、言語そのものに焼き付ける必要があります。

関連する問題