gpt4 book ai didi

ios - `String(describing: MyNSObject.self)` 总是返回 "MyNSObject"吗?

转载 作者:可可西里 更新时间:2023-11-01 02:05:23 25 4
gpt4 key购买 nike

威尔String(describing: MyNSObject.self)总是返回“MyNSObject”?

一些开发者写道:

// identifier is "MyViewController"
let controller = storyboard.instantiateViewController(withIdentifier: String(describing: MyViewController.self)) as! MyViewController

// identifier is "MyTableViewCell"
let cell = tableView.dequeueReusableCell(withIdentifier: String(describing: MyTableViewCell.self), for: indexPath) as! MyTableViewCell

目前有效,因为使用 String(describing: MyNSObject.self)正在返回 "MyNSObject" .

但是我们是处于已定义行为还是未定义行为的情况下? public init<Subject>(describing instance: Subject) 的文档阅读:

/// - If `instance` conforms to the `TextOutputStreamable` protocol, the
/// result is obtained by calling `instance.write(to: s)` on an empty
/// string `s`.
/// - If `instance` conforms to the `CustomStringConvertible` protocol, the
/// result is `instance.description`.
/// - If `instance` conforms to the `CustomDebugStringConvertible` protocol,
/// the result is `instance.debugDescription`.
/// - An unspecified result is supplied automatically by the Swift standard
/// library.

而且我担心我们可能处于未指定结果场景中,不是吗?


注意 1:我们的实际实现是使用 protocol实现接近 static var identifier: String { return String(describing: Self.self) } 的扩展.

注2:NSStringFromClass(Self.self as AnyClass).substring(from: NSStringFromClass(Self.self as AnyClass).range(of: ".")!.upperBound)可能是 String(describing: Self.self) 的潜在定义明确的等价物, 但它看起来真的很丑。

注意 3:甚至覆盖 descriptiondebugDescriptionMyViewControllerMyTableViewCell显然不足以改变 String(describing: Self.self) .

目前使用 Swift 3.1,并将在可用时迁移到 Swift 4。

最佳答案

我现在能记得的唯一描述此行为的官方文档是在 Xcode 发行说明中找到的:

Swift Enhancements and Changes

  • ...

  • Type names and enum cases now print and convert to String without qualification by default. debugPrint or String(reflecting:) can still be used to get fully qualified names. For example:

    enum Fruit { case Apple, Banana, Strawberry }
    print(Fruit.Apple) // “Apple”
    debugPrint(Fruit.Apple) // “MyApp.Fruit.Apple”)

(21788604)

(这在 Xcode 7.0 的部分描述了 Swift 1.2 到 2.0 的增强和变化。所以,convert to String 意味着使用 String。 init(_:),现在是 String.init(describing:).)

因此,Swift 的一些核心成员意识到了这种有意更改的行为。如果 Swift 团队会更改它,我希望在 swift.org 中进行一些讨论或至少发布一些公告。

关于ios - `String(describing: MyNSObject.self)` 总是返回 "MyNSObject"吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43222505/

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