我对使用嵌套函数时的当前代码风格不满意。
什么时候使用嵌套函数?
假设我有一个带有一个参数的函数。该论点需要验证。我会用守卫来保护它。现在您可以将方法内的任务拆分为更小的方法。这样每个方法最多有n行。您可以将提取的方法设为私有(private),但这会比我需要的范围更大。因为这些方法仅在该方法内使用。我可以使用的最小范围是嵌套函数。
但在我看来,嵌套函数会使代码变脏。
下面的例子展示了我目前的代码风格。
private func myFunction(iterationCount: Int) {
func nestedOne() {
}
func nestedTwo(param: Int) {
}
guard iterationCount > 0 else {
return
}
for i in 0 ..< iterationCount {
nestedOne()
nestedTwo(i)
}
}
您如何看待这种代码风格?
编辑:
这是真实世界的例子。这应该是足够的信息。每个方法本身只有几行代码。但是加在一起有很多行代码。但是将它们设为私有(private)将使类可以访问它们。并且这些方法永远不会被其他方法使用。
private func rotateToPoint(newCenterPoint centerPoint: CGPoint, withDuration duration: Double) -> Bool {
func createAnimation(/*n params here*/) -> CAKeyframeAnimation {
let animation = CAKeyframeAnimation(keyPath: "position")
// Create a CAKeyframeAnimation with the given path, duration etc.
//
//
// Method has about this numer of lines.
//
//
return animation
}
func createPathForRotation(/*n params here*/) -> UIBezierPath {
let path = UIBezierPath()
// Calculcate the path to move a view with an rotating second view.
//
//
// Method has about this number of lines.
//
//
//
return path
}
func completionAction(/*n params here*/) {
// Update state etc.
//
// Method has about this number of lines.
//
//
}
guard true /* check here */ else {
return false
}
// Some variables and method calls here.
//
// Method has about this number of lines.
//
//
//
//
return true
}
最佳答案
由于您的内部函数用于创建值,因此您可以使用闭包来初始化和设置您的变量/常量。
private func rotateToPoint(newCenterPoint centerPoint: CGPoint, withDuration duration: Double) -> Bool {
guard true /* check here */ else {
return false
}
let animation : CAKeyframeAnimation = {
let animation = CAKeyframeAnimation(keyPath: "position")
// set animation properties...
return animation
}()
let path: UIBezierPath = {
let path = UIBezierPath()
// seth path properties
return path
}()
let completion: (String)->() = { (word:String)->() in
} // <- IMPORTANT! no parenthesis here
// just use animation, path and completion
return true
}
如你所愿
rotateToPoint 不可见rotateToPoint 之外不可见关于带有嵌套函数的 Swift 简洁代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35434274/
我得到了一个包含嵌套链接的表单。编辑时链接字段为空的问题。这是我的表格:Editingkategori{:action=>'update',:id=>@konkurrancer.id})do|f|%>'Trackingurl',:style=>'width:500;'%>'Editkonkurrence'%>|我的konkurrencer模型:has_one:link我的链接模型:classLink我的konkurrancer编辑操作:defedit@konkurrancer=Konkurrancer.find(params[:id])@konkurrancer.link_attrib
如何在buildr项目中使用Ruby?我在很多不同的项目中使用过Ruby、JRuby、Java和Clojure。我目前正在使用我的标准Ruby开发一个模拟应用程序,我想尝试使用Clojure后端(我确实喜欢功能代码)以及JRubygui和测试套件。我还可以看到在未来的不同项目中使用Scala作为后端。我想我要为我的项目尝试一下buildr(http://buildr.apache.org/),但我注意到buildr似乎没有设置为在项目中使用JRuby代码本身!这看起来有点傻,因为该工具旨在统一通用的JVM语言并且是在ruby中构建的。除了将输出的jar包含在一个独特的、仅限ruby
在rails源中:https://github.com/rails/rails/blob/master/activesupport/lib/active_support/lazy_load_hooks.rb可以看到以下内容@load_hooks=Hash.new{|h,k|h[k]=[]}在IRB中,它只是初始化一个空哈希。和做有什么区别@load_hooks=Hash.new 最佳答案 查看rubydocumentationforHashnew→new_hashclicktotogglesourcenew(obj)→new_has
这道题是thisquestion的逆题.给定一个散列,每个键都有一个数组,例如{[:a,:b,:c]=>1,[:a,:b,:d]=>2,[:a,:e]=>3,[:f]=>4,}将其转换为嵌套哈希的最佳方法是什么{:a=>{:b=>{:c=>1,:d=>2},:e=>3,},:f=>4,} 最佳答案 这是一个迭代的解决方案,递归的解决方案留给读者作为练习:defconvert(h={})ret={}h.eachdo|k,v|node=retk[0..-2].each{|x|node[x]||={};node=node[x]}node[
我想在一个没有Sass引擎的类中使用Sass颜色函数。我已经在项目中使用了sassgem,所以我认为搭载会像以下一样简单:classRectangleincludeSass::Script::FunctionsdefcolorSass::Script::Color.new([0x82,0x39,0x06])enddefrender#hamlengineexecutedwithcontextofself#sothatwithintemlateicouldcall#%stop{offset:'0%',stop:{color:lighten(color)}}endend更新:参见上面的#re
我正在尝试用ruby中的gsub函数替换字符串中的某些单词,但有时效果很好,在某些情况下会出现此错误?这种格式有什么问题吗NoMethodError(undefinedmethod`gsub!'fornil:NilClass):模型.rbclassTest"replacethisID1",WAY=>"replacethisID2andID3",DELTA=>"replacethisID4"}end另一个模型.rbclassCheck 最佳答案 啊,我找到了!gsub!是一个非常奇怪的方法。首先,它替换了字符串,所以它实际上修改了
我有一些代码在几个不同的位置之一运行:作为具有调试输出的命令行工具,作为不接受任何输出的更大程序的一部分,以及在Rails环境中。有时我需要根据代码的位置对代码进行细微的更改,我意识到以下样式似乎可行:print"Testingnestedfunctionsdefined\n"CLI=trueifCLIdeftest_printprint"CommandLineVersion\n"endelsedeftest_printprint"ReleaseVersion\n"endendtest_print()这导致:TestingnestedfunctionsdefinedCommandLin
我的主要目标是能够完全理解我正在使用的库/gem。我尝试在Github上从头到尾阅读源代码,但这真的很难。我认为更有趣、更温和的踏脚石就是在使用时阅读每个库/gem方法的源代码。例如,我想知道RubyonRails中的redirect_to方法是如何工作的:如何查找redirect_to方法的源代码?我知道在pry中我可以执行类似show-methodmethod的操作,但我如何才能对Rails框架中的方法执行此操作?您对我如何更好地理解Gem及其API有什么建议吗?仅仅阅读源代码似乎真的很难,尤其是对于框架。谢谢! 最佳答案 Ru
下面例子中的Nested和Child有什么区别?是否只是同一事物的不同语法?classParentclassNested...endendclassChild 最佳答案 不,它们是不同的。嵌套:Computer之外的“Processor”类只能作为Computer::Processor访问。嵌套为内部类(namespace)提供上下文。对于ruby解释器Computer和Computer::Processor只是两个独立的类。classComputerclassProcessor#Tocreateanobjectforthisc
我的假设是moduleAmoduleBendend和moduleA::Bend是一样的。我能够从thisblog找到解决方案,thisSOthread和andthisSOthread.为什么以及什么时候应该更喜欢紧凑语法A::B而不是另一个,因为它显然有一个缺点?我有一种直觉,它可能与性能有关,因为在更多命名空间中查找常量需要更多计算。但是我无法通过对普通类进行基准测试来验证这一点。 最佳答案 这两种写作方法经常被混淆。首先要说的是,据我所知,没有可衡量的性能差异。(在下面的书面示例中不断查找)最明显的区别,可能也是最著名的,是你的