繁体   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