Swift API 設(shè)計思考題

參考文檔:[譯] 官方 Swift API 設(shè)計規(guī)范

  1. 說明下面兩個方法為什么第一個聲明了參數(shù)標簽 at,第二個方法缺省了。
extension List {
  public mutating func remove(at position: Index) -> Element
  public mutating func remove(_ member: Element) -> Element?
}
  1. 下面兩種聲明方式哪一個是正確的,說明原因。
func add(_ observer: NSObject, for keyPath: String)
func addObserver(_ observer: NSObject, forKeyPath path: String)
  1. 下面哪一種聲明方式更好,說明原因。
x.subViews(havingColor: y)
x.subViews(color: y)
  1. 下面哪一種聲明方式更好,說明原因。
let foreground = Color(red: 32, green: 64, blue: 128)
let foreground = Color(havingRGBValuesRed: 32, green: 64, andBlue: 128)
  1. 下面兩個方法有什么區(qū)別?
x.sort()
x.sorted()
  1. Protocol 有什么命名規(guī)則?
  2. 什么情況可以聲明全局函數(shù)?
  3. 下面聲明的方法缺省了第一個參數(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 { ... }
}
  1. 下面這樣聲明會帶來什么問題?
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? { ... }
}
  1. 下面的參數(shù)名稱哪一個比較好?
func filter(_ predicate: (Element) -> Bool) -> [Generator.Element]
func filter(_ includedInResult: (Element) -> Bool) -> [Generator.Element]
  1. 下面聲明錯誤的地方在哪里?
extension String {
/// ...description...
    public func compare(_ options: CompareOptions = [], other: String, range: Range? = nil, locale: Locale? = nil
    ) -> Ordering
}
  1. 下面的函數(shù)為什么不需要聲明參數(shù)標簽?
min(number1, number2)
zip(sequence1, sequence2)
  1. 下面兩個初始化方法為什么一個有參數(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) 
}
  1. 下面兩個方法的聲明哪一個比較好?
// a 移動到某個點上
a.move(toX: b, y: c)
a.moveTo(x: b, y: c)
  1. 下面兩個方法的聲明哪一個比較好?
extension UIView {
    func addSubview(_ view: UIView)
    func add(subview: UIView)
}
  1. 下面的聲明可能引發(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
}
  1. 下面哪一個命名是正確的:
struct Model {
    var sourceURL: URL
    var sourceUrl: URL
}

綜合題

  • 什么時候方法、函數(shù)的第一個參數(shù)缺省參數(shù)標簽?
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容