繁体   English   中英

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

[英]nil/optional or without...what is the main diff?

这两个代码的最大区别是什么? 我是 swift/编码的初学者 :) 谢谢你的帮助

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


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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM