參考文檔:[譯] 官方 Swift API 設(shè)計規(guī)范
- 說明下面兩個方法為什么第一個聲明了參數(shù)標簽 at,第二個方法缺省了。
extension List {
public mutating func remove(at position: Index) -> Element
public mutating func remove(_ member: Element) -> Element?
}
- 下面兩種聲明方式哪一個是正確的,說明原因。
func add(_ observer: NSObject, for keyPath: String)
func addObserver(_ observer: NSObject, forKeyPath path: String)
- 下面哪一種聲明方式更好,說明原因。
x.subViews(havingColor: y)
x.subViews(color: y)
- 下面哪一種聲明方式更好,說明原因。
let foreground = Color(red: 32, green: 64, blue: 128)
let foreground = Color(havingRGBValuesRed: 32, green: 64, andBlue: 128)
- 下面兩個方法有什么區(qū)別?
x.sort()
x.sorted()
-
Protocol 有什么命名規(guī)則?
- 什么情況可以聲明全局函數(shù)?
- 下面聲明的方法缺省了第一個參數(shù)標簽有什么原因?
extension Shape {
/// Returns `true` iff `other` is within the area of `self`.
func contains(_ other: Point) -> Bool { ... }
/// Returns `true` iff `other` is entirely within the area of `self`.
func contains(_ other: Shape) -> Bool { ... }
}
- 下面這樣聲明會帶來什么問題?
extension Box {
/// Returns the `Int` stored in `self`, if any, and
/// `nil` otherwise.
func value() -> Int? { ... }
/// Returns the `String` stored in `self`, if any, and
/// `nil` otherwise.
func value() -> String? { ... }
}
- 下面的參數(shù)名稱哪一個比較好?
func filter(_ predicate: (Element) -> Bool) -> [Generator.Element]
func filter(_ includedInResult: (Element) -> Bool) -> [Generator.Element]
- 下面聲明錯誤的地方在哪里?
extension String {
/// ...description...
public func compare(_ options: CompareOptions = [], other: String, range: Range? = nil, locale: Locale? = nil
) -> Ordering
}
- 下面的函數(shù)為什么不需要聲明參數(shù)標簽?
min(number1, number2)
zip(sequence1, sequence2)
- 下面兩個初始化方法為什么一個有參數(shù)標簽,一個沒有?
extension UInt32 {
/// Creates an instance having the specified value.
init(_ value: Int16)
/// Creates an instance having the lowest 32 bits of source.
init(truncating source: UInt64)
}
- 下面兩個方法的聲明哪一個比較好?
// a 移動到某個點上
a.move(toX: b, y: c)
a.moveTo(x: b, y: c)
- 下面兩個方法的聲明哪一個比較好?
extension UIView {
func addSubview(_ view: UIView)
func add(subview: UIView)
}
- 下面的聲明可能引發(fā)什么問題?
struct Array {
/// Inserts `newElement` at `self.endIndex`.
public mutating func append(_ newElement: Element)
/// Inserts the contents of `newElements`, in order, at
/// `self.endIndex`.
public mutating func append(_ newElements: S)
where S.Generator.Element == Element
}
- 下面哪一個命名是正確的:
struct Model {
var sourceURL: URL
var sourceUrl: URL
}
綜合題
- 什么時候方法、函數(shù)的第一個參數(shù)缺省參數(shù)標簽?