Extend all types in Swift?

View Swift library code I found:

extension T! : Printable {
  var description: String { get }
}

It appears that the fragment extends all types with a description field. When I try to do the same in my code, I get an error message:

example.swift: 10: 11: Non-nominal type 'T!' cannot be expanded

protocol MyProtocol {
  // ...
}

extension T! : MyProtocol { // error: Non-nominal...
  // ...
}

There are similar questions:

But they cannot address:

  • What's going on here? Why is the library code ok but my code ... no?
  • Is it possible for all types or all types corresponding to a particular protocol?
+4
source share
1 answer

, . T!, ImplicitlyUnwrappedOptional<T>. , , .

"" - ; . , - Swift . .

, "", , - , :

struct Array<T>
extension T[]

enum Optional<T>
extension T?

struct ImplicitlyUnwrappedOptional<T>
extension T!

, - . , extension T! extension ImplicitlyUnwrappedOptional<T>.

extension ImplicitlyUnwrappedOptional<T> " " T ". , "" , . extension Dictionary<KeyType, ValueType>, Swift. .

:

extension ImplicitlyUnwrappedOptional : MyProtocol {
  // ...
}

, .

+7

Source: https://habr.com/ru/post/1545887/


All Articles