問題描述
嘿,這里有一個簡短的問題.我相信有一個簡單的答案.
Hey there, quick question here. I'm sure there's a simple answer.
來自 PHP,我習(xí)慣于用這樣的默認(rèn)參數(shù)值聲明一個函數(shù):
Coming from PHP, I'm used to declaring a function with a default argument value like this:
function myFunction ($array, $sort = FALSE) {
}
我的 sort 參數(shù)沒有被填充,函數(shù)將繼續(xù)使用默認(rèn)值 false.在Obj-C中,有沒有類似的東西?
I the sort parameter wasn't filled, the function would continue with the default value of false. In Obj-C, is there a similar thing?
我正在完成Objective-C 2.0 中的編程"一書中的練習(xí),它希望我重新編寫分?jǐn)?shù)類打印函數(shù)以默認(rèn)不減少分?jǐn)?shù),但如果值為 TRUE給出減少,繼續(xù)減少分?jǐn)?shù),然后打印.本章(本書中也沒有)提供了有關(guān)此的任何信息.
I'm working through the exercises in my "Programming In Objective-C 2.0" book, and it wants me to re-write a fraction class print function to default-ly not reduce the fraction, but if the value TRUE for reduce is given, go ahead and reduce the fraction, then print. The chapter (Nor nowhere in the book) gives any information on this.
感謝您的幫助:D
推薦答案
Objective-C 本身不存在默認(rèn)參數(shù).他們真的不能,因為參數(shù)數(shù)量與方法名稱密不可分——每個冒號對應(yīng)一個參數(shù).
Default arguments don't exist in Objective-C, per se. They can't really, because the argument count is inextricably tied to the method name — each colon corresponds to one argument.
Objective-C 程序員通過創(chuàng)建方便"的方法來實(shí)現(xiàn)類似的目標(biāo),這些方法只調(diào)用更原始"的方法,其中一些參數(shù)填充有默認(rèn)值.例如,-[NSArray indexOfObject:]
可以實(shí)現(xiàn)為 -[NSArray indexOfObject:inRange:]
的版本,參數(shù)為 NSMakeRange(0, [selfcount])
用于 inRange:
部分.
Objective-C programmers accomplish a similar goal, though, by creating "convenience" methods that just call to a more "primitive" method with some of the arguments filled in with default values. For example, -[NSArray indexOfObject:]
could be implemented as version of -[NSArray indexOfObject:inRange:]
with an argument of NSMakeRange(0, [self count])
for the inRange:
part.
不過,在這種情況下,我不認(rèn)為你的書在談?wù)撨@個.我認(rèn)為這只是意味著如果為 reduce:
參數(shù)給出 YES 則減少分?jǐn)?shù),如果給出 NO 則不減少它.
In this case, though, I don't think your book is talking about that. I think it simply means to reduce the fraction if YES is given for the reduce:
argument and not reduce it if NO is given.
這篇關(guān)于Objective-C 默認(rèn)參數(shù)值的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!