2016-01-03 61 views
0

noob問題。此代碼有很多複製&粘貼用於檢查swift類型。有沒有辦法將它凝聚成某種通用函數?感謝您提前提供任何幫助。Swift:類型檢查的通用函數

import Foundation 


let x: AnyObject = 42 


if x is Int { 
    print("x is Int") 
}else { 
    print("x is NOT Int") 
} 

if x is Double { 
    print("x is Double") 
}else { 
    print("x is NOT Double") 
} 

if x is Float { 
    print("x is Float") 
}else { 
    print("x is NOT Float") 
} 

if x is String { 
    print("x is String") 
}else { 
    print("x is NOT String") 
} 

/* 
prints: 
x is Int 
x is Double 
x is Float 
x is NOT String 
*/ 
+0

我想我忘了澄清,理想的功能應該能夠採取未知類型的值,那麼一個「類型」,並檢查值的類型和返回的虛假事實。所以基本上(價值,類型) - >布爾。 – user3399723

+0

這正是'是'所做的。爲什麼你想要一個功能呢? – jtbandes

+0

是的,但由於有很多重複的代碼,我想測試更多的類型,而不僅僅是列出的四個。 – user3399723

回答

2

你可以叫dynamicType

print("x is \(x.dynamicType)") 

在你的情況,因爲你明確指定x是一個對象(AnyObject)它是由編譯器轉換爲NSNumber。從技術上講,它既不是Int,也不是Double,也不是Float

+0

我認爲,他還需要「其他」部分,但不幸的是,在那種情況下,沒有「捷徑」存在。通常.dynamicType也應該使用值類型。 struct S {};讓x:Any = S(); print(「x is \(x.dynamicType)」)。答案中的最後一句應該是BOLD! – user3441734

0

不知道你正在做的究竟是什麼,但只是用is本身就應該工作。

let x: AnyObject = 42 

x is Int  // returns true 
x is Double // returns true 
x is Float // returns true 
x is String // returns false 

但是,如果您確實需要某個功能出於某種其他原因,那麼它的工作原理完全相同。

import Foundation 

func checkType(value: AnyObject, type: AnyObject) -> Bool { 
    if type is Int { 
     if value is Int { 
      return true 
     } else { 
      return false 
     } 
    } else if type is Double { 
     if value is Double { 
      return true 
     } else { 
      return false 
     } 
    } else if type is Float { 
     if value is Float { 
      return true 
     } else { 
      return false 
     } 
    } else if type is String { 
     if value is String { 
      return true 
     } else { 
      return false 
     } 
    } 
    return false 
} 

let myVar: AnyObject = 42 

checkType(myVar, Int())  // returns true 
checkType(myVar, Double())  // returns true 
checkType(myVar, Float())  // returns true 
checkType(myVar, String())  // returns false 
0

確定我找到了解決辦法,這其實很簡單:

let x = 42 

func checkTypeOf<Value, Type> (value: Value, type: Type) { 
    if value is Type { 
     print("value is \(type.dynamicType)") 
    }else { 
     print("value is NOT \(type.dynamicType)") 
    } 
} 

checkTypeOf(x, type: 0) 
checkTypeOf(x, type: "") 

/* 
prints: 
value is Int 
value is NOT String 
*/ 

的東西是「類型」參數必須是一個佔位符值,例如0的詮釋,或一個空字符串如果檢查字符串,所以它不是最乾淨的方式,但Swift的類型推斷使它非常有用。