我自己的自定义类中的扩展

问题描述:

我正在阅读另一个 SO 问题,Swift do-try-catch 语法.在他的回答中,rickster 为 OP 的自定义类创建了一个扩展.Konrad77 评论说这是保持代码干净的好方法".我尊重他们的知识,这让我相信我在自己的代码中遗漏了一点.

I was reading through another SO question, Swift do-try-catch syntax. In his answer, rickster creates an extension for the OP's custom class. Konrad77 comments that it's a "Really nice way to keep your code clean." I respect their knowledge which leads me to believe I'm missing the point somewhere in my own code.

是否有任何其他好处(除了干净)或为我创建的类创建扩展的原因?我可以将相同的功能直接放入类中.如果我是唯一一个使用该课程的人或者其他人将访问它,答案是否会改变?

Are there any other benefits (aside from cleanliness) or reasons to create an extension for a class I created? I can just put the same functionality directly into the class. And does the answer change if I am the only one using the class or if someone else will be accessing it?

对于您从头开始创建的类,扩展是一种强大的文档结构类型.您将类的核心放在初始定义中,然后添加扩展以提供附加功能.例如,增加对协议的遵守.它为包含的代码提供局部性:

In the case of a class that you create from scratch extensions are a powerful type of documentation through structure. You put the core of your class in the initial definition and then add on extensions to provide additional features. For example, adding adherence to a protocol. It provides locality to the contained code:

struct Foo {
  let age: Int
}

extension Foo: CustomStringConvertible {
  var description:String { return "age: \(age)" }
}

我可以将协议和计算属性放在结构声明中吗?绝对可以,但是当您拥有一两个以上的属性时,它就会开始变得混乱且难以阅读.如果代码不干净且不可读,则更容易创建错误.使用扩展是避免复杂性带来的困难的好方法.

Could I have put the protocol and computed property in the struct declaration? Absolutely but when you have more than one or two properties it starts to get messy and difficult to read. It's easier to create bugs if the code isn't clean and readable. Using extensions is a great way to stave off the difficulties that come with complexity.