gpt4 book ai didi

swift - 进行可选链接的好方法

转载 作者:可可西里 更新时间:2023-11-01 01:42:35 24 4
gpt4 key购买 nike

我目前在我的代码中这样做是为了处理可选项...

我做一个

fetchedResultController.performFetch(nil)

let results = fetchedResultController.fetchedObjects as [doesnotmatter]

// add all items to server that have no uid
for result in results {

let uid = result.valueForKey("uid") as String?
if uid == nil
{
let name = result.valueForKey("name") as String?

let trainingday = result.valueForKey("trainingdayRel") as Trainingdays?
if let trainingday = trainingday
{
let trainingUID = trainingday.valueForKey("uid") as String?
if let trainingUID = trainingUID
{

let urlstring = "http://XXXX/myGym/addTrainingday.php?apikey=XXXXXX&date=\(date)&appid=47334&exerciseUID=\(exerciseUID)"
let sUrl = urlstring.stringByAddingPercentEscapesUsingEncoding(NSASCIIStringEncoding)
let url = NSURL(string: sUrl!)

// save the received uid in our database
if let dictionary = Dictionary<String, AnyObject>.loadJSONFromWeb(url!)
{
trainingday.setValue(uid, forKey: "uid")
}
self.managedObjectContext!.save(nil)
}

}

}

}

实际上我还需要为每个“if let”语句添加一个“else”子句。这对我来说似乎是非常糟糕的代码!有没有更好的方法来做到这一点?

最佳答案

是的,使用 switch-case 和模式匹配你可以实现这个:

var x : SomeOptional?
var y : SomeOptional?

switch (x, y)
{
case (.Some(let x), .Some(let y)): doSomething() // x and y present
case (.None(let x), .Some(let y)): doSomethingElse() // x not present, but y
// And so on for the other combinations
default: break
}

看看这篇博文:Swift: Unwrapping Multiple Optionals

编辑(略微偏离主题且基于观点):这是我最喜欢的 Swift 功能之一。它还让您只需很少的代码即可实现 FSM,这非常棒。

关于swift - 进行可选链接的好方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28046614/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com