当方法当作变量或者参数后就意味着我们可以在一个方法中定义新的方法,这给代码结构层次和访问级别的控制带来了新的选择。
如下例的一个方法请求中调用了很多其他的函数,可是其他的函数在项目中可能就只有这个方法会调用到:
func appendQuery(var url: String,
key: String,
value: AnyObject) -> String {
if let dictionary = value as? [String: AnyObject] {
return appendQueryDictionary(url, key, dictionary)
} else if let array = value as? [AnyObject] {
return appendQueryArray(url, key, array)
} else {
return appendQuerySingle(url, key, value)
}
}
func appendQueryDictionary(var url: String,
key: String,
value: [String: AnyObject]) -> String {
//...
return result
}
func appendQueryArray(var url: String,
key: String,
value: [AnyObject]) -> String {
//...
return result
}
func appendQuerySingle(var url: String,
key: String,
value: AnyObject) -> String {
//...
return result
}
可以考虑改成这样的形式
func appendQuery(var url: String,
key: String,
value: AnyObject) -> String {
func appendQueryDictionary(var url: String,
key: String,
value: [String: AnyObject]) -> String {
//...
return result
}
func appendQueryArray(var url: String,
key: String,
value: [AnyObject]) -> String {
//...
return result
}
func appendQuerySingle(var url: String,
key: String,
value: AnyObject) -> String {
//...
return result
}
if let dictionary = value as? [String: AnyObject] {
return appendQueryDictionary(url, key, dictionary)
} else if let array = value as? [AnyObject] {
return appendQueryArray(url, key, array)
} else {
return appendQuerySingle(url, key, value)
}
}