2017-06-22 43 views
0

我有一个类MyCell,它有一个委托和一个实例变量tagToIndex。我想在委托人修改它之后打印这个变量。目前我的代码看起来是这样的:如何访问委托函数中的变量?

class MyCell: UITableViewCell, YSSegmentedControlDelegate { 

var tagToIndex: Dictionary<Int,Int>? 

    func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) { 

    tagToIndex[actionButton.tag] = index 

} 


print(tagToIndex) 
} 

的问题是,而不是打印tagToIndex,因为它在委托函数(willPressItemAt)存在,tagToIndex是零。

我也尝试使用回调将索引发送回视图控制器。代码如下所示:

var switchTapIndex: ((Int)->Void)? 

func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) { 


    switchTapIndex?(index) 

} 

不幸的是,当我在单独的函数中打印该值时,该值仍然返回“无”。也许我没有完全理解回调是如何工作的,但我不知道怎么样我做的是不是使用像这样的开关函数内的回调有什么不同:

var switchTapAction : ((Bool)->Void)? 
func switched(_ sender: UISwitch) { 
    print("Switched: \(sender.isOn)") 

    // send the Switch state in a "call back" to the view controller 
    switchTapAction?(sender.isOn) 
} 
+0

,为什么是相关方法之外的'print'语句? – crizzis

+0

[读取代理函数中存在的变量]的可能重复(https://stackoverflow.com/questions/44679900/reading-a-variable-that-exists-in-a-delegate-function) – crizzis

+0

我不仅必须打印它,我必须在课程中的其他位置实际使用该变量。 –

回答

0

在这里,你可能会得到tagToIndex作为零因为你没有初始化该变量。只要尝试,

func segmentedControl(_ segmentedControl: YSSegmentedControl, willPressItemAt index: Int) { 
    if tagToIndex == nil { 
    tagToIndex = Dictionary() 
    } 
     tagToIndex[actionButton.tag] = index 

    } 


    print(tagToIndex) 
    } 
0

下面一行声明tagToIndexDictionary<Int, Int>?类型的属性。换句话说,它是从IntInt的可选Dictionary映射。可选属性默认为nil。既然你还没有初始化它,它是nil

var tagToIndex: Dictionary<Int,Int>?

使该属性非可选通过移除?,并初始化它:如果你要打印它,它已经被委托修改后

var tagToIndex: Dictionary<Int,Int> = [:]