小编use*_*806的帖子

协议扩展和子类

我想知道为什么以下内容没有打印出我认为应该的内容。

/* Fails */
protocol TheProtocol {
    func update()
}

class A: TheProtocol {
}

class B : A {}

extension TheProtocol {
    func update() {
        print("Called update from TheProtocol")
    }
}

extension TheProtocol where Self: B {
    func update() {
        print("Called update from B")
    }
}

let instanceB = B()
instanceB.update()

let instanceBViaProtocol:TheProtocol = B()
instanceBViaProtocol.update()
Run Code Online (Sandbox Code Playgroud)

这将打印以下内容:

Called update from B
Called update from TheProtocol // Why not: Called update from B (extension)
Run Code Online (Sandbox Code Playgroud)

我特别想知道为什么

instanceBViaProtocol.update()
Run Code Online (Sandbox Code Playgroud)

不在 TheProtocol 的扩展中执行 update(): …

protocols ios swift

5
推荐指数
1
解决办法
706
查看次数

快速便捷初始化和通用类

我在创建方便的init方法时遇到问题,该方法随后在具有泛型类型参数的类上调用指定的init。这是Swift 3.1 XCode版本8.3.2(8E2002)游乐场

protocol A {
    var items: [String] { get set }
    func doSomething()
}

struct Section : A {
    var items: [String] = []

    func doSomething() {
        print("doSomething")
        items.forEach { print($0) }
    }
}

class DataSource<T: A> {
    var sections: [T]

    init(sections: [T]) {
        self.sections = sections
    }

    func process() {
        sections.forEach { $0.doSomething() }
    }

    convenience init() {
        var section = Section()
        section.items.append("Goodbye")
        section.items.append("Swift")

        self.init(sections: [section])
    }
}

/*: Client */
var section = Section()
section.items.append("Hello")
section.items.append("Swift") …
Run Code Online (Sandbox Code Playgroud)

generics init swift

3
推荐指数
1
解决办法
1247
查看次数

RxSwift:处置(由:)怪异

所以下面的代码编译时出现错误

var doneSubscription: Disposable = item.doneSubjectObservable
        .debug("doneSubscriptions")
        .subscribe(
            onNext: {
                done in self.validateDone(done: done, item: item)
        }).disposed(by: disposeBag)
Run Code Online (Sandbox Code Playgroud)

类型“()”的值不符合 .dispose(by: disposeBag) 行上指定的类型“Disposable”

但我可以毫无错误地做到这一点:

var doneSubscription: Disposable = item.doneSubjectObservable
        .debug("doneSubscriptions")
        .subscribe(
            onNext: {
                done in self.validateDone(done: done, item: item)
        })

    doneSubscription.disposed(by: disposeBag)
Run Code Online (Sandbox Code Playgroud)

我所做的只是.disposed(by: disposeBag)从订阅链中移出。

我错过了什么吗,这两种方法不是等价的吗?

swift rx-swift

0
推荐指数
1
解决办法
459
查看次数

标签 统计

swift ×3

generics ×1

init ×1

ios ×1

protocols ×1

rx-swift ×1