0

I'm writing some extension methods for swift Array type.

The environment is Xcode8.3(8E162) and Swift3.1

I want to make the final code look like [1, 2, 3].cc.find { $0 < 2 } Here cc is like rx in RxSwift and snp in SnapKit.

To achieve that, I created a file named Namesapce.swift with code:

public struct CCWrapper<Wrapped> {
    public let wrapped: Wrapped
    public init(_ wrapped: Wrapped) {
        self.wrapped = wrapped
    }
}

public protocol CCCompatible {
    associatedtype CompatibleType
    static var cc: CCWrapper<CompatibleType>.Type { get set }
    var cc: CCWrapper<CompatibleType> { get set }
}

extension CCCompatible {
    public static var cc: CCWrapper<Self>.Type {
        get { return CCWrapper<Self>.self }
        set {} // for mutating
    }

    public var cc: CCWrapper<Self> {
        get { return CCWrapper(self) }
        set {} // for mutating
    }
}

Another file named Array+CC.swift with code:

extension Array: CCCompatible {}

extension CCWrapper where Wrapped == Array<Any> {
    public func find(_ predicate: (Wrapped.Element) -> Bool) -> Wrapped.Element? {
        for e in wrapped where predicate(e) { return e }
        return nil
    }
}

When I build the project, the compiler will issue a error:

'Element' is not a member type of 'Wrapped'

I have googled the problem and found a question Extend array types using where clause in Swift, but the question is about extend Array for specific element type.

What's wrong with my code? How can I fix it?

Community
  • 1
  • 1
Cokile Ceoi
  • 1,326
  • 2
  • 15
  • 26

1 Answers1

0

Finally, I found a workaround.

I change the code in Array+CC.swift:

extension Array: CCCompatible {}

extension CCWrapper where Wrapped: Sequence {
    public func find(_ predicate: (Wrapped.Iterator.Element) -> Bool) -> Wrapped.Iterator.Element? {
        for e in wrapped where predicate(e) { return e }
        return nil
    }
}
Cokile Ceoi
  • 1,326
  • 2
  • 15
  • 26
  • I have the same problem . I tried change my code by using your method and I got "Missing argument for parameter #2 in call" . can you help me ? the code is ` mutating func remove(object: T.Iterator.Element) { if let index = index(of:object) { remove(at: index) } }` – Neko Nov 28 '18 at 02:41