在Swift强制进行非法的类型转换

时间:2015-05-15 21:20:13

标签: objective-c swift

我的Objective-C应用程序中存在一个失败案例,其中(NSDate *)指向CFString并在调用日期方法时崩溃。

我在Swift中编写单元测试来模拟这种情况,但由于Swift的类型安全性,这似乎是不可能的。我现在已经编写了一个Objective-C工厂类来创建乱搞对象,但我想知道是否有人知道在Swift中强制非法类型转换的方法。就像在运行时不会失败的版本一样:

Sub Main()
    Dim ItemsList As New List(Of Item2)
    ItemsList.Add(New Item2 With {.Name = "Toy Truck", .Barcode = 12345689, .Price = "10.00", .Quinety = 100})
    ItemsList.Add(New Item2 With {.Name = "Bicycle", .Barcode = 98754152, .Price = "100.00", .Quinety = 50})

    Dim foundItem = ItemsList.Find(Function(i) i.Barcode = 12345689)
    If Not foundItem Is Nothing Then
        Console.WriteLine(foundItem.Name)
    Else
        Console.WriteLine("Item not found")
    End If

    foundItem = ItemsList.Find(Function(i) i.Barcode = 1111)
    If Not foundItem Is Nothing Then
        Console.WriteLine(foundItem.Name)
    Else
        Console.WriteLine("Item not found")
    End If

    Console.ReadLine()
End Sub

Public Class Item2
    Public Property Name As String
    Public Property Barcode As Integer
    Public Property Price As Double
    Public Property Quinety As Integer
End Class

2 个答案:

答案 0 :(得分:5)

as!将始终执行运行时检查,unsafeDowncast()将在调试版本中执行运行时检查(但不是发布版本)。

要始终跳过运行时检查,请使用unsafeBitCast()

let myString : NSString = "Hello"
let myDate : NSDate = unsafeBitCast(myString, NSDate.self)

NSLog("%@", myDate) // "Hello"

答案 1 :(得分:2)

转换为AnyObject,现在您可以转到任何您喜欢的课程。

let s = "howdy"
let id = s as AnyObject
let crash = id as! NSDate