2017-11-08 13 views
0

時々知っている人がいますので、複数の変数型を格納できる変数を定義することができれば、とても便利できれいです。この操作 は、タイプ名の代わりに「Any」を使用すると簡単に可能です。例えば :最初の二つのもので複数の特定のカスタムタイプで変数を定義する方法はありますか? (Swiftで)

var a : Any  // defines a variable with ability to store all types except a nil 
var b : Any? // defines a variable with ability to store all types including nil 
var c : String // a variable storing only and only a String value 
var d : String? // a variable such as "c" , but also includes nil too 

我々はすべて{等のInt、文字列、フロート&}を格納することができます。 3番目と4番目のものでも、 "Int"や "Float"などの他のものを保存することはできませんが、String値を格納できます。 しかし、場合によってはカスタムタイプを格納できる変数が必要な場合はどうなりますか?たとえば、 "Int"値を格納できる変数が必要で、 "String"を格納できますが、 "Float"を格納できません。

var e : only(String and Int) 
// some code like above, or even below : 
var f : Any but not Float 

ありますか?解決策はありますか?

thanks dudes 

答えて

0

は思えます。

ような何か:この場合

protocol CustomType { 
    // your definitions ... 
} 

extension String: CustomType {} 
extension Int: CustomType {} 

let customType1: CustomType = "string" 
print(customType1) 
let customType2: CustomType = 0 
print(customType2) 

// Error: Value of type 'Double' does not conform to specified type 'CustomType' 
// let customType3: CustomType = 0.0 

CustomType型の値のみ(なぜならプロトコル適合)StringIntタイプを受け入れます。

0

現在、この機能を実現する方法はありません。しかし、私の意見では、より良い方法は、Anyタイプを使用し、値を希望のタイプにキャストするときにguardまたはif letを使用することです。そのような例を以下に見ることができます:あなたはprotocolsを使用する必要があるよう

let a: Any //e.g. you only want to store Int and String in this variable 
if let _ = a as? Int { 
    //a is of type Int 
} else if let _ = a as? String { 
    //a is of type String 
} 
+0

もちろん、他の解決策として、望ましくない値に設定されている場合は強制的にクラッシュさせる方法もあります。それでも私たちが望んでいた方法ではありません。私はまだ迅速なような言葉でそれをする方法がないとは思わない! – Arman

関連する問題