0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

swift実践入門output Chapter4 コレクションを表す型 後編

Last updated at Posted at 2020-10-14

##CollectionとしてのString型

String型は単一の文字を表すCharacter型のコレクションとして定義されており、文字の列挙や文字数のカウントなどの機能を持つ

chapter4.swift

//StringIndex型 文字列内の位置を表すかた
let string = "abcdefghijelmnopqustuvwxyza"
let startString = string[string.startIndex]
print(startString)

//a

//n番目、最後のindexを取得するには
let string2 = "abcdefghijelmnopqustuvwxyza"
let startString2 = string2.startIndex

let bIndex = string.index(startString2, offsetBy: 8)
print(bIndex)
let bb = string[bIndex]
print(bb)

//i

let endString = string2.endIndex
let cIndex = string.index(endString, offsetBy: -1)
let cc = string[cIndex]
print(cc)

//countプロパティを用いて要素数を取得
print(string2.count)
//27

#シーケンス 
その要素に一方向から順次アクセス可能なデータ構造

コレクションはシーケンスを包括する概念
一方向からの順次アクセスと特定のインデックスの値へ直接アクセスが可能なデータ構造

###Sequenceプロトコル 要素へ順次アクセス

chapter4.swift
//forEach(_:)メソッド 要素に対して順次アクセス

let darray = [1,2,3,4,5,6,7]
var enumerated = [] as [Int]
darray.forEach ({ element in enumerated.append(element)
})

print(enumerated)

//[1, 2, 3, 4, 5, 6, 7]

//filterd(_:)メソッド 要素を絞り込む
let filtered = darray.filter ({ element  in element % 2 == 0
})
print(filtered)
//[2, 4, 6]

//map(_:)メソッド 要素を変換する
//全ての要素を特定の要素を用いて変換
let double = darray.map({element in element * 2})
print(double)
//[2, 4, 6, 8, 10, 12, 14]


//別の型のシーケンスへと変換 Int → String

let farray = [1,2,3,4,5]
let converted = farray.map({element in String(element)})
print(converted)

//["1", "2", "3", "4", "5"]


//flatMap(_:)メソッド 要素をシーケンスに変換し、それを一つのシーケンスに追加

let sss = [1,2,3]
let ttt = sss.flatMap({value in [value, value * 2]})
print(ttt)

//compacttMap(_:)メソッド 要素を、失敗する可能sるのある処理を用いて変換する

//全ての要素を特定の処理で変換するが、変換できない値は無視する

let ggg = ["abc","123","kjg","456"]
let integers = ggg.compactMap({value in Int(value)})
print(integers)
//[123, 456]


//reduce(_:)メソッド 要素を1つの値にまとめる
let sarray = [1,2,3,4,5,6,7,8,9]

let sum = sarray.reduce(0, {result, element in result + element} )
print(sum)
//45

let concat = sarray.reduce("", {result, element in result + String(element)})
print(concat)

//123456789




//Collectionプロトコル サブスクリプトによる要素へのアクセス
let warray = [1,2,2,3,2,1,2,3,4]

print(warray.count)
//9

print(warray.isEmpty)
//false

print(warray.first)
//Optional(1)

print(warray.last)
//Optional(4)

print(warray[3])
//3


0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?