Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

發現observable 一定要有default value, 請問可以default nil 嗎? #3

Open
cliff357 opened this issue Dec 6, 2019 · 2 comments

Comments

@cliff357
Copy link

cliff357 commented Dec 6, 2019

No description provided.

@koromiko
Copy link
Owner

koromiko commented Dec 6, 2019

因為Observable是有一個泛型T的類別,如果不希望這個T永遠是optional的話,就沒辦法指定default value是nil

class Observable<T> {
    let value: T? = nil   // T一定要包成optional才有辦法default nil 
}

如果真的很想要default nil的話,可以subclass它並且指定optional型別

class NullableObserver<U>: Observable<U?> {
    override init(value: U? = nil) {
        super.init(value: value)
    }
}

// 就可以這樣
NullableObserver<String>()

當然不太建議這樣做就是了

@cliff357
Copy link
Author

cliff357 commented Dec 13, 2019

明白明白,但為什麼不太建議?
是T 不建議 nil 嗎?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants