はじめに
Objective-Cのコードを書き換える時にArrayについてはハマるようです。
そこでTIPS的のようにできるのではないかと思い記事にします。
まず、追加している箇所のコードが何型の変数を追加しているのかで2パターンに分かれます。
パターン別にコード例を書きました。
Arrayの中身がDictionaryのとき
追加している箇所が、NSDictionaryの場合
(複数の値を1セットにして管理している場合)
方針
Swiftのタプルを使って置き換えるといいのではないかと考えました。
書き換え例
書き換え方の例をユースケース別に記載します。
宣言
@property (nonatomic) NSMutableArray *selectArray;
typealias selectTuple = (index:Int , number:Int)
var selectArray:[selectTuple] = []
初期化
self.selectArray = [NSMutableArray array];
selectArray = []
Swiftは宣言時に初期化しているので必要に応じて初期化を追加すること
(ViewController起動後1しか初期化しない場合はわざわざ初期化する必要はない)
追加
NSDictionary *tappedDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:inxdex], @"index",
[NSNumber numberWithInteger:number], @"number",
nil];
[self.selectArray addObject:tappedDictionary];
let tappedTuple:selectTuple = (index:index , number:numebr)
selectArray.append(tappedTuple)
削除
NSDictionary *tappedDictionary = [NSDictionary dictionaryWithObjectsAndKeys:
[NSNumber numberWithInteger:inxdex], @"index",
[NSNumber numberWithInteger:number], @"number",
nil];
[self.selectArray removeObject:tappedDictionary];
let tappedTuple:selectTuple = (index:index , number:numebr)
if let index = selectArray.firstIndex(where: {$0.number == tappedTuple.number && $0.index == tappedTuple.index}) {
selectArray.remove(at: index)
}
参照
for (NSDictionary *selectDictionary in self.selectArray) {
NSInteger inxdex = [[selectDictionary objectForKey:@"index"] integerValue];
NSInteger number = [[selectDictionary objectForKey:@"number"] integerValue];
}
for select in self.selectArray {
let index = select.index
let number = select.number
}
Arrayの中身がNSStringなどのとき
追加している箇所が、NSString,UIImageなどの変数の場合
方針
SwiftではNSStringならStringの配列として置き換えるといいのではないかと考えました。
書き換え例
書き換え方の例をユースケース別に記載します。
宣言
@property (nonatomic) NSMutableArray *selectTextArray;
private var selectTextArray:[String] = []
初期化
self.selectTextArray = [NSMutableArray array];
selectTextArray = []
Swiftは宣言時に初期化しているので必要に応じて初期化を追加すること
(ViewController起動後1しか初期化しない場合はわざわざ初期化する必要はない)
追加
NSString *text = @"Hoge";
[self.selectTextArray addObject:text];
let text = "Hoge"
selectTextArray.append(text)
削除
NSString *text = @"Hoge";
[self.selectTextArray removeObject:tappedText];
let text = "Hoge"
if let index = selectTextArray.firstIndex(of: text) {
selectTextArray.remove(at: index)
}
参照
for (NSString *text in self.selectTextArray) {
NSLog(@"%@",text);
}
for text in self.selectTextArray {
print(text)
}
最後に
Objective-CではできなかったことがSwiftではできます。
うまく活用して行きたいと思います。