What’s the difference between init?() and init() ?
What’s the difference between init?() and init() ?
In Swift, the difference between init?() and init() lies in their behavior when initialization fails. Here’s a detailed explanation:
init()init() {
// Initialization code
}
struct Person {
var name: String
init(name: String) {
self.name = name
}
}
let person = Person(name: "John")
init?()nil if the initialization fails due to invalid parameters or other conditions.nil if initialization fails).init?(parameter: Type) {
guard condition else {
return nil
}
// Initialization code
}
struct Person {
var name: String
init?(name: String) {
guard !name.isEmpty else {
return nil
}
self.name = name
}
}
Đăng nhập để tham gia thảo luận cùng mọi người.
Chưa có bình luận nào
Hãy là người đầu tiên chia sẻ suy nghĩ của bạn.