iOS オールスターズ2でお話しした資料です! Swift らしさってなんだろう、そんなところを API デザインガイドラインと Swift 標準ライブラリの表現に着目して 7 つほど紹介してみました。あくまでも "指針" なので『そういう風に考えていくのね』みたいに捉えて、そこからは "自分らしい" 言葉を紡いでいってくれたらいいのかなって思います。
36. // 標準ライブラリーに規定されている性質
/// A type that can be compared for value equality.
protocol Equatable {
/// Returns a Boolean value indicating
/// whether two values are equal.
static func ==(lhs: Self, rhs: Self) -> Bool
}
41. // 標準ライブラリーに規定されている性質
/// A type with a customized textual representation.
protocol CustomStringConvertible {
/// A textual representation of this instance.
var description: String { get }
}
42. enum Device : CustomStringConvertible {
case iPhone, iPad, appleWatch
var description: String {
switch self {
case .iPhone: return "iPhone"
case .iPad: return "iPad"
case .appleWatch: return " Watch"
}
}
43. let device = Device.appleWatch
// テキスト表現への Narrow 変換
let displayText = String(describing: device)
// テキスト表現に変換して、テキストコンソールに出力
print(device)
// String 型の文字列補完構文は、テキスト表現を使用
let message = "I love (device)"
49. // 標準ライブラリーに規定されている性質
/// A type that provides sequential,
/// iterated access to its elements.
public protocol Sequence {
/// A type that provides the sequence's iteration
/// interface and encapsulates its iteration state.
associatedtype Iterator : IteratorProtocol
50. // 連続する任意の浮動小数点数を対象にする
func sum<S: Sequence, T: FloatingPoint>
(of values: S) -> T where S.Iterator.Element == T {
return values.reduce(0, +)
}
// 連続する浮動小数点数の部分配列の合計を計算
sum(of: floatValues[2 ..< 6])