1

Here is code.

var item = self.tabBarController?.tabBar.items?[1] as! UITabBarItem

This causes error like this. "Downcast from 'UITabBarItem?" to 'UITabBarItem' only unwraps optionals; did you men to use '!'?"

And Redundant error. Here is code

class PrivateViewController: UITableViewController, UITableViewDelegate, UITableViewDataSource, UIActionSheetDelegate, MFMailComposeViewControllerDelegate, MFMessageComposeViewControllerDelegate {}

This causes error like this. "Dedundant conformance of 'PrivateViewController' to protocal 'UITableViewDataSource" Anybody who knows solution?

2 Answers2

1

1) In Swift 2 the property items of UITabBar is declared as [UITabBarItem]?. If there are always at least two tab bar items you can write

var item = self.tabBarController!.tabBar.items![1]

as the compiler knows the type. If not use appropriate optional binding.

2) UITableViewController conforms to both UITableViewDelegate and UITableViewDataSource by default. Remove both in the code.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Shouldn’t you unwrap the bar item after the subscript? (`items?[1]!`) Because the subscript access almost certainly returns an optional. – zoul Dec 16 '15 at 18:26
  • I don't think so, otherwise the signature is supposed to be `[UITabBarItem?]?` – vadian Dec 16 '15 at 18:28
  • You’re right! Subscript access doesn’t return an optional, instead it blows up when the index is out of range. – zoul Dec 16 '15 at 18:34
1

Well, UITabBarController’s tab bar items are already typed as UITabBarItem, so there’s no point in casting them to the same type. Which is what the compiler says. The only thing that’s needed is to unwrap the optional, since you don’t get a real UITabBarItem back, but an optional UITabBarItem. If you are sure that there’s a bar item under index 1, you can force-unwrap it: self.tabBarController?.tabBar.items?[1]!.

(By the way, this is a thing called generics that makes a difference from the Objective-C days. In Objective-C, having an array of things would “strip” the type off those things, so we often had to cast them to a precise type. In Swift, the array “keeps” the type of the things stored in it, so when you get an item from the array, the compiler already knows its precise type. And by the way, Apple has introduced a lightweight version of generics for Objective-C in Xcode 7.)

As for your second problem, your class inherits from UITableViewController that already conforms to UITableViewDelegate and UITableViewDataSource, so there’s no point in declaring the conformance again.

Community
  • 1
  • 1
zoul
  • 102,279
  • 44
  • 260
  • 354