2017-10-08 3 views
1

プロパティsubrow: IntIndexPathを追加する必要があります。なぜプロパティーrow: Intsection: Intがクラッシュするのですか?カスタムイニシャライザを使用しているときに `Index Row`のプロパティ` var row:Int`と `var section:Int`がクラッシュするのはなぜですか?

import UIKit 

extension IndexPath { 
    init(subrow: Int, row: Int, section: Int) { 
     self.init(indexes: [section, row, subrow]) 
    } 
    var subrow: Int { 
     get { return self[2] } 
     set { return self[2] = newValue } 
    } 
} 

let ip = IndexPath(subrow: 0, row: 1, section: 2) 
print(ip.subrow == 0) // OK 
print(ip.row == 1) // Crash! 
print(ip.section == 2) // Crash! 
+0

注:

あなたが代わりに添字メソッドを使用することができます。 –

答えて

1

特性rowsectionはUIKitフレームワークにおけるIndexPathの拡張 に定義されています。それらは "便利" アクセッサであり、テーブルビューまたはコレクションビューで使用することを意図しています。それは、彼らが唯一の 正確二つの要素持つインデックスパスで使用できるAPIドキュメントから見ることができ

extension IndexPath { 

    /// Initialize for use with `UITableView` or `UICollectionView`. 
    public init(row: Int, section: Int) 

    /// The section of this index path, when used with `UITableView`. 
    /// 
    /// - precondition: The index path must have exactly two elements. 
    public var section: Int 

    /// The row of this index path, when used with `UITableView`. 
    /// 
    /// - precondition: The index path must have exactly two elements. 
    public var row: Int 
} 

UIKit_FoundationExtensions.swift.gybのソースコードを参照してください。セッターで `return`文が冗長であることを

let ip = IndexPath(subrow: 0, row: 1, section: 2) 

print(ip[0]) // 2 
print(ip[1]) // 1 
print(ip[2]) // 0 
+0

しかし、この制限を避けるには? –

+1

@AlexBishop:前提条件がフレームワークに組み込まれているため、回避できません。サブスクリプトアクセサを使用するか、独自のプロパティ 'myrow'、' mysection'を定義することができます –

関連する問題