ios Swift 等价于 Java toString()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36587104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:54:21  来源:igfitidea点击:

Swift equivalent of Java toString()

iosswiftstringtostringcustomstringconvertible

提问by Marcus Leon

What is the Swift equivalent of Java toString()to print the state of a class instance?

什么是 Swift 等价于 JavatoString()来打印类实例的状态?

回答by vacawama

The descriptionproperty is what you are looking for. This is the property that is accessed when you print a variable containing an object.

description物业是您正在寻找的。这是打印包含对象的变量时访问的属性。

You can add descriptionto your own classes by adopting the protocol CustomStringConvertibleand then implementing the descriptionproperty.

您可以description通过采用协议CustomStringConvertible然后实现description属性来添加到您自己的类中。

class MyClass: CustomStringConvertible {
    var val = 17

    public var description: String { return "MyClass: \(val)" }
}

let myobj = MyClass()
myobj.val = 12
print(myobj)  // "MyClass: 12"

descriptionis also used when you call the Stringconstructor:

description调用String构造函数时也使用:

let str = String(myobj)  // str == "MyClass: 12"

This is the recommended method for accessing the instance description (as opposed to myobj.descriptionwhich will not work if a class doesn't implement CustomStringConvertible)

这是访问实例描述的推荐方法(相反,myobj.description如果类没有实现,则该方法将不起作用CustomStringConvertible

回答by Andrey

If it is possible to use the struct instead of class, then nothing additional to do.

如果可以使用结构而不是类,则无需额外操作。

struct just prints fine itself to the output

struct 只是将自身打印到输出中

print("\(yourStructInstance)")

or with class like this:

或者像这样的类:

print(String(describing: yourClassInstance))

回答by Ewan Mellor

You should use String(obj).

你应该使用String(obj).

Direct from the documentation for CustomStringConvertible:

直接来自CustomStringConvertible 的文档

NOTE

String(instance) will work for an instance of any type, returning its description if the instance happens to be CustomStringConvertible. Using CustomStringConvertible as a generic constraint, or accessing a conforming type's description directly, is therefore discouraged.

笔记

String(instance) 将适用于任何类型的实例,如果该实例恰好是 CustomStringConvertible,则返回其描述。因此,不鼓励使用 CustomStringConvertible 作为通用约束或直接访问符合类型的描述。

回答by Randika Vishman

How it's done with NSObjectextended classes

NSObject扩展类是如何完成的

If your model class is extended from NSObject, you have to override the Variable descriptionas follows:

如果您的模型类是从 扩展的NSObject,则必须description按如下方式覆盖变量:

public override var description: String {
    return "\n{\n index: \(self.index),\n"
        + " country: \(self.name),\n"
        + " isoCountryCode: \(self.isoCountryCode),\n"
        + " localeId: \(self.localeId),\n"
        + " flagImageName: \(self.flagImageName!)\n}"
}

You can check how I have done it here within the Countryclass, in the "CountryPicker iOS Swift library".

您可以在“CountryPicker iOS Swift 库”中Country课程中查看我是如何做到的。

Or,to make it simpler for you to understand, your class and descriptionmethod should look like following:

或者,为了让您更容易理解,您的类和description方法应如下所示:

public class MyClass: NSObject {
   public var memberAttribute = "I'm an attribute"

   public override var description: String {
       return "My Class member: \(self.memberAttribute)"
   }
}

Note:Since you are extending your Modal class from NSObjectit doesn't require for your class to comply with CustomStringConvertibleclass anymore, and you are overriding descriptionvariable from the NSObjectclass itself. Always remember, CustomStringConvertibleis mostly the pure Swift way of achieving this.

注意:由于您要从中扩展 Modal 类,NSObject因此您的类不再需要遵守CustomStringConvertible类,并且您正在覆盖类本身的description变量NSObject。永远记住,CustomStringConvertible主要是实现这一点的纯 Swift 方式。