转换流
我在很多地方都表达了我对流的喜爱。我在 Swift Cookbook 中介绍了一些。现在,我将通过 Pearson 的内容更新计划更新 Swift 3 的相关内容,正好我有一些要说的。我想在文章中添加一些有趣的新配方。 今天,让我们谈谈『转换流』。你写 因此我决定创建一个翻译流。如截图所示,当你打印流的时候,会把英文文本转换成其他语言。
如图所示,我的解决方案充分利用了 Swift 标准库内置的 print 函数。Swift 允许打印到流。当使用我的 在我的实现中,我希望能够做到几个关键点:
标准库内置的 /// A text output stream that performs translation in /// the process of printing public struct TranslationStream<Language: EnglishTranslationProvider>: TextOutputStream { /// Writes the contents of the string to stdout after /// passing the string through an automatic translator public func write(_ string: String) { guard let translation = Language.translate(string) else { return } print(translation) } } 比较 tricky 的是我的 /// A provider of string translations from English public protocol EnglishTranslationProvider { /// Returns a shared instance of the provider static var shared: TranslationStream<Self> { get } /// Returns a translated string static func translate(_ string: String) -> String? } 每个语言翻译的 provider 提供一个 /// A stream type that automatically translates from English to French public struct FrenchStream: EnglishTranslationProvider { /// Returns a shared instance of the provider public static var shared = TranslationStream<FrenchStream>() /// Returns a translated string public static func translate(_ string: String) -> String? { return FrenchStream.translate(string,language: "fr") } } 很简单吧?这真的不难。它实现了两个必要的成员,另一方面作为在协议扩展中声明的默认 我试图让本文的重点是『哇,6666,你可以在打印流时转换文本。』,而不是『哦,翻译了。』。我认为翻译流是展示这个特定的 Swift 特性的好方式。 在下面的截图中,我把(第20行)打印到了用户的通知栏。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |