簡體   English   中英

Swift:用於類型檢查的通用函數

[英]Swift: Generic Function for Type Checking

新手問題。 這段代碼有很多復制和粘貼,用於檢查快速類型。 有沒有一種方法可以將其壓縮為某種通用函數? 感謝您的任何幫助。

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
*/

您可以調用dynamicType

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

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

不確定您到底在做什么,但僅使用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

好的,我找到了解決方案,它實際上非常簡單:

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
*/

問題是“類型”參數必須是一個占位符值,例如Int為0,或者如果檢查String則為空字符串,因此這不是最干凈的方法,但是Swift的類型推斷使其非常有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM