参考文档:[译] 官方 Swift API 设计规范
- 说明下面两个方法为什么第一个声明了参数标签 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)
- 下面两个方法有什么区别?
x.sort()
x.sorted()
-
Protocol
有什么命名规则?
- 什么情况可以声明全局函数?
- 下面声明的方法缺省了第一个参数标签有什么原因?
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? { ... }
}
- 下面的参数名称哪一个比较好?
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
}
- 下面的函数为什么不需要声明参数标签?
min(number1, number2)
zip(sequence1, sequence2)
- 下面两个初始化方法为什么一个有参数标签,一个没有?
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)
}
- 下面的声明可能引发什么问题?
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
}
综合题