iOS オールスターズ2でお話しした資料です! Swift らしさってなんだろう、そんなところを API デザインガイドラインと Swift 標準ライブラリの表現に着目して 7 つほど紹介してみました。あくまでも "指針" なので『そういう風に考えていくのね』みたいに捉えて、そこからは "自分らしい" 言葉を紡いでいってくれたらいいのかなって思います。
// Int 型の値をString 型にキャスト(全幅変換)
let string = String(number, radix: 16)
// ビットパターンを指定して Int32 型を生成(Narrow 変換)
let value = Int32(truncatingBitPattern: number)
// 範囲を生成
let range = MyRange(lower: start, upper: last)
// 標準ライブラリーに規定されている性質
/// Atype 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
}
// 標準ライブラリーに規定されている性質
/// Atype 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)"
// 標準ライブラリーに規定されている性質
/// Atype 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])