匹配Swift中对象的数据类型 [英] Match the data type of a object in Swift

查看:122
本文介绍了匹配Swift中对象的数据类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何匹配Swift中对象的数据类型?

How to match the data type of a object in Swift?

赞:

var xyz : Any
    xyz = 1;
    switch xyz
 {
    case let x where xyz as?AnyObject[]:
        println("\(x) is AnyObject Type")
    case let x where xyz as?String[]:
        println("\(x) is String Type")
    case let x where xyz as?Int[]:
        println("\(x) is Int Type")
    case let x where xyz as?Double[]:
        println("\(x) is Double Type")
    case let x where xyz as?Float[]:
        println("\(x) is Float Type")
    default:println("None")
    }

在这种情况下,案例运行默认情况

In this case switch case run default case

推荐答案

var xyz:AnyObject 更改为 var xyz:任何并添加它将与此案例匹配

change var xyz : AnyObject to var xyz : Any and add it will match to this case

case let x as Int:



来自REPL的





from REPL

  1> var a : Any = 1
a: Int = <read memory from 0x7fec8ad8bed0 failed (0 of 8 bytes read)>
  2> switch a { case let x as Int: println("int"); default: println("default"); }
int






来自 Swift编程语言


您可以在switch语句的情况下使用is和as运算符来
发现具体的已知
的常量或变量的类型,只能是Any或AnyObject类型。下面的示例迭代了
items数组中的项目,并使用
switch语句查询每个项目的类型。有几个switch语句将它们的
匹配值绑定到指定类型的常量,以使其值
打印出来:

You can use the is and as operators in a switch statement’s cases to discover the specific type of a constant or variable that is known only to be of type Any or AnyObject. The example below iterates over the items in the things array and queries the type of each item with a switch statement. Several of the switch statement’s cases bind their matched value to a constant of the specified type to enable its value to be printed:



for thing in things {
    switch thing {
    case 0 as Int:
        println("zero as an Int")
    case 0 as Double:
        println("zero as a Double")
    case let someInt as Int:
        println("an integer value of \(someInt)")
    case let someDouble as Double where someDouble > 0:
        println("a positive double value of \(someDouble)")
    case is Double:
        println("some other double value that I don't want to print")
    case let someString as String:
        println("a string value of \"\(someString)\"")
    case let (x, y) as (Double, Double):
        println("an (x, y) point at \(x), \(y)")
    case let movie as Movie:
        println("a movie called '\(movie.name)', dir. \(movie.director)")
    default:
        println("something else")
    }
}

// zero as an Int
// zero as a Double
// an integer value of 42
// a positive double value of 3.14159
// a string value of "hello"
// an (x, y) point at 3.0, 5.0
// a movie called 'Ghostbusters', dir. Ivan Reitman






注:


Note:

var xyz : AnyObject = 1

将为您提供 NSNumber ,因为 Int 不是对象,因此会自动将其转换为 NSNumber 这是对象

will give you NSNumber because Int is not object so it auto convert it to NSNumber which is object

这篇关于匹配Swift中对象的数据类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆