我一直在尝试在Swift中开发全功能音乐应用程序。我试图查看用swift编写的可用开源音乐应用程序。我发现了一个有用的音乐应用程序(ESTMusicPlayer)但是这个应用程序是用目标C
我使用Swift Interpolablity和Mix-Match功能几乎用MusicListViewContorller.swift取代了MusicListViewContorller.h和MusicListViewContorller.m文件的Objective-C版本。
我已经转换了Objective-C版本:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
if (_delegate && [_delegate respondsToSelector:@selector(playMusicWithSpecialIndex:)]) {
[_delegate playMusicWithSpecialIndex:indexPath.row];
} else {
MusicViewController *musicVC = [MusicViewController sharedInstance];
musicVC.musicTitle = self.navigationItem.title;
musicVC.musicEntities = _musicEntities;
musicVC.specialIndex = indexPath.row;
musicVC.delegate = self;
[self presentToMusicViewWithMusicVC:musicVC];
}
[self updatePlaybackIndicatorWithIndexPath:indexPath];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
要
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
delegate?.playMusicSpecial(indexPath.row)
self.updatePlayBackIndicatorWithIndexPath(indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}
什么是等效的Swift中以下代码的代码片段?
if (_delegate && [_delegate respondsToSelector:@selector(playMusicWithSpecialIndex:)]) {
[_delegate playMusicWithSpecialIndex:indexPath.row];
}
什么是swift中respondToSelector:
的替代代码?
答案 0 :(得分:1)
我们可以通过Optional chaining检查委托实现特定方法。要执行可选链接方法,应该是可选类型。
您可以在协议中定义可选方法。
@objc protocol MyProtocol:class
{
func requiredMethod()
optional func playMusicWithSpecialIndex(index : int)
}
请在协议中查看Optional Method declaration的此链接。
试试这段代码。这可能会对你有帮助。
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if _delegate.playMusicWithSpecialIndex?(indexPath.row) {
//Method Exist
}else{
var musicVC: MusicViewController = MusicViewController.sharedInstance()
musicVC.musicTitle = self.navigationItem.title
musicVC.musicEntities = musicEntities
musicVC.specialIndex = indexPath.row
musicVC.delegate = self
self.presentToMusicViewWithMusicVC(musicVC)
}
self.updatePlaybackIndicatorWithIndexPath(indexPath)
tableView.deselectRowAtIndexPath(indexPath, animated: true)
}