【问题标题】:Match the data type of a object in Swift在 Swift 中匹配对象的数据类型
【发布时间】:2014-08-18 02:37:30
【问题描述】:

如何在 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")
    }

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

【问题讨论】:

标签: ios swift types


【解决方案1】:

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

case let x as Int:

来自 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

来自The Swift Programming Language

您可以在 switch 语句的 case 中使用 is 和 as 运算符来 发现已知的常量或变量的特定类型 只能是 Any 或 AnyObject 类型。下面的示例迭代 things 数组中的项目,并使用 a 查询每个项目的类型 切换语句。一些 switch 语句的 case 绑定了它们的 将值匹配到指定类型的常量以启用其值 待打印:

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

注意:

var xyz : AnyObject = 1

会给你NSNumber 因为Int 不是对象,所以它会自动将它转换为NSNumber 这是对象

【讨论】:

  • 更改 var xyz : AnyObject 为 var xyz : Any 不起作用 @BryanChen
  • 它再次运行默认@BryanChen
  • 感谢 Bryan Chen,您在回复部分的代码有效 -> switch a { case let x as Int: println("int");默认值:println("default"); }
  • @Bryan Chen NSDate 呢?
  • @LeeWhitney case let date as NSDate:
【解决方案2】:

提出一个有趣的“case is”用法,即“case is Int, is String”,"," 行为类似于 OR 运算符。

switch value{
case is Int, is String:
    if value is Int{
        print("Integer::\(value)")
    }else{
        print("String::\(value)")
    }
default:
    print("\(value)")
}

Similar Post with demo link

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-23
    • 1970-01-01
    • 2021-07-30
    • 1970-01-01
    • 2020-01-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多