ноль / опционально или без ... что такое основной дифференциал? - PullRequest
0 голосов
/ 27 февраля 2019

в чем большая разница в этих двух кодах?Я новичок в swift / coding вообще :) спасибо за помощь

func hellou(_ name: String = "World") -> String {
return "Hello \(name)!"}


func hello(_ name: String? = nil) -> String {
return "Hello, \(name ?? "World")!)}

1 Ответ

0 голосов
/ 27 февраля 2019

Вот простой код Playground, демонстрирующий различия:

import UIKit

func hellou(_ name: String = "World") -> String {
    return "Hello \(name)!"}


func hello(_ name: String? = nil) -> String {
    return "Hello, \(name ?? "World")!"
}


var someNonNilOptional:String? = "this is not nil, but it could be"
var someNilOptional:String?  // this is nil
var someNonNilString:String = "This string cannot be nil"


// First, all inputs work in the optional method
hello(someNilOptional) // this is fine because hello takes optionals
hello(someNonNilOptional) // this is also fine, because hello takes optionals
hello(someNonNilString) // this too is fine, because a string will work for an Optional(String)


// for the non-optional method, things get more dicey
hellou(someNonNilString) // this is fine, because the parameter is String not String?
hellou(someNonNilOptional!) // this works because we force-unwrap and it wasn't nil

hellou(someNilOptional!) // Fatal error: Unexpectedly found nil while unwrapping an Optional value

hellou(someNonNilOptional) // compile time error
hellou(someNilOptional) // compile time error

Бывают случаи, когда вам не нужен необязательный параметр.Приведенные выше две ошибки времени компиляции являются хорошими примерами, когда я ожидаю, что строка будет иметь значение как программист, а компилятор удостоверится, что они есть.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...