无/可选或无...主要区别是什么?

时间:2019-02-26 21:53:42

标签: swift string function null

这两个代码的最大区别是什么?我完全是swift /编码的初学者:) thx寻求帮助

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


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

1 个答案:

答案 0 :(得分:0)

下面是一些简单的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

有时您不希望使用可选参数。上面的两个编译时错误是一个很好的例子,我希望该字符串作为程序员具有一个值,并且编译器确保它们是正确的。