简体   繁体   中英

Swift: Generic Function for Type Checking

noob question. This code has a lot of copy & paste for checking swift types. Is there a way to condense it into one generic function of some kind? Thanks for any help in advance.

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

You can call dynamicType :

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

In your case, since you explicit specified that x is an object ( AnyObject ) it is converted to NSNumber by the compiler. Technically, it's neither Int , nor Double , nor Float .

not sure what you're doing exactly, but just using is alone should work.

let x: AnyObject = 42

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

but if you actually need a function for some other reason, then this works the exact same.

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

ok I found the solution, it's actually quite simple:

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

the thing is the "type" parameter needs to be a placeholder value, for example 0 for Int, or an empty string if checking String, so it's not the cleanest way to do it, but Swift's type inference makes it quite usable.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM