swift2 如何在swift中使用guard而不是if

vlf7wbxs  于 2022-11-06  发布在  Swift
关注(0)|答案(4)|浏览(268)

如何在swift中使用'guard'。我看了很多关于'guard'的文章。但是我对这个不太清楚。请给予我一个清楚的想法。请给我下面的'if'语句的示例输出。

if firstName != "" 
{
   if lastName != "" 
   {
      if address != "" 
      {
        // do great code
      }
   }
 }
wgx48brx

wgx48brx1#

如果一个或多个条件不满足,guard语句用于将程序控制转移到作用域之外。

func doSomething(data: String?) -> String {

    // If data is nil, then return
    guard let data = data else { return "Invalid data" }

    defer { print("This will always be printed if data isn't nil") }

    // data is now a non optional String
    if data.lowercaseString == "ok" { return "Data is \"ok\"" }

    return "I'm your father"
}

print(doSomething("ok"))

输出:

This will always be returned if data isn't nil
Data is "ok"

更接近你的问题:
保护语句中任何条件的值都必须具有符合BooleanType协议的类型。

func doSomething(data: String) -> String {

    guard !data.isEmpty else { return "Data is empty" }

    return data
}

print(doSomething("ok")) // ok
print(doSomething(""))   // Data is empty
bq8i3lrv

bq8i3lrv2#

您也可以使用guards,这样代码可读性会更好,

let firstName = "First"
let lastName = "Last"
let address = "" // empty

if firstName != ""
{
    if lastName != ""
    {
        if address != ""
        {
            print(1,firstName,lastName, address)
        } else {
            print(1,"address is empty")
        }
    } else {
        print(1,"lastName is empty")
    }
} else {
    print(1,"firstName is empty")
}

func foo(firstName: String, lastName: String, address: String) {
    guard !firstName.isEmpty else { print(2,"firstName is empty"); return }
    guard !lastName.isEmpty else { print(2,"lastName is empty"); return }
    guard !address.isEmpty else { print(2,"address is empty"); return }

    print(2,firstName,lastName, address)
}

foo(firstName, lastName: lastName, address: address)
/*
 1 address is empty
 2 address is empty
 */
foo(firstName, lastName: lastName, address: "Address")
/*
 2 First Last Address
 */
zysjyyx4

zysjyyx43#

  1. guard的目的是验证某个条件,并在不满足该条件时强制停止执行,但defer定义了一个代码块,该代码块在执行即将离开当前作用域时才执行。
    1.在guard中,一旦选择项成功展开,展开的值就可以供后续程式码使用,而Defer则可用于执行无条件清除,不论某些作业是否成功。
  2. Guards提供了一个深度嵌套的if-let的替代方法,而defer提供了一个try/finally done right的替代方法。
    1.两者都用于控制流和错误处理
    使用保护延迟(& D):
for imageName in imageNamesList {
    guard let image = UIImage(named: imageName)
else { continue }
    // do something with image
}

func deferExample() {
    defer {
        print(“This will be run last”)
    }
    defer {
         print(“This will be run second-last”)
    }
    print(“operation started”)
    // …
    print(“operation complete”)
}

请看http://nstechstack.com/archives/question/223-1

p1tboqfb

p1tboqfb4#

让我们来了解一下非常简单的if方法。

class MySampleClass {

    var sampleString:String?

    func printSampleString() -> Void {

        if let str = sampleString{ ///if sampleString is nil the if will escape

            print(str) ///sampleString is not nil
        }
    }
}

var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()

现在,让我们来看看guard方法

class MySampleClass {

    var sampleString:String?

    func printSampleString() -> Void {

        guard let str = sampleString else { ///guard will ensure sampleString is not nil

            return ///if sampleString is nil,then return
        }

        print(str) //sampleString is not nil,so print str!

    }
}

var obj : MySampleClass = MySampleClass()
obj.sampleString = "SampleString"///Assign value to sampleString
obj.printSampleString()

相关问题