tableViewなどのcellの型をenumで作成し、
Dataをassociated valueで持たせている時、
その並びをcustom struct(collectionを継承)で定義しようと思っています。
そこで、その値を変更するcustom funcを設定する時、
配列のindexをintで指定できなくて困っています。
PresentCell「.name」を忘れてて、修正したら、違うエラーとなりましたので、
変更しました。
サンプルコードを作って試しています。
下記のコードを見てもらった方が早いと思います。
Swift
1import UIKit 2 3class ViewController: UIViewController { 4 5 override func viewDidLoad() { 6 super.viewDidLoad() 7 // Do any additional setup after loading the view. 8 9 let cells = TempCells() 10 print(cells[0] as! PresentCell) // これは動く 11 print(cells[1] as! PresentCell) // これも動く 12 print(cells[2] as! PresentCell) // そしてこれも大丈夫 13 cells.rewriteName(firstName: "大阪", lastName: "次郎") // これを実行したい 14 } 15} 16 17struct TempCells: Collection { 18 typealias _Element = PresentCell 19 typealias Index = Int 20 21 var startIndex: Int { return 0 } 22 var endIndex: Int { return limit } 23 let limit: Int = 2 24 25 subscript(position: Int) -> _Element { 26 precondition((startIndex...endIndex) ~= position, "Index out of bounds.") 27 switch position { 28 case 0: return PresentCell.name(NameData(firstName: "東京", lastName: "太郎")) 29 case 1: return PresentCell.birthday(DateData(date: Date().addingTimeInterval(-60*60*24*365*20).timeIntervalSince1970)) 30 case 2: return PresentCell.university(SchoolData(university: "東京大学")) 31 default: return PresentCell.none 32 } 33 } 34 35 func index(after i: Int) -> Int { 36 precondition(i < endIndex, "Can't advance beyond endIndex") 37 return i + 1 38 } 39 40 func rewriteName(firstName: String, lastName: String) -> TempCells { 41 var tempCells = TempCells() 42 tempCells[0] = PresentCell.name(NameData(firstName: firstName, lastName: lastName)) // <-この行で[0]のとこがIntでは指定できませんというエラーが返ってきて詰まっています。 43 return tempCells 44 } 45 46} 47 48enum PresentCell { 49 case name(NameData) 50 case birthday(DateData) 51 case university(SchoolData) 52 case none 53} 54 55struct NameData { 56 let firstName: String 57 let lastName: String 58} 59 60struct DateData { 61 let date: Double 62} 63 64struct SchoolData { 65 let university: String 66}
解決できる指定方法をご教授いただけると幸いです。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。