在 Swift 1.2 中我有这个:
if let filePath = NSBundle.mainBundle().pathForResource("some", ofType: "txt"),
data = String(contentsOfFile: filePath, encoding: NSUTF8StringEncoding) {
for line in data.componentsSeparatedByCharactersInSet(NSCharacterSet.newlineCharacterSet()) {
// Do something
}
} else {
println("some.txt is missing")
}
在 Swift 2 中,我不能再这样做了,因为 pathForResource 和 contentsOfFile 都可以抛出,也可以返回可选值。我可以修复它,但它现在看起来非常冗长:
do {
if let filePath = try NSBundle.... {
do {
if let data = try String.... {
for line in data..... {
// Do something
}
} else {
print("Nil data")
}
} catch {
print("contentsOfFile threw")
}
} else {
print("Nil pathForResource")
}
} catch {
print("pathForResource threw")
}
我想我错过了一些东西 - 感谢您的帮助。
最佳答案
使用 guard 语法代替 if-let。
这是一个示例:
do {
guard let filePath = try NSBundle .... else {
// if there is exception or there is no value
throw SomeError
}
guard let data = try String .... else {
}
} catch {
}
if-let 和 guard 的区别在于展开值的范围。如果您使用 if-let filePath 值仅在 if-let block 内可用。如果您使用保护文件路径值可用于保护调用的范围。
这是swift book中的相关部分
A guard statement, like an if statement, executes statements depending on the Boolean value of an expression. You use a guard statement to require that a condition must be true in order for the code after the guard statement to be executed. Unlike an if statement, a guard statement always has an else clause—the code inside the else` clause is executed if the condition is not true.
关于Swift 2 if let with do-try-catch,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30738271/
如果您尝试在Ruby中的nil对象上调用方法,则会出现NoMethodError异常并显示消息:"undefinedmethod‘...’fornil:NilClass"然而,有一个tryRails中的方法,如果它被发送到一个nil对象,它只返回nil:require'rubygems'require'active_support/all'nil.try(:nonexisting_method)#noNoMethodErrorexceptionanymore那么try如何在内部工作以防止该异常? 最佳答案 像Ruby中的所有其他对象
“输出”是一个序列化的OpenStruct。定义标题try(:output).try(:data).try(:title)结束什么会更好?:) 最佳答案 或者只是这样:deftitleoutput.data.titlerescuenilend 关于ruby-on-rails-更好的替代方法try(:output).try(:data).try(:name)?,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.c
我需要从json记录中获取一些值并像下面这样提取curr_json_doc['title']['genre'].map{|s|s['name']}.join(',')但对于某些记录,curr_json_doc['title']['genre']可以为空。所以我想对map和join()使用try函数。我试过如下curr_json_doc['title']['genre'].try(:map,{|s|s['name']}).try(:join,(','))但是没用。 最佳答案 你没有正确传递block。block被传递给参数括号外的方法
catch在Ruby中是为了跳出深度嵌套的代码。在Java中,例如Java用于处理异常的try-catch可以实现同样的效果,但它被认为是糟糕的解决方案,而且效率也很低。在用于处理异常的Ruby中,我们有begin-raise-rescue,我认为将它用于其他任务也很昂贵。Ruby的catch-throw真的是比begin-raise-rescue更有效的解决方案吗?或者还有其他原因可以使用它来打破嵌套block而不是begin-raise-rescue? 最佳答案 除了是摆脱控制结构的“正确”方式之外,catch-throw也明显
我正在尝试在ruby中获取对Object#try的访问权限。我认为只包含activesupport就可以解决问题,但事实并非如此。irb(main):001:0>require'rubygems'=>trueirb(main):002:0>require'active_support'=>trueirb(main):003:0>o=Object.new=>#irb(main):004:0>o.respond_to?:try=>falseirb(main):005:0>如何访问Object#try? 最佳答案 要尝试,您需要做的就
在ruby中,begin#...rescue#...end不会捕获不是StandardError子类的异常。在C中,rb_rescue(x,Qnil,y,Qnil);VALUEx(void){/*...*/returnQnil;}VALUEy(void){/*...*/returnQnil;}会做同样的事情。我如何从rubyC扩展中rescueException=>e(而不仅仅是rescue=>e)? 最佳答案 Ruby需要更多文档。我不得不进入ruby源代码,这是我发现的:VALUErb_rescue(VALUE(*b_p
在我的大多数应用程序中,我都有一个current_user方法。为了避免像current_user.name这样的情况出现异常,其中current_user是nil,rails提供了try方法。这个问题是我需要记住在current_user可能是nil的地方使用try。我想使用NullObject模式来消除这种额外的开销。classNullUserdefmethod_missing(method_name,*args)nilendenddefcurrent_userreturnNullUser.newunlessUserSession.find@current_user||=UserS
我正在使用Savon为SOAP服务编写一个Ruby接口(interface)。它似乎正在工作,但我在命令行上出现了几条DEBUG消息D,[2011-02-15T16:33:32.664620#4140]DEBUG--:HTTPI尝试使用httpclient适配器,但无法在LOAD_PATH中找到库。后退现在使用net_http适配器。D,[2011-02-15T16:33:32.820863#4140]DEBUG--:HTTPI使用net_http适配器执行HTTPPOST我不确定为什么会出现这些消息,或者它们的含义。有什么想法吗? 最佳答案
我正在尝试使用RubygemRestClient为我的一个FusionTables更新样式。这是我的代码:require'rest_client'tableId=''styleId=''key=''table_url="https://www.googleapis.com/fusiontables/v1/tables/#{tableId}/styles/#{styleId}?key=#{key}"update='{"polygonOptions":{"strokeColor":"#ffffff"}}'token='STRINGCONTAININGAUTHORIZATIONTOKEN'R
尝试运行“foremanstart”来执行我的rails文件时,我收到以下错误。dyld:Symbolnotfound:_rb_ary_new_from_valuesReferencedfrom:/Users/paulbattisson/.rvm/gems/ruby-2.1.1/gems/psych-2.0.5/lib/psych.bundleExpectedin:flatnamespace如果我运行railss那么应用程序可以正常启动,但是我想使用以下Procfile:web:bundleexecrackupconfig.ru-p$PORTresque:envTERM_CHILD=1