Swift Class with an optional value -
how can following:
i have class in swift
class book { var title: string var author: string? init(title: string, author: string?) { self.title = title self.author = author } and in class i'm making phone call api retrieve list of books, though author not nowadays so
let title: string? = getbooktitle() allow author: string? = getbookauthor() book = new book(title: book, author: author) i'm not confident approach, right way it? because have utilize (if let) every time want author of book
you have:
let title: string? = getbooktitle() allow author: string? = getbookauthor() there's presumably no point in making title optional, tell present, depends upon how getbooktitle defined. furthermore, if these methods defined homecoming string or string?, appropriate, type here inferred, yielding:
let title = getbooktitle() allow author = getbookauthor() next, have:
book = new book(title: book, author: author) but, instantiation of new book object needs variable name (and new keyword not needed), yielding:
let book = book(title: book, author: author) (use let if you're going set local book variable 1 time within scope. if you're going reset 1 time again , 1 time again without leaving function, utilize var. bottom line, utilize let whenever can.)
finally, say:
is right way it? because have utilize (if let) every time want author of book.
yes, appropriate utilize optional author. and, yes, means have disclose optional if let or equivalent syntax when want utilize it. note, don't have optional binding syntax, if let, if don't want, rather utilize if , perform forced unwrapping (e.g. !), if want. need disclose 1 way or other.
you technically utilize implicitly unwrapped optional (!), , automatically unwrapped every time utilize it. think standard optional syntax makes meaning more clear (specifically, author may nil).
swift
No comments:
Post a Comment