gpt4 book ai didi

swift - Xcode 8 测试版 6 : AnyObject replaced by Any: where is classForCoder?

转载 作者:搜寻专家 更新时间:2023-10-30 22:30:44 24 4
gpt4 key购买 nike

Xcode 8 beta 6 已将 AnyObject 替换为 Any

在某些情况下,出于调试原因,我使用 a.classForCoder 来查看其中的内容。使用 AnyObject 这行得通。使用 Any 这不再有效。

现在我必须使用 Any:查看 Any 类型变量中的类型的首选方法是什么?

转换为 AnyObject 似乎不是很有用,因为在许多情况下这是一个 StringString 不会确认 AnyObject 自 Xcode 8 beta 6 以来不再存在。

最佳答案

使用类型(of:)

您可以使用type(of:) 找出Any 类型的变量中的变量类型。

let a: Any = "hello"
print(type(of: a)) // String

let b: Any = 3.14
print(type(of: b)) // Double

import Foundation
let c: Any = "hello" as NSString
print(type(of: c)) // __NSCFString

let d: Any = ["one": 1, "two": "two"]
print(type(of: d)) // Dictionary<String, Any>

struct Person { var name = "Bill" }
let e: Any = Person()
print(type(of: e)) // Person

使用 classForCoder

classForCoder 仍然存在,您可以将 Any 类型的值转换为 AnyObject,但如果该值是 Swift 值类型,你会得到一个转换后的结果,而不是原始类型:

import Foundation // or import UIKit or import Cocoa

let f: Any = "bye"
print((f as AnyObject).classForCoder) // NSString
print(type(of: f)) // String

let g: Any = 2
print((g as AnyObject).classForCoder) // NSNumber
print(type(of: g)) // Int

let h: Any = [1: "one", 2: 2.0]
print((h as AnyObject).classForCoder) // NSDictionary
print(type(of: h)) // Dictionary<Int, Any>

struct Dog { var name = "Orion" }
let i: Any = Dog()
print((i as AnyObject).classForCoder) // _SwiftValue
print(type(of: i)) // Dog

// For an object, the result is the same
let j: Any = UIButton()
print((j as AnyObject).classForCoder) // UIButton
print(type(of: j)) // UIButton

关于swift - Xcode 8 测试版 6 : AnyObject replaced by Any: where is classForCoder?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38963362/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com