question
stringlengths
11
28.2k
answer
stringlengths
26
27.7k
tag
stringclasses
130 values
question_id
int64
935
78.4M
score
int64
10
5.49k
I'm trying to add UICollectionView to ViewController, and I need to have 3 cells 'per row' without blank space between cells (it should look like a grid). Cell width should be one third of screen size, so I thought that the layout.item width should be the same. But then I get this: If I reduce that size (by 7 or 8 pixels e.g.), it's better, but the third cell in row is not completely visible, and I still have that blank space (top & bottom, and left & right) . class ViewController: UIViewController, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource { var collectionView: UICollectionView? var screenSize: CGRect! var screenWidth: CGFloat! var screenHeight: CGFloat! override func viewDidLoad() { super.viewDidLoad() screenSize = UIScreen.mainScreen().bounds screenWidth = screenSize.width screenHeight = screenSize.height // Do any additional setup after loading the view, typically from a nib let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0) layout.itemSize = CGSize(width: screenWidth / 3, height: screenWidth / 3) collectionView = UICollectionView(frame: self.view.frame, collectionViewLayout: layout) collectionView!.dataSource = self collectionView!.delegate = self collectionView!.registerClass(CollectionViewCell.self, forCellWithReuseIdentifier: "CollectionViewCell") collectionView!.backgroundColor = UIColor.greenColor() self.view.addSubview(collectionView!) } func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int { return 1 } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return 20 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("CollectionViewCell", forIndexPath: indexPath) as CollectionViewCell cell.backgroundColor = UIColor.whiteColor() cell.layer.borderColor = UIColor.blackColor().CGColor cell.layer.borderWidth = 0.5 cell.frame.size.width = screenWidth / 3 cell.frame.size.height = screenWidth / 3 cell.textLabel?.text = "\(indexPath.section):\(indexPath.row)" return cell } }
Add these 2 lines layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 So you have: // Do any additional setup after loading the view, typically from a nib. let layout: UICollectionViewFlowLayout = UICollectionViewFlowLayout() layout.sectionInset = UIEdgeInsets(top: 20, left: 0, bottom: 10, right: 0) layout.itemSize = CGSize(width: screenWidth/3, height: screenWidth/3) layout.minimumInteritemSpacing = 0 layout.minimumLineSpacing = 0 collectionView!.collectionViewLayout = layout That will remove all the spaces and give you a grid layout: If you want the first column to have a width equal to the screen width then add the following function: func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { if indexPath.row == 0 { return CGSize(width: screenWidth, height: screenWidth/3) } return CGSize(width: screenWidth/3, height: screenWidth/3); } Grid layout will now look like (I've also added a blue background to first cell):
Swift
28,325,277
166
Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface. With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide member variables or constants and there is no dynamic dispatch. An example of this technique would be: protocol Employee { var annualSalary: Int {get} } extension Employee { var biweeklySalary: Int { return self.annualSalary / 26 } func logSalary() { print("$\(self.annualSalary) per year or $\(self.biweeklySalary) biweekly") } } struct SoftwareEngineer: Employee { var annualSalary: Int func logSalary() { print("overridden") } } let sarah = SoftwareEngineer(annualSalary: 100000) sarah.logSalary() // prints: overridden (sarah as Employee).logSalary() // prints: $100000 per year or $3846 biweekly Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol. Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again. Most importantly, notice that there is no dynamic dispatch. When logSalary is called on the instance that is stored as a SoftwareEngineer it calls the overridden version of the method. When logSalary is called on the instance after it has been cast to an Employee, it calls the original implementation (it doesn't not dynamically dispatch to the overridden version even though the instance is actually a Software Engineer. For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift
Swift
24,110,396
166
I'm trying to get path to Documents folder with code: var documentsPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory:0,NSSearchPathDomainMask:0,true) but Xcode gives error: Cannot convert expression's type 'AnyObject[]!' to type 'NSSearchPathDirectory' I'm trying to understand what is wrong in the code.
Apparently, the compiler thinks NSSearchPathDirectory:0 is an array, and of course it expects the type NSSearchPathDirectory instead. Certainly not a helpful error message. But as to the reasons: First, you are confusing the argument names and types. Take a look at the function definition: func NSSearchPathForDirectoriesInDomains( directory: NSSearchPathDirectory, domainMask: NSSearchPathDomainMask, expandTilde: Bool) -> AnyObject[]! directory and domainMask are the names, you are using the types, but you should leave them out for functions anyway. They are used primarily in methods. Also, Swift is strongly typed, so you shouldn't just use 0. Use the enum's value instead. And finally, it returns an array, not just a single path. So that leaves us with (updated for Swift 2.0): let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] and for Swift 3: let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
Swift
24,055,146
166
Is is possible to build views with SwiftUI side by side with an existing UIKit application? I have an existing application written in Objective-C. I've begun migrating to Swift 5. I'm wondering if I can use SwiftUI alongside my existing UIKit .xib views. That is to say I want some views built with SwiftUI and some other views built with UIKit in the same app. Not mixing the two of course. SomeObjCSwiftProject/ SwiftUIViewController.swift SwiftUIView.xib UIKitViewController.swift UIKitView.xib Working alongside each other
edit 05/06/19: Added information about UIHostingController as suggested by @Departamento B in his answer. Credits go to him! Using SwiftUI within UIKit One can use SwiftUI components in existing UIKit environments by wrapping a SwiftUI View into a UIHostingController like this: let swiftUIView = SomeSwiftUIView() // swiftUIView is View let viewCtrl = UIHostingController(rootView: swiftUIView) It's also possible to override UIHostingController and customize it to one's needs, e. g. by setting the preferredStatusBarStyle manually if it doesn't work via SwiftUI as expected. UIHostingController is documented here. Using UIKit within SwiftUI If an existing UIKit view should be used in a SwiftUI environment, the UIViewRepresentable protocol is there to help! It is documented here and can be seen in action in this official Apple tutorial. Compatibility Please note that you cannot use SwiftUI on iOS versions < iOS 13, as SwiftUI is only available on iOS 13 and above. See this post for more information. If you want to use SwiftUI in a project with a target below iOS 13, you need to tag your SwiftUI structs with @available(iOS 13.0.0, *) attribute.
Swift
56,433,826
165
I've been experimenting with UITextField and how to work with it's cursor position. I've found a number of relation Objective-C answers, as in Getting the cursor position of UITextField in ios Control cursor position in UITextField UITextField get currently edited word But since I am working with Swift, I wanted to learn how to get the current cursor location and also set it in Swift. The answer below is the the result of my experimentation and translation from Objective-C.
The following content applies to both UITextField and UITextView. Useful information The very beginning of the text field text: let startPosition: UITextPosition = textField.beginningOfDocument The very end of the text field text: let endPosition: UITextPosition = textField.endOfDocument The currently selected range: let selectedRange: UITextRange? = textField.selectedTextRange Get cursor position if let selectedRange = textField.selectedTextRange { let cursorPosition = textField.offset(from: textField.beginningOfDocument, to: selectedRange.start) print("\(cursorPosition)") } Set cursor position In order to set the position, all of these methods are actually setting a range with the same start and end values. To the beginning let newPosition = textField.beginningOfDocument textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition) To the end let newPosition = textField.endOfDocument textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition) To one position to the left of the current cursor position // only if there is a currently selected range if let selectedRange = textField.selectedTextRange { // and only if the new position is valid if let newPosition = textField.position(from: selectedRange.start, offset: -1) { // set the new position textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition) } } To an arbitrary position Start at the beginning and move 5 characters to the right. let arbitraryValue: Int = 5 if let newPosition = textField.position(from: textField.beginningOfDocument, offset: arbitraryValue) { textField.selectedTextRange = textField.textRange(from: newPosition, to: newPosition) } Related Select all text textField.selectedTextRange = textField.textRange(from: textField.beginningOfDocument, to: textField.endOfDocument) Select a range of text // Range: 3 to 7 let startPosition = textField.position(from: textField.beginningOfDocument, offset: 3) let endPosition = textField.position(from: textField.beginningOfDocument, offset: 7) if startPosition != nil && endPosition != nil { textField.selectedTextRange = textField.textRange(from: startPosition!, to: endPosition!) } Insert text at the current cursor position textField.insertText("Hello") Notes Use textField.becomeFirstResponder() to give focus to the text field and make the keyboard appear. See this answer for how to get the text at some range. See also How to Create a Range in Swift
Swift
34,922,331
165
I know that the presence of the more view controller (navigation bar) pushes down the UIView by its height. I also know that this height = 44px. I have also discovered that this push down maintains the [self.view].frame.origin.y = 0. So how do I determine the height of this navigation bar, other than just setting it to a constant? Or, shorter version, how do I determine that my UIView is showing with the navigation bar on top? The light bulb started to come on. Unfortunately, I have not discovered a uniform way to correct the problem, as described below. I believe that my whole problem centers on my autoresizingMasks. And the reason I have concluded that is the same symptoms exist, with or without a UIWebView. And that symptom is that everything is peachy for Portrait. For Landscape, the bottom-most UIButton pops down behind the TabBar. For example, on one UIView, I have, from top to bottom: UIView – both springs set (default case) and no struts UIScrollView - If I set the two springs, and clear everything else (like the UIView), then the UIButton intrudes on the object immediately above it. If I clear everything, then UIButton is OK, but the stuff at the very top hides behind the StatusBar Setting only the top strut, the UIButton pops down behind the Tab Bar. UILabel and UIImage next vertically – top strut set, flexible everywhere else Just to complete the picture for the few that have a UIWebView: UIWebView - Struts: top, left, right Springs: both UIButton – nothing set, i.e., flexible everywhere Although my light bulb is dim, there appears to be hope. Please bear with me because I needed more room than that provided for a short reply comment. Thanks for trying to understand what I am really fishing for ... so here goes. 1) Each UIViewController (a TabBar app) has a UIImage, some text and whatever on top. Another common denominator is a UIButton on the bottom. On some of the UIViewControllers I have a UIWebView above the UIButton. So, UIImage, text etc. UIWebView (on SOME) UIButton Surrounding all the above is a UIScrollView. 2) For those that have a UIWebView, its autoresizingMask looks like: — | — ^ | | |—| ←----→ |—| | | V The UIButton's mask has nothing set, i.e., flexible everywhere Within my -viewDidLoad, I call my -repositionSubViews within which I do the following: If there is no UIWebView, I do nothing except center the UIButton that I placed with IB. If I do have a UIWebView, then I determine its *content*Height and set its frame to enclose the entire content. UIScrollView *scrollViewInsideWebView = [[webView_ subviews] lastObject]; webViewContentHeight = scrollViewInsideWebView.contentSize.height; [webView_ setFrame:CGRectMake(webViewOriginX, webViewOriginY, sameWholeViewScrollerWidth, webViewContentHeight)] Once I do that, then I programmatically push the UIButton down so that it ends up placed below the UIWebView. Everything works, until I rotate it from Portrait to Landscape. I call my -repositionSubViews within my -didRotateFromInterfaceOrientation. Why does the content height of my UIWebView not change with rotation?. From Portrait to Landscape, the content width should expand and the content height should shrink. It does visually as it should, but not according to my NSLog. Anyway, with or without a UIWebView, the button I've talked about moves below the TabBar when in Landscape mode but it will not scroll up to be seen. I see it behind the TabBar when I scroll "vigorously", but then it "falls back" behind the TabBar. Bottom line, this last is the reason I've asked about the height of the TabBar and the NavigationBar because the TabBar plants itself at the bottom of the UIView and the NavigationBar pushes the UIView down. Now, I'm going to add a comment or two here because they wouldn't have made sense earlier. With no UIWebView, I leave everything as is as seen by IB. With a UIWebView, I increase the UIWebView's frame.height to its contentHeight and also adjust upward the height of the surrounding UIScrollView that surrounds all the sub-views. Well there you have it.
Do something like this ? NSLog(@"Navframe Height=%f", self.navigationController.navigationBar.frame.size.height); The swift version is located here UPDATE iOS 13 As the statusBarFrame was deprecated in iOS13 you can use this: extension UIViewController { /** * Height of status bar + navigation bar (if navigation bar exist) */ var topbarHeight: CGFloat { return (view.window?.windowScene?.statusBarManager?.statusBarFrame.height ?? 0.0) + (self.navigationController?.navigationBar.frame.height ?? 0.0) } }
Swift
7,312,059
165
I don't have a code to sample or anything, because I have no idea how to do it, but can someone please tell me how to delay a function with swift for a set amount of time?
You can use GCD (in the example with a 10 second delay): Swift 2 let triggerTime = (Int64(NSEC_PER_SEC) * 10) dispatch_after(dispatch_time(DISPATCH_TIME_NOW, triggerTime), dispatch_get_main_queue(), { () -> Void in self.functionToCall() }) Swift 3 and Swift 4 DispatchQueue.main.asyncAfter(deadline: .now() + 10.0, execute: { self.functionToCall() }) Swift 5 or Later DispatchQueue.main.asyncAfter(deadline: .now() + 10.0) { //call any function }
Swift
28,821,722
164
I'm trying to make an alert controller with message and input, and then get the value from the input. I've found many good tutorials on how to make the input text field, but I can't get the value from the alert.
Updated for Swift 3 and above: //1. Create the alert controller. let alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .alert) //2. Add the text field. You can configure it however you need. alert.addTextField { (textField) in textField.text = "Some default text" } // 3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .default, handler: { [weak alert] (_) in let textField = alert.textFields![0] // Force unwrapping because we know it exists. print("Text field: \(textField.text)") })) // 4. Present the alert. self.present(alert, animated: true, completion: nil) Swift 2.x Assuming you want an action alert on iOS: //1. Create the alert controller. var alert = UIAlertController(title: "Some Title", message: "Enter a text", preferredStyle: .Alert) //2. Add the text field. You can configure it however you need. alert.addTextFieldWithConfigurationHandler({ (textField) -> Void in textField.text = "Some default text." }) //3. Grab the value from the text field, and print it when the user clicks OK. alert.addAction(UIAlertAction(title: "OK", style: .Default, handler: { [weak alert] (action) -> Void in let textField = alert.textFields![0] as UITextField println("Text field: \(textField.text)") })) // 4. Present the alert. self.presentViewController(alert, animated: true, completion: nil)
Swift
26,567,413
164
I'm trying to create a custom table view cell from a nib. I'm referring to this article here. I'm facing two issues. I created a .xib file with a UITableViewCell object dragged on to it. I created a subclass of UITableViewCell and set it as the cell's class and Cell as the reusable identifier. import UIKit class CustomOneCell: UITableViewCell { @IBOutlet weak var middleLabel: UILabel! @IBOutlet weak var leftLabel: UILabel! @IBOutlet weak var rightLabel: UILabel! required init(coder aDecoder: NSCoder!) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) } override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } } In the UITableViewController I have this code, import UIKit class ViewController: UITableViewController, UITableViewDataSource, UITableViewDelegate { var items = ["Item 1", "Item2", "Item3", "Item4"] override func viewDidLoad() { super.viewDidLoad() } // MARK: - UITableViewDataSource override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell! { let identifier = "Cell" var cell: CustomOneCell! = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell if cell == nil { tableView.registerNib(UINib(nibName: "CustomCellOne", bundle: nil), forCellReuseIdentifier: identifier) cell = tableView.dequeueReusableCellWithIdentifier(identifier) as? CustomOneCell } return cell } } This code complies with no errors but when I run it in the simulator, it looks like this. In the UITableViewController in the storyboard I haven't done anything to the cell. Blank identifier and no subclass. I tried adding the Cell identifier to the prototype cell and ran it again but I get the same result. Another error I faced is, when I tried to implement the following method in the UITableViewController. override func tableView(tableView: UITableView!, willDisplayCell cell: CustomOneCell!, forRowAtIndexPath indexPath: NSIndexPath!) { cell.middleLabel.text = items[indexPath.row] cell.leftLabel.text = items[indexPath.row] cell.rightLabel.text = items[indexPath.row] } As shown in the article I mentioned I changed the cell parameter's type form UITableViewCell to CustomOneCell which is my subclass of UITableViewCell. But I get the following error, Overriding method with selector 'tableView:willDisplayCell:forRowAtIndexPath:' has incompatible type '(UITableView!, CustomOneCell!, NSIndexPath!) -> ()' Anyone have any idea how to resolve these errors? These seemed to work fine in Objective-C. Thank you. EDIT: I just noticed if I change the simulator's orientation to landscape and turn it back to portrait, the cells appear! I still couldn't figure out what's going on. I uploaded an Xcode project here demonstrating the problem if you have time for a quick look.
With Swift 5 and iOS 12.2, you should try the following code in order to solve your problem: CustomCell.swift import UIKit class CustomCell: UITableViewCell { // Link those IBOutlets with the UILabels in your .XIB file @IBOutlet weak var middleLabel: UILabel! @IBOutlet weak var leftLabel: UILabel! @IBOutlet weak var rightLabel: UILabel! } TableViewController.swift import UIKit class TableViewController: UITableViewController { let items = ["Item 1", "Item2", "Item3", "Item4"] override func viewDidLoad() { super.viewDidLoad() tableView.register(UINib(nibName: "CustomCell", bundle: nil), forCellReuseIdentifier: "CustomCell") } // MARK: - UITableViewDataSource override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "CustomCell", for: indexPath) as! CustomCell cell.middleLabel.text = items[indexPath.row] cell.leftLabel.text = items[indexPath.row] cell.rightLabel.text = items[indexPath.row] return cell } } The image below shows a set of constraints that work with the provided code without any constraints ambiguity message from Xcode:
Swift
25,541,786
164
I have a class called MyClass which is a subclass of UIView, that I want to initialize with a XIB file. I am not sure how to initialize this class with the xib file called View.xib class MyClass: UIView { // what should I do here? //init(coder aDecoder: NSCoder) {} ?? }
I tested this code and it works great: class MyClass: UIView { class func instanceFromNib() -> UIView { return UINib(nibName: "nib file name", bundle: nil).instantiateWithOwner(nil, options: nil)[0] as UIView } } Initialise the view and use it like below: var view = MyClass.instanceFromNib() self.view.addSubview(view) OR var view = MyClass.instanceFromNib self.view.addSubview(view()) UPDATE Swift >=3.x & Swift >=4.x class func instanceFromNib() -> UIView { return UINib(nibName: "nib file name", bundle: nil).instantiate(withOwner: nil, options: nil)[0] as! UIView }
Swift
25,513,271
164
I simply want to include my Swift class from another file, like its test PrimeNumberModel.swift import Foundation class PrimeNumberModel { } PrimeNumberModelTests.swift import XCTest import PrimeNumberModel // gives me "No such module 'PrimeNumberModel'" class PrimeNumberModelTests: XCTestCase { let testObject = PrimeNumberModel() // "Use of unresolved identifier 'PrimeNumberModel'" } Both swift files are in the same directory.
I had the same problem, also in my XCTestCase files, but not in the regular project files. To get rid of the: Use of unresolved identifier 'PrimeNumberModel' I needed to import the base module in the test file. In my case, my target is called 'myproject' and I added import myproject and the class was recognised.
Swift
24,029,781
164
I have this ContentView with two different modal views, so I'm using sheet(isPresented:) for both, but as it seems only the last one gets presented. How could I solve this issue? Or is it not possible to use multiple sheets on a view in SwiftUI? struct ContentView: View { @State private var firstIsPresented = false @State private var secondIsPresented = false var body: some View { NavigationView { VStack(spacing: 20) { Button("First modal view") { self.firstIsPresented.toggle() } Button ("Second modal view") { self.secondIsPresented.toggle() } } .navigationBarTitle(Text("Multiple modal view problem"), displayMode: .inline) .sheet(isPresented: $firstIsPresented) { Text("First modal view") } .sheet(isPresented: $secondIsPresented) { Text("Only the second modal view works!") } } } } The above code compiles without warnings (Xcode 11.2.1).
UPD Starting from Xcode 12.5.0 Beta 3 (3 March 2021) this question makes no sense anymore as it is possible now to have multiple .sheet(isPresented:) or .fullScreenCover(isPresented:) in a row and the code presented in the question will work just fine. Nevertheless I find this answer still valid as it organizes the sheets very well and makes the code clean and much more readable - you have one source of truth instead of a couple of independent booleans The actual answer Best way to do it, which also works for iOS 14: enum ActiveSheet: Identifiable { case first, second var id: Int { hashValue } } struct YourView: View { @State var activeSheet: ActiveSheet? var body: some View { VStack { Button { activeSheet = .first } label: { Text("Activate first sheet") } Button { activeSheet = .second } label: { Text("Activate second sheet") } } .sheet(item: $activeSheet) { item in switch item { case .first: FirstView() case .second: SecondView() } } } } Read more here: https://developer.apple.com/documentation/swiftui/view/sheet(item:ondismiss:content:) To hide the sheet just set activeSheet = nil Bonus: If you want your sheet to be fullscreen, then use the very same code, but instead of .sheet write .fullScreenCover
Swift
58,837,007
163
I am trying to find a way to include the PI constant in my Swift code. I already found help in another answer, to import Darwin which I know gives me access to C functions. I also checked the Math package in Darwin and came across the following declaration: var M_PI: Double { get } /* pi */ So, I assume there is a way to use PI in the code, I just don't know how...
With Swift 3 & 4, pi is now defined as a static variable on the floating point number types Double, Float and CGFloat, so no specific imports are required any more: Double.pi Float.pi CGFloat.pi Also note that the actual type of .pi can be inferred by the compiler. So, in situations where it's clear from the context that you are using e.g. CGFloat, you can just use .pi (thanks to @Qbyte and @rickster for pointing that out in the comments). For older versions of Swift: M_PI is originally defined in Darwin but is also contained in Foundation and UIKit, so importing any of these will give you the right access. import Darwin // or Foundation or UIKit let pi = M_PI Note: As noted in the comments, pi can also be used as unicode character in Swift, so you might as well do let π = M_PI alt + p is the shortcut (on US-keyboards) that will create the π unicode character.
Swift
26,324,050
163
I would like to be able to get the current version of my iOS project/app as an NSString object without having to define a constant in a file somewhere. I don't want to change my version value in 2 places. The value needs to be updated when I bump my version in the Project target summary.
You can get the version and build numbers as follows: let version = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String let build = Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String or in Objective-C NSString * version = [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]; NSString * build = [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey]; I have the following methods in a category on UIApplication: extension UIApplication { static var appVersion: String { return Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String } static var appBuild: String { return Bundle.main.object(forInfoDictionaryKey: kCFBundleVersionKey as String) as! String } static var versionBuild: String { let version = appVersion, build = appBuild return version == build ? "v\(version)" : "v\(version)(\(build))" } } Gist: https://gist.github.com/ashleymills/6ec9fce6d7ec2a11af9b Here's the equivalent in Objective-C: + (NSString *) appVersion { return [[NSBundle mainBundle] objectForInfoDictionaryKey: @"CFBundleShortVersionString"]; } + (NSString *) build { return [[NSBundle mainBundle] objectForInfoDictionaryKey: (NSString *)kCFBundleVersionKey]; } + (NSString *) versionBuild { NSString * version = [self appVersion]; NSString * build = [self build]; NSString * versionBuild = [NSString stringWithFormat: @"v%@", version]; if (![version isEqualToString: build]) { versionBuild = [NSString stringWithFormat: @"%@(%@)", versionBuild, build]; } return versionBuild; } Gist: https://gist.github.com/ashleymills/c37efb46c9dbef73d5dd
Swift
7,608,632
163
I get an error that my class doesn't conform the NSObjectProtocol, I don't know what this means. I have implemented all the function from the WCSessionDelegate so that is not the problem. Does somebody know what the issue is? Thanks! import Foundation import WatchConnectivity class BatteryLevel: WCSessionDelegate { var session: WCSession? { didSet { if let session = session { session.delegate = self session.activate() } } } var batteryStatus = 0.0; func getBatteryLevel(){ if WCSession.isSupported() { // 2 session = WCSession.default() // 3 session!.sendMessage(["getBatteryLevel": ""], replyHandler: { (response) -> Void in if (response["batteryLevel"] as? String) != nil { self.batteryStatus = (response["batteryLevel"] as? Double)! * 100 } }, errorHandler: { (error) -> Void in // 6 print(error) }) }} func session(_ session: WCSession, activationDidCompleteWith activationState: WCSessionActivationState, error: Error?) { } func session(_ session: WCSession, didReceiveMessage message: [String : Any]) { } }
See Why in swift we cannot adopt a protocol without inheritance a class from NSObject? In short, WCSessionDelegate itself inherits from NSObjectProtocol therefore you need to implement methods in that protocol, too. The easiest way to implement those methods is to subclass NSObject: class BatteryLevel: NSObject, WCSessionDelegate Note that you are dealing with Obj-C APIs here.
Swift
40,705,591
162
I want to delete the first character from a string. So far, the most succinct thing I've come up with is: display.text = display.text!.substringFromIndex(advance(display.text!.startIndex, 1)) I know we can't index into a string with an Int because of Unicode, but this solution seems awfully verbose. Is there another way that I'm overlooking?
If you're using Swift 3, you can ignore the second section of this answer. Good news is, this is now actually succinct again! Just using String's new remove(at:) method. var myString = "Hello, World" myString.remove(at: myString.startIndex) myString // "ello, World" I like the global dropFirst() function for this. let original = "Hello" // Hello let sliced = dropFirst(original) // ello It's short, clear, and works for anything that conforms to the Sliceable protocol. If you're using Swift 2, this answer has changed. You can still use dropFirst, but not without dropping the first character from your strings characters property and then converting the result back to a String. dropFirst has also become a method, not a function. let original = "Hello" // Hello let sliced = String(original.characters.dropFirst()) // ello Another alternative is to use the suffix function to splice the string's UTF16View. Of course, this has to be converted back to a String afterwards as well. let original = "Hello" // Hello let sliced = String(suffix(original.utf16, original.utf16.count - 1)) // ello All this is to say that the solution I originally provided has turned out not to be the most succinct way of doing this in newer versions of Swift. I recommend falling back on @chris' solution using removeAtIndex() if you're looking for a short and intuitive solution. var original = "Hello" // Hello let removedChar = original.removeAtIndex(original.startIndex) original // ello And as pointed out by @vacawama in the comments below, another option that doesn't modify the original String is to use substringFromIndex. let original = "Hello" // Hello let substring = original.substringFromIndex(advance(original.startIndex, 1)) // ello Or if you happen to be looking to drop a character off the beginning and end of the String, you can use substringWithRange. Just be sure to guard against the condition when startIndex + n > endIndex - m. let original = "Hello" // Hello let newStartIndex = advance(original.startIndex, 1) let newEndIndex = advance(original.endIndex, -1) let substring = original.substringWithRange(newStartIndex..<newEndIndex) // ell The last line can also be written using subscript notation. let substring = original[newStartIndex..<newEndIndex]
Swift
28,445,917
162
I want to replace my CI bash scripts with swift. I can't figure out how to invoke normal terminal command such as ls or xcodebuild #!/usr/bin/env xcrun swift import Foundation // Works println("Test") // Works ls // Fails xcodebuild -workspace myApp.xcworkspace // Fails $ ./script.swift ./script.swift:5:1: error: use of unresolved identifier 'ls' ls // Fails ^ ... etc ....
If you would like to use command line arguments "exactly" as you would in command line (without separating all the arguments), try the following. (This answer improves off of LegoLess's answer and can be used in Swift 5) import Foundation func shell(_ command: String) -> String { let task = Process() let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.arguments = ["-c", command] task.launchPath = "/bin/zsh" task.standardInput = nil task.launch() let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8)! return output } // Example usage: shell("ls -la") Updated / safer function calls 10/23/21: It's possible to run into a runtime error with the above shell command and if so, try swapping to the updated calls below. You'll need to use a do catch statement around the new shell command but hopefully this saves you some time searching for a way to catch unexpected error(s) too. Explanation: Since task.launch() isn't a throwing function it cannot be caught and I was finding it to occasionally simply crash the app when called. After much internet searching, I found the Process class has deprecated task.launch() in favor of a newer function task.run() which does throw errors properly w/out crashing the app. To find out more about the updated methods, please see: https://eclecticlight.co/2019/02/02/scripting-in-swift-process-deprecations/ import Foundation @discardableResult // Add to suppress warnings when you don't want/need a result func safeShell(_ command: String) throws -> String { let task = Process() let pipe = Pipe() task.standardOutput = pipe task.standardError = pipe task.arguments = ["-c", command] task.executableURL = URL(fileURLWithPath: "/bin/zsh") //<--updated task.standardInput = nil try task.run() //<--updated let data = pipe.fileHandleForReading.readDataToEndOfFile() let output = String(data: data, encoding: .utf8)! return output } Examples: // Example usage capturing error: do { try safeShell("ls -la") } catch { print("\(error)") //handle or silence the error here } // Example usage where you don't care about the error and want a nil back instead let result = try? safeShell("ls -la") // Example usage where you don't care about the error or the return value try? safeShell("ls -la") Note: For the last case where you are using try? and aren't using the result, for some reason the compiler still warns you even though it's marked as @discardableResult. This only happens with try?, not try within a do-try-catch block or from within a throwing function. Either way, you can safely ignore it.
Swift
26,971,240
162
Say I want to init a UIView subclass with a String and an Int. How would I do this in Swift if I'm just subclassing UIView? If I just make a custom init() function but the parameters are a String and an Int, it tells me that "super.init() isn't called before returning from initializer". And if I call super.init() I'm told I must use a designated initializer. What should I be using there? The frame version? The coder version? Both? Why?
The init(frame:) version is the default initializer. You must call it only after initializing your instance variables. If this view is being reconstituted from a Nib then your custom initializer will not be called, and instead the init?(coder:) version will be called. Since Swift now requires an implementation of the required init?(coder:), I have updated the example below and changed the let variable declarations to var and optional. In this case, you would initialize them in awakeFromNib() or at some later time. class TestView : UIView { var s: String? var i: Int? init(s: String, i: Int) { self.s = s self.i = i super.init(frame: CGRect(x: 0, y: 0, width: 100, height: 100)) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
Swift
24,339,145
162
The documentation only mentions nested types, but it's not clear if they can be used as namespaces. I haven't found any explicit mentioning of namespaces.
I would describe Swift's namespacing as aspirational; it's been given a lot of advertising that doesn't correspond to any meaningful reality on the ground. For example, the WWDC videos state that if a framework you're importing has a class MyClass and your code has a class MyClass, those names do not conflict because "name mangling" gives them different internal names. In reality, however, they do conflict, in the sense that your own code's MyClass wins, and you can't specify "No no, I mean the MyClass in the framework" — saying TheFramework.MyClass doesn't work (the compiler knows what you mean, but it says it can't find such a class in the framework). My experience is that Swift therefore is not namespaced in the slightest. In turning one of my apps from Objective-C to Swift, I created an embedded framework because it was so easy and cool to do. Importing the framework, however, imports all the Swift stuff in the framework - so presto, once again there is just one namespace and it's global. And there are no Swift headers so you can't hide any names. EDIT: In seed 3, this feature is now starting to come online, in the following sense: if your main code contains MyClass and your framework MyFramework contains MyClass, the former overshadows the latter by default, but you can reach the one in the framework by using the syntax MyFramework.MyClass. Thus we do in fact have the rudiments of a distinct namespace! EDIT 2: In seed 4, we now have access controls! Plus, in one of my apps I have an embedded framework and sure enough, everything was hidden by default and I had to expose all the bits of the public API explicitly. This is a big improvement.
Swift
24,002,821
162
How can I, in my view controller code, differentiate between: presented modally pushed on navigation stack Both presentingViewController and isMovingToParentViewController are YES in both cases, so are not very helpful. What complicates things is that my parent view controller is sometimes modal, on which the to be checked view controller is pushed. It turns out my issue is that I embed my HtmlViewController in a UINavigationController which is then presented. That's why my own attempts and the good answers below were not working. HtmlViewController* termsViewController = [[HtmlViewController alloc] initWithDictionary:dictionary]; UINavigationController* modalViewController; modalViewController = [[UINavigationController alloc] initWithRootViewController:termsViewController]; modalViewController.modalTransitionStyle = UIModalTransitionStyleCoverVertical; [self presentViewController:modalViewController animated:YES completion:nil]; I guess I'd better tell my view controller when it's modal, instead of trying to determine.
Take with a grain of salt, didn't test. - (BOOL)isModal { if([self presentingViewController]) return YES; if([[[self navigationController] presentingViewController] presentedViewController] == [self navigationController]) return YES; if([[[self tabBarController] presentingViewController] isKindOfClass:[UITabBarController class]]) return YES; return NO; }
Swift
23,620,276
162
I am having troubles to understand the difference between both, or the purpose of the convenience init.
Standard init: Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain. convenience init: Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type. per the Swift Documentation In a nutshell, this means that you can use a convenience initializer to make calling a designated initializer faster and more "convenient". So convenience initializers require the use of self.init instead of the super.init you might see in an override of a designated initializer. pseudocode example: init(param1, param2, param3, ... , paramN) { // code } // can call this initializer and only enter one parameter, // set the rest as defaults convenience init(myParamN) { self.init(defaultParam1, defaultParam2, defaultParam3, ... , myParamN) } I use these a lot when creating custom views and such that have long initializers with mainly defaults. The docs do a better job explaining than I can, check them out!
Swift
40,093,484
161
How can I use UserDefaults to save/retrieve strings, booleans and other data in Swift?
ref: NSUserdefault objectTypes Swift 3 and above Store UserDefaults.standard.set(true, forKey: "Key") //Bool UserDefaults.standard.set(1, forKey: "Key") //Integer UserDefaults.standard.set("TEST", forKey: "Key") //setObject Retrieve UserDefaults.standard.bool(forKey: "Key") UserDefaults.standard.integer(forKey: "Key") UserDefaults.standard.string(forKey: "Key") Remove UserDefaults.standard.removeObject(forKey: "Key") Remove all Keys if let appDomain = Bundle.main.bundleIdentifier { UserDefaults.standard.removePersistentDomain(forName: appDomain) } Swift 2 and below Store NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "yourkey") NSUserDefaults.standardUserDefaults().synchronize() Retrieve var returnValue: [NSString]? = NSUserDefaults.standardUserDefaults().objectForKey("yourkey") as? [NSString] Remove NSUserDefaults.standardUserDefaults().removeObjectForKey("yourkey") Register registerDefaults: adds the registrationDictionary to the last item in every search list. This means that after NSUserDefaults has looked for a value in every other valid location, it will look in registered defaults, making them useful as a "fallback" value. Registered defaults are never stored between runs of an application, and are visible only to the application that registers them. Default values from Defaults Configuration Files will automatically be registered. for example detect the app from launch , create the struct for save launch struct DetectLaunch { static let keyforLaunch = "validateFirstlunch" static var isFirst: Bool { get { return UserDefaults.standard.bool(forKey: keyforLaunch) } set { UserDefaults.standard.set(newValue, forKey: keyforLaunch) } } } Register default values on app launch: UserDefaults.standard.register(defaults: [ DetectLaunch.isFirst: true ]) remove the value on app termination: func applicationWillTerminate(_ application: UIApplication) { DetectLaunch.isFirst = false } and check the condition as if DetectLaunch.isFirst { // app launched from first } UserDefaults suite name another one property suite name, mostly its used for App Groups concept, the example scenario I taken from here : The use case is that I want to separate my UserDefaults (different business logic may require Userdefaults to be grouped separately) by an identifier just like Android's SharedPreferences. For example, when a user in my app clicks on logout button, I would want to clear his account related defaults but not location of the the device. let user = UserDefaults(suiteName:"User") use of userDefaults synchronize, the detail info has added in the duplicate answer.
Swift
31,203,241
161
I have a very simple subclass of UITextView that adds the "Placeholder" functionality that you can find native to the Text Field object. Here is my code for the subclass: import UIKit import Foundation @IBDesignable class PlaceholderTextView: UITextView, UITextViewDelegate { @IBInspectable var placeholder: String = "" { didSet { setPlaceholderText() } } private let placeholderColor: UIColor = UIColor.lightGrayColor() private var textColorCache: UIColor! override init(frame: CGRect) { super.init(frame: frame) self.delegate = self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.delegate = self } func textViewDidBeginEditing(textView: UITextView) { if textView.text == placeholder { textView.text = "" textView.textColor = textColorCache } } func textViewDidEndEditing(textView: UITextView) { if textView.text == "" && placeholder != "" { setPlaceholderText() } } func setPlaceholderText() { if placeholder != "" { if textColorCache == nil { textColorCache = self.textColor } self.textColor = placeholderColor self.text = placeholder } } } After changing the class for the UITextView object in the Identity Inspector to PlaceholderTextView, I can set the Placeholder property just fine in the Attribute Inspector. The code works great when running the app, but does not display the placeholder text in the interface builder. I also get the following non-blocking errors (I assume this is why it's not rendering at design time): error: IB Designables: Failed to update auto layout status: Interface Builder Cocoa Touch Tool crashed error: IB Designables: Failed to render instance of PlaceholderTextView: Rendering the view took longer than 200 ms. Your drawing code may suffer from slow performance. I'm not able to figure out what is causing these errors. The second error doesn't make any sense, as I'm not even overriding drawRect(). Any ideas?
There are crash reports generated when Interface Builder Cocoa Touch Tool crashes. Theses are located in ~/Library/Logs/DiagnosticReports and named IBDesignablesAgentCocoaTouch_*.crash. In my case they contained a useful stack-trace that identified the issue in my code.
Swift
27,374,330
161
I'm learning Swift for iOS 8 / OSX 10.10 by following this tutorial, and the term "unwrapped value" is used several times, as in this paragraph (under Objects and Class): When working with optional values, you can write ? before operations like methods, properties, and subscripting. If the value before the ? is nil, everything after the ? is ignored and the value of the whole expression is nil. Otherwise, the optional value is unwrapped, and everything after the ? acts on the unwrapped value. In both cases, the value of the whole expression is an optional value. let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare?.sideLength I don't get it, and searched on the web without luck. What does this means? Edit From Cezary's answer, there's a slight difference between the output of the original code and the final solution (tested on playground) : Original code Cezary's solution The superclass' properties are shown in the output in the second case, while there's an empty object in the first case. Isn't the result supposed to be identical in both case? Related Q&A : What is an optional value in Swift?
First, you have to understand what an Optional type is. An optional type basically means that the variable can be nil. Example: var canBeNil : Int? = 4 canBeNil = nil The question mark indicates the fact that canBeNil can be nil. This would not work: var cantBeNil : Int = 4 cantBeNil = nil // can't do this To get the value from your variable if it is optional, you have to unwrap it. This just means putting an exclamation point at the end. var canBeNil : Int? = 4 println(canBeNil!) Your code should look like this: let optionalSquare: Square? = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare!.sideLength A sidenote: You can also declare optionals to automatically unwrap by using an exclamation mark instead of a question mark. Example: var canBeNil : Int! = 4 print(canBeNil) // no unwrapping needed So an alternative way to fix your code is: let optionalSquare: Square! = Square(sideLength: 2.5, name: "optional square") let sideLength = optionalSquare.sideLength EDIT: The difference that you're seeing is exactly the symptom of the fact that the optional value is wrapped. There is another layer on top of it. The unwrapped version just shows the straight object because it is, well, unwrapped. A quick playground comparison: In the first and second cases, the object is not being automatically unwrapped, so you see two "layers" ({{...}}), whereas in the third case, you see only one layer ({...}) because the object is being automatically unwrapped. The difference between the first case and the second two cases is that the second two cases will give you a runtime error if optionalSquare is set to nil. Using the syntax in the first case, you can do something like this: if let sideLength = optionalSquare?.sideLength { println("sideLength is not nil") } else { println("sidelength is nil") }
Swift
24,034,483
161
What is the difference between the isKind(of aClass: AnyClass) and the isMember(of aClass: AnyClass) functions in Swift? Original Question in Objective-C What is the difference between the isKindOfClass:(Class)aClass and the isMemberOfClass:(Class)aClass functions? I know it is something small like, one is global while the other is an exact class match but I need someone to specify which is which please.
isKindOfClass: returns YES if the receiver is an instance of the specified class or an instance of any class that inherits from the specified class. isMemberOfClass: returns YES if, and only if, the receiver is an instance of the specified class. Most of the time you want to use isKindOfClass: to ensure that your code also works with subclasses. The NSObject Protocol Reference talks a little more about these methods.
Swift
3,653,929
161
I tend to only put the necessities (stored properties, initializers) into my class definitions and move everything else into their own extension, kind of like an extension per logical block that I would group with // MARK: as well. For a UIView subclass for example, I would end up with an extension for layout-related stuff, one for subscribing and handling events and so forth. In these extensions, I inevitably have to override some UIKit methods, e.g. layoutSubviews. I never noticed any issues with this approach -- until today. Take this class hierarchy for example: public class C: NSObject { public func method() { print("C") } } public class B: C { } extension B { override public func method() { print("B") } } public class A: B { } extension A { override public func method() { print("A") } } (A() as A).method() (A() as B).method() (A() as C).method() The output is A B C. That makes little sense to me. I read about Protocol Extensions being statically dispatched, but this ain't a protocol. This is a regular class, and I expect method calls to be dynamically dispatched at runtime. Clearly the call on C should at least be dynamically dispatched and produce C? If I remove the inheritance from NSObject and make C a root class, the compiler complains saying declarations in extensions cannot override yet, which I read about already. But how does having NSObject as a root class change things? Moving both overrides into their class declaration produces A A A as expected, moving only B's produces A B B, moving only A's produces C B C, the last of which makes absolutely no sense to me: not even the one statically typed to A produces the A-output any more! Adding the dynamic keyword to the definition or an override does seem to give me the desired behavior 'from that point in the class hierarchy downwards'... Let's change our example to something a little less constructed, what actually made me post this question: public class B: UIView { } extension B { override public func layoutSubviews() { print("B") } } public class A: B { } extension A { override public func layoutSubviews() { print("A") } } (A() as A).layoutSubviews() (A() as B).layoutSubviews() (A() as UIView).layoutSubviews() We now get A B A. Here I cannot make UIView's layoutSubviews dynamic by any means. Moving both overrides into their class declaration gets us A A A again, only A's or only B's still gets us A B A. dynamic again solves my problems. In theory I could add dynamic to all overrides I ever do but I feel like I'm doing something else wrong here. Is it really wrong to use extensions for grouping code like I do?
Extensions cannot/should not override. It is not possible to override functionality (like properties or methods) in extensions as documented in Apple's Swift Guide. Extensions can add new functionality to a type, but they cannot override existing functionality. Swift Developer Guide The compiler is allowing you to override in the extension for compatibility with Objective-C. But it's actually violating the language directive. That reminded me of Isaac Asimov's "Three Laws of Robotics" 🤖 Extensions (syntactic sugar) define independent methods that receive their own arguments. The function that is called for i.e. layoutSubviews depends on the context the compiler knows about when the code is compiled. UIView inherits from UIResponder which inherits from NSObject so the override in the extension is permitted but should not be. So there's nothing wrong with grouping but you should override in the class not in the extension. Directive Notes You can only override a superclass method i.e. load() initialize()in an extension of a subclass if the method is Objective-C compatible. Therefore we can take a look at why it is allowing you to compile using layoutSubviews. All Swift apps execute inside the Objective-C runtime except for when using pure Swift-only frameworks which allow for a Swift-only runtime. As we found out the Objective-C runtime generally calls two class main methods load() and initialize() automatically when initializing classes in your app’s processes. Regarding the dynamic modifier From the Apple Developer Library (archive.org) You can use the dynamic modifier to require that access to members be dynamically dispatched through the Objective-C runtime. When Swift APIs are imported by the Objective-C runtime, there are no guarantees of dynamic dispatch for properties, methods, subscripts, or initializers. The Swift compiler may still devirtualize or inline member access to optimize the performance of your code, bypassing the Objective-C runtime. 😳 So dynamic can be applied to your layoutSubviews -> UIView Class since it’s represented by Objective-C and access to that member is always used using the Objective-C runtime. That's why the compiler allowing you to use override and dynamic.
Swift
38,213,286
160
I've been looking around for this solution for a while but haven't got any. e.g one solution is self.navigationItem.setRightBarButtonItem(UIBarButtonItem(barButtonSystemItem: .Stop, target: self, action: nil), animated: true) This code will add a button with "stop" image. Just like this, there are other solutions with "search, "refresh" etc. But what if I want to add a button programmatically with the image I want?
Custom button image without setting button frame: You can use init(image: UIImage?, style: UIBarButtonItemStyle, target: Any?, action: Selector?) to initializes a new item using the specified image and other properties. let button1 = UIBarButtonItem(image: UIImage(named: "imagename"), style: .plain, target: self, action: Selector("action")) // action:#selector(Class.MethodName) for swift 3 self.navigationItem.rightBarButtonItem = button1 Check this Apple Doc. reference UIBarButtonItem with custom button image using button frame FOR Swift 3.0 let btn1 = UIButton(type: .custom) btn1.setImage(UIImage(named: "imagename"), for: .normal) btn1.frame = CGRect(x: 0, y: 0, width: 30, height: 30) btn1.addTarget(self, action: #selector(Class.Methodname), for: .touchUpInside) let item1 = UIBarButtonItem(customView: btn1) let btn2 = UIButton(type: .custom) btn2.setImage(UIImage(named: "imagename"), for: .normal) btn2.frame = CGRect(x: 0, y: 0, width: 30, height: 30) btn2.addTarget(self, action: #selector(Class.MethodName), for: .touchUpInside) let item2 = UIBarButtonItem(customView: btn2) self.navigationItem.setRightBarButtonItems([item1,item2], animated: true) FOR Swift 2.0 and older let btnName = UIButton() btnName.setImage(UIImage(named: "imagename"), forState: .Normal) btnName.frame = CGRectMake(0, 0, 30, 30) btnName.addTarget(self, action: Selector("action"), forControlEvents: .TouchUpInside) //.... Set Right/Left Bar Button item let rightBarButton = UIBarButtonItem() rightBarButton.customView = btnName self.navigationItem.rightBarButtonItem = rightBarButton Or simply use init(customView:) like let rightBarButton = UIBarButtonItem(customView: btnName) self.navigationItem.rightBarButtonItem = rightBarButton For System UIBarButtonItem let camera = UIBarButtonItem(barButtonSystemItem: .Camera, target: self, action: Selector("btnOpenCamera")) self.navigationItem.rightBarButtonItem = camera For set more then 1 items use rightBarButtonItems or for left side leftBarButtonItems let btn1 = UIButton() btn1.setImage(UIImage(named: "img1"), forState: .Normal) btn1.frame = CGRectMake(0, 0, 30, 30) btn1.addTarget(self, action: Selector("action1:"), forControlEvents: .TouchUpInside) let item1 = UIBarButtonItem() item1.customView = btn1 let btn2 = UIButton() btn2.setImage(UIImage(named: "img2"), forState: .Normal) btn2.frame = CGRectMake(0, 0, 30, 30) btn2.addTarget(self, action: Selector("action2:"), forControlEvents: .TouchUpInside) let item2 = UIBarButtonItem() item2.customView = btn2 self.navigationItem.rightBarButtonItems = [item1,item2] Using setLeftBarButtonItem or setRightBarButtonItem let btn1 = UIButton() btn1.setImage(UIImage(named: "img1"), forState: .Normal) btn1.frame = CGRectMake(0, 0, 30, 30) btn1.addTarget(self, action: Selector("action1:"), forControlEvents: .TouchUpInside) self.navigationItem.setLeftBarButtonItem(UIBarButtonItem(customView: btn1), animated: true); For swift >= 2.2 action should be #selector(Class.MethodName) ... for e.g. btnName.addTarget(self, action: #selector(Class.MethodName), forControlEvents: .TouchUpInside)
Swift
30,022,780
160
I feel like this might be a common issue and was wondering if there was any common solution to it. Basically, my UITableView has dynamic cell heights for every cell. If I am not at the top of the UITableView and I tableView.reloadData(), scrolling up becomes jumpy. I believe this is due to the fact that because I reloaded data, as I'm scrolling up, the UITableView is recalculating the height for each cell coming into visibility. How do I mitigate that, or how do I only reloadData from a certain IndexPath to the end of the UITableView? Further, when I do manage to scroll all the way to the top, I can scroll back down and then up, no problem with no jumping. This is most likely because the UITableViewCell heights were already calculated.
To prevent jumping you should save heights of cells when they loads and give exact value in tableView:estimatedHeightForRowAtIndexPath: Swift: var cellHeights = [IndexPath: CGFloat]() func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cellHeights[indexPath] = cell.frame.size.height } func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat { return cellHeights[indexPath] ?? UITableView.automaticDimension } Objective C: // declare cellHeightsDictionary NSMutableDictionary *cellHeightsDictionary = @{}.mutableCopy; // declare table dynamic row height and create correct constraints in cells tableView.rowHeight = UITableViewAutomaticDimension; // save height - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath { [cellHeightsDictionary setObject:@(cell.frame.size.height) forKey:indexPath]; } // give exact height value - (CGFloat)tableView:(UITableView *)tableView estimatedHeightForRowAtIndexPath:(NSIndexPath *)indexPath { NSNumber *height = [cellHeightsDictionary objectForKey:indexPath]; if (height) return height.doubleValue; return UITableViewAutomaticDimension; }
Swift
28,244,475
160
I'm trying to conditionally hide a DatePicker in SwiftUI. However, I'm having any issue with mismatched types: var datePicker = DatePicker($datePickerDate) if self.showDatePicker { datePicker = datePicker.hidden() } In this case, datePicker is a DatePicker<EmptyView> type but datePicker.hidden() is a _ModifiedContent<DatePicker<EmptyView>, _HiddenModifier>. So I cannot assign datePicker.hidden() to datePicker. I've tried variations of this and can't seem to find a way that works. Any ideas? UPDATE You can unwrap the _ModifiedContent type to get the underlying type using it's content property. However, this doesn't solve the underlying issue. The content property appears to just be the original, unmodified date picker.
✅ The correct and Simplest Way: You can set the alpha instead, this will preserve the layout space of the view too, and does not force you to add dummy views like the other answers: .opacity(isHidden ? 0 : 1) Demo 💡 Cleaner Way! - Extend original hidden modifier: Also, you can implement a custom function to get the visibility state as an argument: extension View { func hidden(_ shouldHide: Bool) -> some View { opacity(shouldHide ? 0 : 1) } } Now just pass the bool to the modifier: DatePicker($datePickerDate) .hidden(showDatePicker) Note that unlike the original behavior of the hidden modifier, both of these methods preserve the frame of the hiding view. ⛔️ Don't use bad practices !!! All other answers (including the accepted answer by @Jake) use branches instead of dependent code that causes a performance hit. 🛑 Branch example: (from WWDC) ✅ Dependent Code example: Returning logical SAME view for different states causes the SwiftUI to render engine to re-render and initial a view again and cause a performance hit! (see more at this WWDC session)
Swift
56,490,250
159
how to convert Range to Array I tried: let min = 50 let max = 100 let intArray:[Int] = (min...max) get error Range<Int> is not convertible to [Int] I also tried: let intArray:[Int] = [min...max] and let intArray:[Int] = (min...max) as [Int] they don't work either.
You need to create an Array<Int> using the Range<Int> rather than casting it. let intArray: [Int] = Array(min...max)
Swift
32,103,282
159
i've been trying to remove the navigationBars border without luck. I've researched and people seem to tell to set shadowImage and BackgroundImage to nil, but this does not work in my case. My code self.navigationController?.navigationBar.barTintColor = UIColor(rgba: "#4a5866") self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default) self.navigationController?.navigationBar.shadowImage = UIImage(named: "") illustration:
The trouble is with these two lines: self.navigationController?.navigationBar.setBackgroundImage(UIImage(named: ""), forBarMetrics: UIBarMetrics.Default) self.navigationController?.navigationBar.shadowImage = UIImage(named: "") Since you don't have an image with no name, UIImage(named: "") returns nil, which means the default behavior kicks in: When non-nil, a custom shadow image to show instead of the default shadow image. For a custom shadow to be shown, a custom background image must also be set with -setBackgroundImage:forBarMetrics: (if the default background image is used, the default shadow image will be used). You need a truly empty image, so just initialize with UIImage(): self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) self.navigationController?.navigationBar.shadowImage = UIImage()
Swift
26,390,072
159
So I updated to Xcode 6 beta 5 today and noticed I received errors in nearly all of my subclasses of Apple's classes. The error states: Class 'x' does not implement its superclass's required members Here is one example I picked because this class is currently pretty lightweight so it will be easy to post. class InfoBar: SKSpriteNode { //Error message here let team: Team let healthBar: SKSpriteNode init(team: Team, size: CGSize) { self.team = team if self.team == Team.TeamGood { healthBar = SKSpriteNode(color: UIColor.greenColor(), size:size) } else { healthBar = SKSpriteNode(color: UIColor.redColor(), size:size) } super.init(texture:nil, color: UIColor.darkGrayColor(), size: size) self.addChild(healthBar) } } So my question is, why am I receiving this error, and how can I fix it? What is it that I am not implementing? I'm calling a designated initializer.
From an Apple employee on the Developer Forums: "A way to declare to the compiler and the built program that you really don't want to be NSCoding-compatible is to do something like this:" required init(coder: NSCoder) { fatalError("NSCoding not supported") } If you know you don't want to be NSCoding compliant, this is an option. I've taken this approach with a lot of my SpriteKit code, as I know I won't be loading it from a storyboard. Another option you can take which works rather well is to implement the method as a convenience init, like so: convenience required init(coder: NSCoder) { self.init(stringParam: "", intParam: 5) } Note the call to an initializer in self. This allows you to only have to use dummy values for the parameters, as opposed to all non-optional properties, while avoiding throwing a fatal error. The third option of course is to implement the method while calling super, and initialize all of your non-optional properties. You should take this approach if the object is a view being loaded from a storyboard: required init(coder aDecoder: NSCoder!) { foo = "some string" bar = 9001 super.init(coder: aDecoder) }
Swift
25,126,295
159
I am trying to build UIs programmatically with Swift. How can I get this action working? override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let myFirstLabel = UILabel() let myFirstButton = UIButton() myFirstLabel.text = "I made a label on the screen #toogood4you" myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45) myFirstLabel.textColor = UIColor.redColor() myFirstLabel.textAlignment = .Center myFirstLabel.numberOfLines = 5 myFirstLabel.frame = CGRectMake(15, 54, 300, 500) myFirstButton.setTitle("✸", forState: .Normal) myFirstButton.setTitleColor(UIColor.blueColor(), forState: .Normal) myFirstButton.frame = CGRectMake(15, -50, 300, 500) myFirstButton.addTarget(self, action: "pressed", forControlEvents: .TouchUpInside) self.view.addSubview(myFirstLabel) self.view.addSubview(myFirstButton) } func pressed(sender: UIButton!) { var alertView = UIAlertView(); alertView.addButtonWithTitle("Ok"); alertView.title = "title"; alertView.message = "message"; alertView.show(); }
You're just missing the colon at the end of the selector name. Since pressed takes a parameter the colon must be there. Also your pressed function shouldn't be nested inside viewDidLoad. override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. let myFirstLabel = UILabel() let myFirstButton = UIButton() myFirstLabel.text = "I made a label on the screen #toogood4you" myFirstLabel.font = UIFont(name: "MarkerFelt-Thin", size: 45) myFirstLabel.textColor = .red myFirstLabel.textAlignment = .center myFirstLabel.numberOfLines = 5 myFirstLabel.frame = CGRect(x: 15, y: 54, width: 300, height: 500) myFirstButton.setTitle("✸", for: .normal) myFirstButton.setTitleColor(.blue, for: .normal) myFirstButton.frame = CGRect(x: 15, y: -50, width: 300, height: 500) myFirstButton.addTarget(self, action: #selector(pressed), for: .touchUpInside) } @objc func pressed() { var alertView = UIAlertView() alertView.addButtonWithTitle("Ok") alertView.title = "title" alertView.message = "message" alertView.show() } EDIT: Updated to reflect best practices in Swift 2.2. #selector() should be used rather than a literal string which is deprecated.
Swift
24,102,191
159
The idiom for dealing with optionals in Swift seems excessively verbose, if all you want to do is provide a default value in the case where it's nil: if let value = optionalValue { // do something with 'value' } else { // do the same thing with your default value } which involves needlessly duplicating code, or var unwrappedValue if let value = optionalValue { unwrappedValue = value } else { unwrappedValue = defaultValue } which requires unwrappedValue not be a constant. Scala's Option monad (which is basically the same idea as Swift's Optional) has the method getOrElse for this purpose: val myValue = optionalValue.getOrElse(defaultValue) Am I missing something? Does Swift have a compact way of doing that already? Or, failing that, is it possible to define getOrElse in an extension for Optional?
Update Apple has now added a coalescing operator: var unwrappedValue = optionalValue ?? defaultValue The ternary operator is your friend in this case var unwrappedValue = optionalValue ? optionalValue! : defaultValue You could also provide your own extension for the Optional enum: extension Optional { func or(defaultValue: T) -> T { switch(self) { case .None: return defaultValue case .Some(let value): return value } } } Then you can just do: optionalValue.or(defaultValue) However, I recommend sticking to the ternary operator as other developers will understand that much more quickly without having to investigate the or method Note: I started a module to add common helpers like this or on Optional to swift.
Swift
24,099,985
159
I have a protocol RequestType and it has associatedType Model as below. public protocol RequestType: class { associatedtype Model var path: String { get set } } public extension RequestType { public func executeRequest(completionHandler: Result<Model, NSError> -> Void) { request.response(rootKeyPath: rootKeyPath) { [weak self] (response: Response<Model, NSError>) -> Void in completionHandler(response.result) guard let weakSelf = self else { return } if weakSelf.logging { debugPrint(response) } } } } Now I am trying to make a queue of all failed requests. public class RequestEventuallyQueue { static let requestEventuallyQueue = RequestEventuallyQueue() let queue = [RequestType]() } But I get the error on line let queue = [RequestType]() that Protocol RequestType can only be used as a generic constraint because it has Self or associatedType requirements.
Suppose for the moment we adjust your protocol to add a routine that uses the associated type: public protocol RequestType: class { associatedtype Model var path: String { get set } func frobulateModel(aModel: Model) } And Swift were to let you create an array of RequestType the way you want to. I could pass an array of those request types into a function: func handleQueueOfRequests(queue: [RequestType]) { // frobulate All The Things! for request in queue { request.frobulateModel(/* What do I put here? */) } } I get down to the point that I want to frobulate all the things, but I need to know what type of argument to pass into the call. Some of my RequestType entities could take a LegoModel, some could take a PlasticModel, and others could take a PeanutButterAndPeepsModel. Swift is not happy with the ambiguity so it will not let you declare a variable of a protocol that has an associated type. At the same time it makes perfect sense to, for example, create an array of RequestType when we KNOW that all of them use the LegoModel. This seems reasonable, and it is, but you need some way to express that. One way to do that is to create a class (or struct, or enum) that associates a real type with the abstract Model type name: class LegoRequestType: RequestType { typealias Model = LegoModel // Implement protocol requirements here } Now it's entirely reasonable to declare an array of LegoRequestType because if we wanted to frobulate all of them we know we would have to pass in a LegoModel each time. This nuance with Associated Types makes any protocol that uses them special. The Swift Standard Library has Protocols like this most notably Collection or Sequence. To allow you to create an array of things that implement the Collection protocol or a set of things that implement the sequence protocol, the Standard Library employs a technique called "type-erasure" to create the struct types AnyCollection<T> or AnySequence<T>. The type-erasure technique is rather complex to explain in a Stack Overflow answer, but if you search the web there are lots of articles about it. Swift 5.7 Existentials Swift 5.7 introduces explicit existential using the any keyword. This will remove the "Protocol can only be used as a generic constraint…" error, but it doesn't solve the fundamental problem with this example. (Admittedly this example is academic, for demonstration purposes, and likely not useful in real code because of its limitations. But it also demonstrates how explicit existentials aren't a panacea.) Here is the code sample using Swift 5.7 and the any keyword. public protocol RequestType: AnyObject { associatedtype Model var path: String { get set } func frobulateModel(aModel: Model) } func handleQueueOfRequests(queue: [any RequestType]) { // frobulate All The Things! for request in queue { request.frobulateModel(/* What do I put here? */) } } Now our queue contains a collection of existentials and we no longer have the error about the "type cannot be used here because of Self or AssociatedType constraints". But it doesn't fix the underlying problem in this example because the frobulateModel method can still take an arbitrary type (the associated type of the entity conforming to the RequestType protocol). Swift provides other mechanisms that can help compensate for this. In general you'd want constrain the Model value to expose behavior shared by all Models. The frobulateModel method might be made generic and have constraints on the parameter to follow that protocol. Or you could use Swift 5.7's primary associated types (SE-0346) to help constrain the behavior of Models at the protocol level. So yes, explicit existentials can remove the error message that the OP asked about - but they are not a solution for every situation. Also, keep in mind that existentials lead to indirection and that can introduce performance problems. In their WWDC session, Apple cautioned us to use them judiciously.
Swift
36,348,061
158
I'm getting the error ... Command failed due to signal: Segmentation fault: 11 ... when trying to compile my Swift app. I'm using Xcode 6.1, trying to build for an iPhone 5 on iOS 8.1. My Code import UIKit class ViewController: UIViewController { @IBOutlet weak var username: UITextField! @IBAction func signIn(sender: AnyObject) { PFUser.logInWithUsernameInBackground(username.text, password:"mypass") { (user: PFUser!, error: NSError!) -> Void in if user != nil { println("Logged In") } else { func myMethod() { var user = PFUser() user.username = username.text user.password = " " user.signUpInBackgroundWithBlock { (succeeded: Bool!, error: NSError!) -> Void in if error == nil { // Hooray! Let them use the app now. } else { println("Signed Up") } } } println(error) } } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. Parse.setApplicationId("key here") } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } And the error text! CompileSwift normal arm64 /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/ViewController.swift cd /Users/Alec/Desktop/Re-Chat/Re-Chat /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/ViewController.swift /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/AppDelegate.swift -target arm64-apple-ios8.0 -Xllvm -aarch64-use-tbi -target-cpu cyclone -target-abi darwinpcs -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -I /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos -F /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos -F /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat -g -import-objc-header /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/Re-Chat-Bridging-Header.h -module-cache-path /Users/Alec/Library/Developer/Xcode/DerivedData/ModuleCache -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-generated-files.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-own-target-headers.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-all-target-headers.hmap -Xcc -iquote -Xcc /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-project-headers.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos/include -Xcc -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/DerivedSources/arm64 -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/DerivedSources -Xcc -DDEBUG=1 -emit-module-doc-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController~partial.swiftdoc -Onone -module-name Re_Chat -emit-module-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController~partial.swiftmodule -serialize-diagnostics-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.dia -emit-dependencies-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.d -o /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.o 0 swift 0x0000000108145a68 llvm::sys::PrintStackTrace(__sFILE*) + 40 1 swift 0x0000000108145f54 SignalHandler(int) + 452 2 libsystem_platform.dylib 0x00007fff86631f1a _sigtramp + 26 3 libsystem_platform.dylib 0x00007fd0ac1eb010 _sigtramp + 633049360 4 swift 0x00000001075d4517 swift::Lowering::SILGenFunction::emitClosureValue(swift::SILLocation, swift::SILDeclRef, llvm::ArrayRef<swift::Substitution>, swift::AnyFunctionRef) + 1303 5 swift 0x00000001075c599e swift::Lowering::SILGenFunction::visitFuncDecl(swift::FuncDecl*) + 190 6 swift 0x000000010760987c swift::Lowering::SILGenFunction::visitBraceStmt(swift::BraceStmt*) + 380 7 swift 0x000000010760c8e8 swift::ASTVisitor<swift::Lowering::SILGenFunction, void, void, void, void, void, void>::visit(swift::Stmt*) + 152 8 swift 0x000000010760a0a5 swift::Lowering::SILGenFunction::visitIfStmt(swift::IfStmt*) + 757 9 swift 0x000000010760c8f6 swift::ASTVisitor<swift::Lowering::SILGenFunction, void, void, void, void, void, void>::visit(swift::Stmt*) + 166 10 swift 0x00000001076097e8 swift::Lowering::SILGenFunction::visitBraceStmt(swift::BraceStmt*) + 232 11 swift 0x000000010760c8e8 swift::ASTVisitor<swift::Lowering::SILGenFunction, void, void, void, void, void, void>::visit(swift::Stmt*) + 152 12 swift 0x00000001075d52dd swift::Lowering::SILGenFunction::emitClosure(swift::AbstractClosureExpr*) + 205 13 swift 0x00000001075b4234 swift::Lowering::SILGenModule::emitClosure(swift::AbstractClosureExpr*) + 196 14 swift 0x00000001075eef71 (anonymous namespace)::RValueEmitter::visitAbstractClosureExpr(swift::AbstractClosureExpr*, swift::Lowering::SGFContext) + 97 15 swift 0x00000001075e1866 swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 2870 16 swift 0x00000001075e24da swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 6058 17 swift 0x00000001075cfa0b swift::Lowering::SILGenFunction::emitExprInto(swift::Expr*, swift::Lowering::Initialization*) + 235 18 swift 0x00000001075ae824 swift::Lowering::RValueSource::materialize(swift::Lowering::SILGenFunction&) && + 196 19 swift 0x0000000107604a69 swift::Lowering::RValueSource::materialize(swift::Lowering::SILGenFunction&, swift::Lowering::AbstractionPattern, swift::SILType) && + 233 20 swift 0x00000001075f371c swift::Lowering::SILGenFunction::emitInjectOptionalValueInto(swift::SILLocation, swift::Lowering::RValueSource&&, swift::SILValue, swift::Lowering::TypeLowering const&) + 268 21 swift 0x00000001075e9b8d swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 36445 22 swift 0x00000001075e3e2b swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 12539 23 swift 0x00000001075e202b swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 4859 24 swift 0x00000001075cfab6 swift::Lowering::SILGenFunction::emitRValue(swift::Expr*, swift::Lowering::SGFContext) + 22 25 swift 0x00000001075bffc4 (anonymous namespace)::ArgEmitter::emitExpanded(swift::Lowering::RValueSource&&, swift::Lowering::AbstractionPattern) + 836 26 swift 0x00000001075bf582 (anonymous namespace)::ArgEmitter::emit(swift::Lowering::RValueSource&&, swift::Lowering::AbstractionPattern) + 98 27 swift 0x00000001075b7ff8 (anonymous namespace)::CallEmission::apply(swift::Lowering::SGFContext) + 1128 28 swift 0x00000001075b751a swift::Lowering::SILGenFunction::emitApplyExpr(swift::ApplyExpr*, swift::Lowering::SGFContext) + 58 29 swift 0x00000001075e0d81 swift::ASTVisitor<(anonymous namespace)::RValueEmitter, swift::Lowering::RValue, void, void, void, void, void, swift::Lowering::SGFContext>::visit(swift::Expr*, swift::Lowering::SGFContext) + 81 30 swift 0x00000001075ea00d swift::Lowering::SILGenFunction::emitIgnoredExpr(swift::Expr*) + 237 31 swift 0x0000000107609829 swift::Lowering::SILGenFunction::visitBraceStmt(swift::BraceStmt*) + 297 32 swift 0x000000010760c8e8 swift::ASTVisitor<swift::Lowering::SILGenFunction, void, void, void, void, void, void>::visit(swift::Stmt*) + 152 33 swift 0x00000001075d4ee0 swift::Lowering::SILGenFunction::emitFunction(swift::FuncDecl*) + 256 34 swift 0x00000001075b3659 swift::Lowering::SILGenModule::emitFunction(swift::FuncDecl*) + 233 35 swift 0x00000001075cea93 swift::ASTVisitor<SILGenType, void, void, void, void, void, void>::visit(swift::Decl*) + 355 36 swift 0x00000001075cd7eb SILGenType::emitType() + 203 37 swift 0x00000001075c85ae swift::Lowering::SILGenModule::visitNominalTypeDecl(swift::NominalTypeDecl*) + 30 38 swift 0x00000001075b555b swift::Lowering::SILGenModule::emitSourceFile(swift::SourceFile*, unsigned int) + 395 39 swift 0x00000001075b581a swift::SILModule::constructSIL(swift::Module*, swift::SourceFile*, swift::Optional<unsigned int>) + 314 40 swift 0x00000001075b5968 swift::performSILGeneration(swift::SourceFile&, swift::Optional<unsigned int>) + 72 41 swift 0x000000010748be18 frontend_main(llvm::ArrayRef<char const*>, char const*, void*) + 3432 42 swift 0x000000010748996d main + 1677 43 libdyld.dylib 0x00007fff8aa4c5c9 start + 1 Stack dump: 0. Program arguments: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin/swift -frontend -c -primary-file /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/ViewController.swift /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/AppDelegate.swift -target arm64-apple-ios8.0 -Xllvm -aarch64-use-tbi -target-cpu cyclone -target-abi darwinpcs -sdk /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS8.1.sdk -I /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos -F /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos -F /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat -g -import-objc-header /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/Re-Chat-Bridging-Header.h -module-cache-path /Users/Alec/Library/Developer/Xcode/DerivedData/ModuleCache -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/swift-overrides.hmap -Xcc -iquote -Xcc /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-generated-files.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-own-target-headers.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-all-target-headers.hmap -Xcc -iquote -Xcc /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Re-Chat-project-headers.hmap -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Products/Debug-iphoneos/include -Xcc -I/Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/include -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/DerivedSources/arm64 -Xcc -I/Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/DerivedSources -Xcc -DDEBUG=1 -emit-module-doc-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController~partial.swiftdoc -Onone -module-name Re_Chat -emit-module-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController~partial.swiftmodule -serialize-diagnostics-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.dia -emit-dependencies-path /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.d -o /Users/Alec/Library/Developer/Xcode/DerivedData/Re-Chat-awwdkmqavitiqkcdsphwnhzhzzfb/Build/Intermediates/Re-Chat.build/Debug-iphoneos/Re-Chat.build/Objects-normal/arm64/ViewController.o 1. While emitting SIL for 'signIn' at /Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/ViewController.swift:14:15 2. While silgen closureexpr SIL function @_TFFC7Re_Chat14ViewController6signInFS0_FPSs9AnyObject_T_U_FTGSQCSo6PFUser_GSQCSo7NSError__T_ for expression at [/Users/Alec/Desktop/Re-Chat/Re-Chat/Re-Chat/ViewController.swift:16:80 - line:45:9] RangeText="{ (user: PFUser!, error: NSError!) -> Void in if user != nil { // Do stuff after successful login. println("Logged In") } else { func myMethod() { var user = PFUser() user.username = username.text user.password = "" // other fields can be set just like with PFObject user.signUpInBackgroundWithBlock { (succeeded: Bool!, error: NSError!) -> Void in if error == nil { // Hooray! Let them use the app now. } else { println("Signed Up") } } } println("error") } }"
You can get this error when the compiler gets too confused about what's going on in your code. I noticed you have a number of what appear to be functions nested within functions. You might try commenting out some of that at a time to see if the error goes away. That way you can zero in on the problem area. You can't use breakpoints because it's a compile time error, not a run time error.
Swift
26,557,581
158
In my app there is a textField where the user have to put is password in and i want that when he enter a character it change it to '•' how can i do this?
You can achieve this directly in Xcode: The very last checkbox, make sure secure is checked . Or you can do it using code: Identifies whether the text object should hide the text being entered. Declaration optional var secureTextEntry: Bool { get set } Discussion This property is set to false by default. Setting this property to true creates a password-style text object, which hides the text being entered. example: texfield.secureTextEntry = true
Swift
26,064,315
158
In Objective-C, you can define a block's input and output, store one of those blocks that's passed in to a method, then use that block later: // in .h typedef void (^APLCalibrationProgressHandler)(float percentComplete); typedef void (^APLCalibrationCompletionHandler)(NSInteger measuredPower, NSError *error); // in .m @property (strong) APLCalibrationProgressHandler progressHandler; @property (strong) APLCalibrationCompletionHandler completionHandler; - (id)initWithRegion:(CLBeaconRegion *)region completionHandler:(APLCalibrationCompletionHandler)handler { self = [super init]; if(self) { ... _completionHandler = [handler copy]; .. } return self; } - (void)performCalibrationWithProgressHandler:(APLCalibrationProgressHandler)handler { ... self.progressHandler = [handler copy]; ... dispatch_async(dispatch_get_main_queue(), ^{ _completionHandler(0, error); }); ... } So I'm trying to do the equivilant in Swift: var completionHandler:(Float)->Void={} init() { locationManager = CLLocationManager() region = CLBeaconRegion() timer = NSTimer() } convenience init(region: CLBeaconRegion, handler:((Float)->Void)) { self.init() locationManager.delegate = self self.region = region completionHandler = handler rangedBeacons = NSMutableArray() } The compiler doesn't like that declaration of completionHandler. Not that I blame it, but, how do I define a closure that can be set and used later in Swift?
The compiler complains on var completionHandler: (Float)->Void = {} because the right-hand side is not a closure of the appropriate signature, i.e. a closure taking a float argument. The following would assign a "do nothing" closure to the completion handler: var completionHandler: (Float)->Void = { (arg: Float) -> Void in } and this can be shortened to var completionHandler: (Float)->Void = { arg in } due to the automatic type inference. But what you probably want is that the completion handler is initialized to nil in the same way that an Objective-C instance variable is inititialized to nil. In Swift this can be realized with an optional: var completionHandler: ((Float)->Void)? Now the property is automatically initialized to nil ("no value"). In Swift you would use optional binding to check of a the completion handler has a value if let handler = completionHandler { handler(result) } or optional chaining: completionHandler?(result)
Swift
24,603,559
158
This article has been helpful in understanding the new access specifiers in Swift 3. It also gives some examples of different usages of fileprivate and private. My question is - isn't using fileprivate on a function that is going to be used only in this file the same as using private?
fileprivate is now what private used to be in earlier Swift releases: accessible from the same source file. A declaration marked as private can now only be accessed within the lexical scope it is declared in. So private is more restrictive than fileprivate. As of Swift 4, private declarations inside a type are accessible to extensions of the same type if the extension is defined in the same source file. Example (all in one source file): class A { private func foo() {} fileprivate func bar() {} func baz() { foo() bar() } } extension A { func test() { foo() // Swift 3: error: use of unresolved identifier 'foo' // Swift 4: no error because extension is in same source file bar() } } let a = A() a.foo() // error: 'foo' is inaccessible due to 'private' protection level a.bar() The private foo method is accessible only within the scope of the class A { ... } definition. It is not even accessible from an extension to the type (in Swift 3, see the second note below for changes in Swift 4). The file-private bar method is accessible from the same source file. Notes: The proposal SE-0159 – Fix Private Access Levels suggested to revert to the Swift 2 semantics in Swift 4. After a lengthy and controversial discussion on the swift-evolution mailing list, the proposal was rejected. The proposal SE-0169 – Improve Interaction Between private Declarations and Extensions suggests to make private declarations inside a type accessible to extensions of the same type if the extension is defined in the same source file. This proposal was accepted and implemented in Swift 4.
Swift
39,027,250
157
I am setting a background image to view controller. But also i want to add blur effect to this background. How can I do this? I am setting background with following code: self.view.backgroundColor = UIColor(patternImage: UIImage(named: "testBg")!) I found on internet for blur imageview how can i implement this to my background? var darkBlur = UIBlurEffect(style: UIBlurEffectStyle.Dark) // 2 var blurView = UIVisualEffectView(effect: darkBlur) blurView.frame = imageView.bounds // 3 imageView.addSubview(blurView)
I have tested this code and it's working fine: let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) For Swift 3.0: let blurEffect = UIBlurEffect(style: UIBlurEffectStyle.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) For Swift 4.0: let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.dark) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] view.addSubview(blurEffectView) Here you can see result: Or you can use this lib for that: https://github.com/FlexMonkey/Blurable
Swift
30,953,201
157
I decided to continue my remaining project with Swift. When I add the custom class (subclass of UIViewcontroller) to my storyboard view controller and load the project, the app crashes suddenly with the following error: fatal error: use of unimplemented initializer 'init(coder:)' for class This is a code: import UIKit class TestViewController: UIViewController { init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) { super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil) // Custom initialization } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) { // Get the new view controller using [segue destinationViewController]. // Pass the selected object to the new view controller. } */ } Please suggest something
Issue This is caused by the absence of the initializer init?(coder aDecoder: NSCoder) on the target UIViewController. That method is required because instantiating a UIViewController from a UIStoryboard calls it. To see how we initialize a UIViewController from a UIStoryboard, please take a look here Why is this not a problem with Objective-C? Because Objective-C automatically inherits all the required UIViewController initializers. Why doesn't Swift automatically inherit the initializers? Swift by default does not inherit the initializers due to safety. But it will inherit all the initializers from the superclass if all the properties have a value (or optional) and the subclass has not defined any designated initializers. Solution 1. First method Manually implementing init?(coder aDecoder: NSCoder) on the target UIViewController required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } 2. Second method Removing init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: NSBundle?) on your target UIViewController will inherit all of the required initializers from the superclass as Dave Wood pointed on his answer below
Swift
24,036,393
157
Can someone please instruct me on the easiest way to change the font size for the text in a UITableView section header? I have the section titles implemented using the following method: - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section Then, I understand how to successfully change the section header height using this method: - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section I have the UITableView cells populated using this method: - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath However, I'm stuck as to how to actually increase the font size - or for that matter the font style - of the section header text? Can someone please assist? Thanks.
Another way to do this would be to respond to the UITableViewDelegate method willDisplayHeaderView. The passed view is actually an instance of a UITableViewHeaderFooterView. The example below changes the font, and also centers the title text vertically and horizontally within the cell. Note that you should also respond to heightForHeaderInSection to have any changes to your header's height accounted for in the layout of the table view. (That is, if you decide to change the header height in this willDisplayHeaderView method.) You could then respond to the titleForHeaderInSection method to reuse this configured header with different section titles. Objective-C - (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section { UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view; header.textLabel.textColor = [UIColor redColor]; header.textLabel.font = [UIFont boldSystemFontOfSize:18]; CGRect headerFrame = header.frame; header.textLabel.frame = headerFrame; header.textLabel.textAlignment = NSTextAlignmentCenter; } Swift 1.2 (Note: if your view controller is a descendant of a UITableViewController, this would need to be declared as override func.) override func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { let header:UITableViewHeaderFooterView = view as! UITableViewHeaderFooterView header.textLabel.textColor = UIColor.redColor() header.textLabel.font = UIFont.boldSystemFontOfSize(18) header.textLabel.frame = header.frame header.textLabel.textAlignment = NSTextAlignment.Center } Swift 3.0 This code also ensures that the app doesn't crash if your header view is something other than a UITableViewHeaderFooterView: override func tableView(_ tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) { guard let header = view as? UITableViewHeaderFooterView else { return } header.textLabel?.textColor = UIColor.red header.textLabel?.font = UIFont.boldSystemFont(ofSize: 18) header.textLabel?.frame = header.bounds header.textLabel?.textAlignment = .center }
Swift
19,802,336
157
When I run my swift 3.2 code with Xcode 9 beta 4 this is the error I get: *** Terminating app due to uncaught exception 'com.firebase.core', reason: '[FIRApp configure]; (FirebaseApp.configure() in Swift) could not find a valid GoogleService-Info.plist in your project. Please download one from https://console.firebase.google.com/.' I already have a GoogleService-Info.plist file that is named exactly like it should and it is valid. Is there any trial to firebase or something like that?
Remove the Google-Info.plist file from your project and try to add it from your project folder's option menu. EDIT: this is how you remove a plist file Xcode 10 Error: Multiple commands produce
Swift
45,317,777
156
Why doesn't this Swift code compile? protocol P { } struct S: P { } let arr:[P] = [ S() ] extension Array where Element : P { func test<T>() -> [T] { return [] } } let result : [S] = arr.test() The compiler says: "Type P does not conform to protocol P" (or, in later versions of Swift, "Using 'P' as a concrete type conforming to protocol 'P' is not supported."). Why not? This feels like a hole in the language, somehow. I realize that the problem stems from declaring the array arr as an array of a protocol type, but is that an unreasonable thing to do? I thought protocols were there exactly to help supply structs with something like a type hierarchy?
Why don't protocols conform to themselves? Allowing protocols to conform to themselves in the general case is unsound. The problem lies with static protocol requirements. These include: static methods and properties Initialisers Associated types (although these currently prevent the use of a protocol as an actual type) We can access these requirements on a generic placeholder T where T : P – however we cannot access them on the protocol type itself, as there's no concrete conforming type to forward onto. Therefore we cannot allow T to be P. Consider what would happen in the following example if we allowed the Array extension to be applicable to [P]: protocol P { init() } struct S : P {} struct S1 : P {} extension Array where Element : P { mutating func appendNew() { // If Element is P, we cannot possibly construct a new instance of it, as you cannot // construct an instance of a protocol. append(Element()) } } var arr: [P] = [S(), S1()] // error: Using 'P' as a concrete type conforming to protocol 'P' is not supported arr.appendNew() We cannot possibly call appendNew() on a [P], because P (the Element) is not a concrete type and therefore cannot be instantiated. It must be called on an array with concrete-typed elements, where that type conforms to P. It's a similar story with static method and property requirements: protocol P { static func foo() static var bar: Int { get } } struct SomeGeneric<T : P> { func baz() { // If T is P, what's the value of bar? There isn't one – because there's no // implementation of bar's getter defined on P itself. print(T.bar) T.foo() // If T is P, what method are we calling here? } } // error: Using 'P' as a concrete type conforming to protocol 'P' is not supported SomeGeneric<P>().baz() We cannot talk in terms of SomeGeneric<P>. We need concrete implementations of the static protocol requirements (notice how there are no implementations of foo() or bar defined in the above example). Although we can define implementations of these requirements in a P extension, these are defined only for the concrete types that conform to P – you still cannot call them on P itself. Because of this, Swift just completely disallows us from using a protocol as a type that conforms to itself – because when that protocol has static requirements, it doesn't. Instance protocol requirements aren't problematic, as you must call them on an actual instance that conforms to the protocol (and therefore must have implemented the requirements). So when calling a requirement on an instance typed as P, we can just forward that call onto the underlying concrete type's implementation of that requirement. However making special exceptions for the rule in this case could lead to surprising inconsistencies in how protocols are treated by generic code. Although that being said, the situation isn't too dissimilar to associatedtype requirements – which (currently) prevent you from using a protocol as a type. Having a restriction that prevents you from using a protocol as a type that conforms to itself when it has static requirements could be an option for a future version of the language Edit: And as explored below, this does look like what the Swift team are aiming for. @objc protocols And in fact, actually that's exactly how the language treats @objc protocols. When they don't have static requirements, they conform to themselves. The following compiles just fine: import Foundation @objc protocol P { func foo() } class C : P { func foo() { print("C's foo called!") } } func baz<T : P>(_ t: T) { t.foo() } let c: P = C() baz(c) baz requires that T conforms to P; but we can substitute in P for T because P doesn't have static requirements. If we add a static requirement to P, the example no longer compiles: import Foundation @objc protocol P { static func bar() func foo() } class C : P { static func bar() { print("C's bar called") } func foo() { print("C's foo called!") } } func baz<T : P>(_ t: T) { t.foo() } let c: P = C() baz(c) // error: Cannot invoke 'baz' with an argument list of type '(P)' So one workaround to to this problem is to make your protocol @objc. Granted, this isn't an ideal workaround in many cases, as it forces your conforming types to be classes, as well as requiring the Obj-C runtime, therefore not making it viable on non-Apple platforms such as Linux. But I suspect that this limitation is (one of) the primary reasons why the language already implements 'protocol without static requirements conforms to itself' for @objc protocols. Generic code written around them can be significantly simplified by the compiler. Why? Because @objc protocol-typed values are effectively just class references whose requirements are dispatched using objc_msgSend. On the flip side, non-@objc protocol-typed values are more complicated, as they carry around both value and witness tables in order to both manage the memory of their (potentially indirectly stored) wrapped value and to determine what implementations to call for the different requirements, respectively. Because of this simplified representation for @objc protocols, a value of such a protocol type P can share the same memory representation as a 'generic value' of type some generic placeholder T : P, presumably making it easy for the Swift team to allow the self-conformance. The same isn't true for non-@objc protocols however as such generic values don't currently carry value or protocol witness tables. However this feature is intentional and is hopefully to be rolled out to non-@objc protocols, as confirmed by Swift team member Slava Pestov in the comments of SR-55 in response to your query about it (prompted by this question): Matt Neuburg added a comment - 7 Sep 2017 1:33 PM This does compile: @objc protocol P {} class C: P {} func process<T: P>(item: T) -> T { return item } func f(image: P) { let processed: P = process(item:image) } Adding @objc makes it compile; removing it makes it not compile again. Some of us over on Stack Overflow find this surprising and would like to know whether that's deliberate or a buggy edge-case. Slava Pestov added a comment - 7 Sep 2017 1:53 PM It's deliberate – lifting this restriction is what this bug is about. Like I said it's tricky and we don't have any concrete plans yet. So hopefully it's something that language will one day support for non-@objc protocols as well. But what current solutions are there for non-@objc protocols? Implementing extensions with protocol constraints In Swift 3.1, if you want an extension with a constraint that a given generic placeholder or associated type must be a given protocol type (not just a concrete type that conforms to that protocol) – you can simply define this with an == constraint. For example, we could write your array extension as: extension Array where Element == P { func test<T>() -> [T] { return [] } } let arr: [P] = [S()] let result: [S] = arr.test() Of course, this now prevents us from calling it on an array with concrete type elements that conform to P. We could solve this by just defining an additional extension for when Element : P, and just forward onto the == P extension: extension Array where Element : P { func test<T>() -> [T] { return (self as [P]).test() } } let arr = [S()] let result: [S] = arr.test() However it's worth noting that this will perform an O(n) conversion of the array to a [P], as each element will have to be boxed in an existential container. If performance is an issue, you can simply solve this by re-implementing the extension method. This isn't an entirely satisfactory solution – hopefully a future version of the language will include a way to express a 'protocol type or conforms to protocol type' constraint. Prior to Swift 3.1, the most general way of achieving this, as Rob shows in his answer, is to simply build a wrapper type for a [P], which you can then define your extension method(s) on. Passing a protocol-typed instance to a constrained generic placeholder Consider the following (contrived, but not uncommon) situation: protocol P { var bar: Int { get set } func foo(str: String) } struct S : P { var bar: Int func foo(str: String) {/* ... */} } func takesConcreteP<T : P>(_ t: T) {/* ... */} let p: P = S(bar: 5) // error: Cannot invoke 'takesConcreteP' with an argument list of type '(P)' takesConcreteP(p) We cannot pass p to takesConcreteP(_:), as we cannot currently substitute P for a generic placeholder T : P. Let's take a look at a couple of ways in which we can solve this problem. 1. Opening existentials Rather than attempting to substitute P for T : P, what if we could dig into the underlying concrete type that the P typed value was wrapping and substitute that instead? Unfortunately, this requires a language feature called opening existentials, which currently isn't directly available to users. However, Swift does implicitly open existentials (protocol-typed values) when accessing members on them (i.e it digs out the runtime type and makes it accessible in the form of a generic placeholder). We can exploit this fact in a protocol extension on P: extension P { func callTakesConcreteP/*<Self : P>*/(/*self: Self*/) { takesConcreteP(self) } } Note the implicit generic Self placeholder that the extension method takes, which is used to type the implicit self parameter – this happens behind the scenes with all protocol extension members. When calling such a method on a protocol typed value P, Swift digs out the underlying concrete type, and uses this to satisfy the Self generic placeholder. This is why we're able to call takesConcreteP(_:) with self – we're satisfying T with Self. This means that we can now say: p.callTakesConcreteP() And takesConcreteP(_:) gets called with its generic placeholder T being satisfied by the underlying concrete type (in this case S). Note that this isn't "protocols conforming to themselves", as we're substituting a concrete type rather than P – try adding a static requirement to the protocol and seeing what happens when you call it from within takesConcreteP(_:). If Swift continues to disallow protocols from conforming to themselves, the next best alternative would be implicitly opening existentials when attempting to pass them as arguments to parameters of generic type – effectively doing exactly what our protocol extension trampoline did, just without the boilerplate. However note that opening existentials isn't a general solution to the problem of protocols not conforming to themselves. It doesn't deal with heterogenous collections of protocol-typed values, which may all have different underlying concrete types. For example, consider: struct Q : P { var bar: Int func foo(str: String) {} } // The placeholder `T` must be satisfied by a single type func takesConcreteArrayOfP<T : P>(_ t: [T]) {} // ...but an array of `P` could have elements of different underlying concrete types. let array: [P] = [S(bar: 1), Q(bar: 2)] // So there's no sensible concrete type we can substitute for `T`. takesConcreteArrayOfP(array) For the same reasons, a function with multiple T parameters would also be problematic, as the parameters must take arguments of the same type – however if we have two P values, there's no way we can guarantee at compile time that they both have the same underlying concrete type. In order to solve this problem, we can use a type eraser. 2. Build a type eraser As Rob says, a type eraser, is the most general solution to the problem of protocols not conforming to themselves. They allow us to wrap a protocol-typed instance in a concrete type that conforms to that protocol, by forwarding the instance requirements to the underlying instance. So, let's build a type erasing box that forwards P's instance requirements onto an underlying arbitrary instance that conforms to P: struct AnyP : P { private var base: P init(_ base: P) { self.base = base } var bar: Int { get { return base.bar } set { base.bar = newValue } } func foo(str: String) { base.foo(str: str) } } Now we can just talk in terms of AnyP instead of P: let p = AnyP(S(bar: 5)) takesConcreteP(p) // example from #1... let array = [AnyP(S(bar: 1)), AnyP(Q(bar: 2))] takesConcreteArrayOfP(array) Now, consider for a moment just why we had to build that box. As we discussed early, Swift needs a concrete type for cases where the protocol has static requirements. Consider if P had a static requirement – we would have needed to implement that in AnyP. But what should it have been implemented as? We're dealing with arbitrary instances that conform to P here – we don't know about how their underlying concrete types implement the static requirements, therefore we cannot meaningfully express this in AnyP. Therefore, the solution in this case is only really useful in the case of instance protocol requirements. In the general case, we still cannot treat P as a concrete type that conforms to P.
Swift
33,112,559
156
I have created a custom UICollectionViewCell in Interface Builder, binded views on it to the class, and then when I want to use and set a string to the label on the string, tha label has a nil value. override func viewDidLoad() { super.viewDidLoad() // Register cell classes self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls") } override func collectionView(collectionView: UICollectionView!, cellForItemAtIndexPath indexPath: NSIndexPath!) -> UICollectionViewCell! { var cell: LeftMenuCollectionViewCell cell = collectionView.dequeueReusableCellWithReuseIdentifier("ls", forIndexPath: indexPath) as LeftMenuCollectionViewCell println(cell.label) // <- this is nil, why?? cell.label.text = "asd" return cell } And the subclassed cell: class LeftMenuCollectionViewCell: UICollectionViewCell { @IBOutlet weak var imageView: UIImageView! @IBOutlet weak var label: UILabel! @IBOutlet weak var activityIndicatorView: UIActivityIndicatorView! }
I am calling self.collectionView.registerClass(LeftMenuCollectionViewCell.self, forCellWithReuseIdentifier: "ls") again. If you are using a storyboard you don't want to call this. It will overwrite what you have in your storyboard. If you still have the problem check wether reuseIdentifier is same in dequeueReusableCellWithReuseIdentifier and in storyboard.
Swift
25,165,195
156
Given an array of Swift numeric values, how can I find the minimum and maximum values? I've so far got a simple (but potentially expensive) way: var myMax = sort(myArray,>)[0] And how I was taught to do it at school: var myMax = 0 for i in 0..myArray.count { if (myArray[i] > myMax){myMax = myArray[i]} } Is there a better way to get the minimum or maximum value from an integer Array in Swift? Ideally something that's one line such as Ruby's .min and .max.
Given: let numbers = [1, 2, 3, 4, 5] Swift 3: numbers.min() // equals 1 numbers.max() // equals 5 Swift 2: numbers.minElement() // equals 1 numbers.maxElement() // equals 5
Swift
24,036,514
156
How do I set bold and italic on UILabel of iPhone/iPad? I searched the forum but nothing helped me. Could anyone help me?
Don't try to play with the font names. Using the font descriptor you need no names: UILabel * label = [[UILabel alloc] init]; // use your label object instead of this UIFontDescriptor * fontD = [label.font.fontDescriptor fontDescriptorWithSymbolicTraits:UIFontDescriptorTraitBold | UIFontDescriptorTraitItalic]; label.font = [UIFont fontWithDescriptor:fontD size:0]; size:0 means 'keep the size as is' With Swift try the following extension: extension UIFont { func withTraits(traits:UIFontDescriptorSymbolicTraits...) -> UIFont { let descriptor = self.fontDescriptor() .fontDescriptorWithSymbolicTraits(UIFontDescriptorSymbolicTraits(traits)) return UIFont(descriptor: descriptor, size: 0) } func boldItalic() -> UIFont { return withTraits(.TraitBold, .TraitItalic) } } Then you may use it this way: myLabel.font = myLabel.font.boldItalic() or even add additional traits like Condensed: myLabel.font = myLabel.font.withTraits(.TraitCondensed, .TraitBold, .TraitItalic) Update for Swift 4: extension UIFont { var bold: UIFont { return with(traits: .traitBold) } // bold var italic: UIFont { return with(traits: .traitItalic) } // italic var boldItalic: UIFont { return with(traits: [.traitBold, .traitItalic]) } // boldItalic func with(traits: UIFontDescriptorSymbolicTraits) -> UIFont { guard let descriptor = self.fontDescriptor.withSymbolicTraits(traits) else { return self } // guard return UIFont(descriptor: descriptor, size: 0) } // with(traits:) } // extension Use it as follows: myLabel.font = myLabel.font.bold or myLabel.font = myLabel.font.italic or myLabel.font = myLabel.font.with(traits: [ .traitBold, .traitCondensed ]) Update for Swift 5 extension UIFont { var bold: UIFont { return with(.traitBold) } var italic: UIFont { return with(.traitItalic) } var boldItalic: UIFont { return with([.traitBold, .traitItalic]) } func with(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont { guard let descriptor = self.fontDescriptor.withSymbolicTraits(UIFontDescriptor.SymbolicTraits(traits).union(self.fontDescriptor.symbolicTraits)) else { return self } return UIFont(descriptor: descriptor, size: 0) } func without(_ traits: UIFontDescriptor.SymbolicTraits...) -> UIFont { guard let descriptor = self.fontDescriptor.withSymbolicTraits(self.fontDescriptor.symbolicTraits.subtracting(UIFontDescriptor.SymbolicTraits(traits))) else { return self } return UIFont(descriptor: descriptor, size: 0) } }
Swift
4,713,236
156
I would like to find an easier way to call deep links in the iOS simulator. On Android you can use ADB to pipe links into the simulator by using the console. Is there a similar way or a workaround to open deep links with the latest iOS Simulator?
You can type this into your Terminal : xcrun simctl openurl booted '<INSERT_URL_HERE>' You can even share documents using the builtin Share Extension from the Finder to the iOS Simulator.
Swift
46,670,298
155
I am trying to delete a row from my Data Source and the following line of code: if let tv = tableView { causes the following error: Initializer for conditional binding must have Optional type, not UITableView Here is the full code: // Override to support editing the table view. func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source if let tv = tableView { myData.removeAtIndex(indexPath.row) tv.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) How should I correct the following? if let tv = tableView {
if let/if var optional binding only works when the result of the right side of the expression is an optional. If the result of the right side is not an optional, you can not use this optional binding. The point of this optional binding is to check for nil and only use the variable if it's non-nil. In your case, the tableView parameter is declared as the non-optional type UITableView. It is guaranteed to never be nil. So optional binding here is unnecessary. func tableView(tableView: UITableView, commitEditingStyle editingStyle:UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source myData.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) All we have to do is get rid of the if let and change any occurrences of tv within it to just tableView.
Swift
31,038,759
155
Does anyone know of a way to get a users time zone in Swift? I'm getting a specific time something is on t.v. out of a database and then need to subtract/add from where they are located to show them the correct time it's on.
edit/update: Xcode 8 or later • Swift 3 or later var secondsFromGMT: Int { return TimeZone.current.secondsFromGMT() } secondsFromGMT // -7200 if you need the abbreviation: var localTimeZoneAbbreviation: String { return TimeZone.current.abbreviation() ?? "" } localTimeZoneAbbreviation // "GMT-2" if you need the timezone identifier: var localTimeZoneIdentifier: String { return TimeZone.current.identifier } localTimeZoneIdentifier // "America/Sao_Paulo" To know all timezones abbreviations available: var timeZoneAbbreviations: [String:String] { return TimeZone.abbreviationDictionary } timeZoneAbbreviations // ["CEST": "Europe/Paris", "WEST": "Europe/Lisbon", "CDT": "America/Chicago", "EET": "Europe/Istanbul", "BRST": "America/Sao_Paulo", "EEST": "Europe/Istanbul", "CET": "Europe/Paris", "MSD": "Europe/Moscow", "MST": "America/Denver", "KST": "Asia/Seoul", "PET": "America/Lima", "NZDT": "Pacific/Auckland", "CLT": "America/Santiago", "HST": "Pacific/Honolulu", "MDT": "America/Denver", "NZST": "Pacific/Auckland", "COT": "America/Bogota", "CST": "America/Chicago", "SGT": "Asia/Singapore", "CAT": "Africa/Harare", "BRT": "America/Sao_Paulo", "WET": "Europe/Lisbon", "IST": "Asia/Calcutta", "HKT": "Asia/Hong_Kong", "GST": "Asia/Dubai", "EDT": "America/New_York", "WIT": "Asia/Jakarta", "UTC": "UTC", "JST": "Asia/Tokyo", "IRST": "Asia/Tehran", "PHT": "Asia/Manila", "AKDT": "America/Juneau", "BST": "Europe/London", "PST": "America/Los_Angeles", "ART": "America/Argentina/Buenos_Aires", "PDT": "America/Los_Angeles", "WAT": "Africa/Lagos", "EST": "America/New_York", "BDT": "Asia/Dhaka", "CLST": "America/Santiago", "AKST": "America/Juneau", "ADT": "America/Halifax", "AST": "America/Halifax", "PKT": "Asia/Karachi", "GMT": "GMT", "ICT": "Asia/Bangkok", "MSK": "Europe/Moscow", "EAT": "Africa/Addis_Ababa"] To know all timezones names (identifiers) available: var timeZoneIdentifiers: [String] { return TimeZone.knownTimeZoneIdentifiers } timeZoneIdentifiers // ["Africa/Abidjan", "Africa/Accra", "Africa/Addis_Ababa", "Africa/Algiers", "Africa/Asmara", "Africa/Bamako", "Africa/Bangui", "Africa/Banjul", "Africa/Bissau", "Africa/Blantyre", "Africa/Brazzaville", "Africa/Bujumbura", "Africa/Cairo", "Africa/Casablanca", "Africa/Ceuta", "Africa/Conakry", "Africa/Dakar", "Africa/Dar_es_Salaam", "Africa/Djibouti", "Africa/Douala", "Africa/El_Aaiun", "Africa/Freetown", "Africa/Gaborone", "Africa/Harare", "Africa/Johannesburg", "Africa/Juba", "Africa/Kampala", "Africa/Khartoum", "Africa/Kigali", "Africa/Kinshasa", "Africa/Lagos", "Africa/Libreville", "Africa/Lome", "Africa/Luanda", "Africa/Lubumbashi", "Africa/Lusaka", "Africa/Malabo", "Africa/Maputo", "Africa/Maseru", "Africa/Mbabane", "Africa/Mogadishu", "Africa/Monrovia", "Africa/Nairobi", "Africa/Ndjamena", "Africa/Niamey", "Africa/Nouakchott", "Africa/Ouagadougou", "Africa/Porto-Novo", "Africa/Sao_Tome", "Africa/Tripoli", "Africa/Tunis", "Africa/Windhoek", "America/Adak", "America/Anchorage", "America/Anguilla", "America/Antigua", "America/Araguaina", "America/Argentina/Buenos_Aires", "America/Argentina/Catamarca", "America/Argentina/Cordoba", "America/Argentina/Jujuy", "America/Argentina/La_Rioja", "America/Argentina/Mendoza", "America/Argentina/Rio_Gallegos", "America/Argentina/Salta", "America/Argentina/San_Juan", "America/Argentina/San_Luis", "America/Argentina/Tucuman", "America/Argentina/Ushuaia", "America/Aruba", "America/Asuncion", "America/Atikokan", "America/Bahia", "America/Bahia_Banderas", "America/Barbados", "America/Belem", "America/Belize", "America/Blanc-Sablon", "America/Boa_Vista", "America/Bogota", …, "Pacific/Marquesas", "Pacific/Midway", "Pacific/Nauru", "Pacific/Niue", "Pacific/Norfolk", "Pacific/Noumea", "Pacific/Pago_Pago", "Pacific/Palau", "Pacific/Pitcairn", "Pacific/Pohnpei", "Pacific/Ponape", "Pacific/Port_Moresby", "Pacific/Rarotonga", "Pacific/Saipan", "Pacific/Tahiti", "Pacific/Tarawa", "Pacific/Tongatapu", "Pacific/Truk", "Pacific/Wake", "Pacific/Wallis"] There is a few other info you may need: var isDaylightSavingTime: Bool { return TimeZone.current.isDaylightSavingTime(for: Date()) } print(isDaylightSavingTime) // true (in effect) var daylightSavingTimeOffset: TimeInterval { return TimeZone.current.daylightSavingTimeOffset() } print(daylightSavingTimeOffset) // 3600 seconds (1 hour - daylight savings time) var nextDaylightSavingTimeTransition: Date? { return TimeZone.current.nextDaylightSavingTimeTransition } // "Feb 18, 2017, 11:00 PM" print(nextDaylightSavingTimeTransition?.description(with: .current) ?? "none") nextDaylightSavingTimeTransition // "Saturday, February 18, 2017 at 11:00:00 PM Brasilia Standard Time\n" var nextDaylightSavingTimeTransitionAfterNext: Date? { guard let nextDaylightSavingTimeTransition = nextDaylightSavingTimeTransition else { return nil } return TimeZone.current.nextDaylightSavingTimeTransition(after: nextDaylightSavingTimeTransition) } nextDaylightSavingTimeTransitionAfterNext // "Oct 15, 2017, 1:00 AM" TimeZone - Apple Developer Swift Documentation
Swift
27,053,135
155
Does swift have fall through statement? e.g if I do the following var testVar = "hello" var result = 0 switch(testVal) { case "one": result = 1 case "two": result = 1 default: result = 3 } is it possible to have the same code executed for case "one" and case "two"?
Yes. You can do so as follows: var testVal = "hello" var result = 0 switch testVal { case "one", "two": result = 1 default: result = 3 } Alternatively, you can use the fallthrough keyword: var testVal = "hello" var result = 0 switch testVal { case "one": fallthrough case "two": result = 1 default: result = 3 }
Swift
24,049,024
155
If I have an app made with SwiftUI, will it work for iOS below iOS 13?
I just checked it out in Xcode 11 and can confirm it won't be backwards-compatible, as can be seen in SwiftUI's View implementation: /// A piece of user interface. /// /// You create custom views by declaring types that conform to the `View` /// protocol. Implement the required `body` property to provide the content /// and behavior for your custom view. @available(iOS 13.0, OSX 10.15, tvOS 13.0, watchOS 6.0, *) public protocol View : _View { /// The type of view representing the body of this view. /// /// When you create a custom view, Swift infers this type from your /// implementation of the required `body` property. associatedtype Body : View /// Declares the content and behavior of this view. var body: Self.Body { get } }
Swift
56,433,305
154
While exploring Xcode9 Beta Found Safe Area on Interface builders View hierarchy viewer. Got curious and tried to know about Safe Area on Apples documentation, in gist the doc says "The the view area which directly interacts with Auto layout" But it did not satisfy me, I want to know Practical use of this new thing. Do any one have some clue? Conclusion paragraph from Apple doc for Safe area. The UILayoutGuide class is designed to perform all the tasks previously performed by dummy views, but to do it in a safer, more efficient manner. Layout guides do not define a new view. They do not participate in the view hierarchy. Instead, they simply define a rectangular region in their owning view’s coordinate system that can interact with Auto Layout.
Safe Area is a layout guide (Safe Area Layout Guide). The layout guide representing the portion of your view that is unobscured by bars and other content. In iOS 11+, Apple is deprecating the top and bottom layout guides and replacing them with a single safe area layout guide. When the view is visible onscreen, this guide reflects the portion of the view that is not covered by other content. The safe area of a view reflects the area covered by navigation bars, tab bars, toolbars, and other ancestors that obscure a view controller's view. (In tvOS, the safe area incorporates the screen's bezel, as defined by the overscanCompensationInsets property of UIScreen.) It also covers any additional space defined by the view controller's additionalSafeAreaInsets property. If the view is not currently installed in a view hierarchy, or is not yet visible onscreen, the layout guide always matches the edges of the view. For the view controller's root view, the safe area in this property represents the entire portion of the view controller's content that is obscured, and any additional insets that you specified. For other views in the view hierarchy, the safe area reflects only the portion of that view that is obscured. For example, if a view is entirely within the safe area of its view controller's root view, the edge insets in this property are 0. According to Apple, Xcode 9 - Release note Interface Builder uses UIView.safeAreaLayoutGuide as a replacement for the deprecated Top and Bottom layout guides in UIViewController. To use the new safe area, select Safe Area Layout Guides in the File inspector for the view controller, and then add constraints between your content and the new safe area anchors. This prevents your content from being obscured by top and bottom bars, and by the overscan region on tvOS. Constraints to the safe area are converted to Top and Bottom when deploying to earlier versions of iOS. Here is simple reference as a comparison (to make similar visual effect) between existing (Top & Bottom) Layout Guide and Safe Area Layout Guide. Safe Area Layout: AutoLayout How to work with Safe Area Layout? Follow these steps to find solution: Enable 'Safe Area Layout', if not enabled. Remove 'all constraint' if they shows connection with with Super view and re-attach all with safe layout anchor. OR Double click on a constraint and edit connection from super view to SafeArea anchor Here is sample snapshot, how to enable safe area layout and edit constraint. Here is result of above changes Layout Design with SafeArea When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen. Most apps that use standard, system-provided UI elements like navigation bars, tables, and collections automatically adapt to the device's new form factor. Background materials extend to the edges of the display and UI elements are appropriately inset and positioned. For apps with custom layouts, supporting iPhone X should also be relatively easy, especially if your app uses Auto Layout and adheres to safe area and margin layout guides. Here is sample code (Ref from: Safe Area Layout Guide): If you create your constraints in code use the safeAreaLayoutGuide property of UIView to get the relevant layout anchors. Let’s recreate the above Interface Builder example in code to see how it looks: Assuming we have the green view as a property in our view controller: private let greenView = UIView() We might have a function to set up the views and constraints called from viewDidLoad: private func setupView() { greenView.translatesAutoresizingMaskIntoConstraints = false greenView.backgroundColor = .green view.addSubview(greenView) } Create the leading and trailing margin constraints as always using the layoutMarginsGuide of the root view: let margins = view.layoutMarginsGuide NSLayoutConstraint.activate([ greenView.leadingAnchor.constraint(equalTo: margins.leadingAnchor), greenView.trailingAnchor.constraint(equalTo: margins.trailingAnchor) ]) Now unless you are targeting iOS 11 only you will need to wrap the safe area layout guide constraints with #available and fall back to top and bottom layout guides for earlier iOS versions: if #available(iOS 11, *) { let guide = view.safeAreaLayoutGuide NSLayoutConstraint.activate([ greenView.topAnchor.constraintEqualToSystemSpacingBelow(guide.topAnchor, multiplier: 1.0), guide.bottomAnchor.constraintEqualToSystemSpacingBelow(greenView.bottomAnchor, multiplier: 1.0) ]) } else { let standardSpacing: CGFloat = 8.0 NSLayoutConstraint.activate([ greenView.topAnchor.constraint(equalTo: topLayoutGuide.bottomAnchor, constant: standardSpacing), bottomLayoutGuide.topAnchor.constraint(equalTo: greenView.bottomAnchor, constant: standardSpacing) ]) } Result: Following UIView extension, make it easy for you to work with SafeAreaLayout programatically. extension UIView { // Top Anchor var safeAreaTopAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.topAnchor } else { return self.topAnchor } } // Bottom Anchor var safeAreaBottomAnchor: NSLayoutYAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.bottomAnchor } else { return self.bottomAnchor } } // Left Anchor var safeAreaLeftAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.leftAnchor } else { return self.leftAnchor } } // Right Anchor var safeAreaRightAnchor: NSLayoutXAxisAnchor { if #available(iOS 11.0, *) { return self.safeAreaLayoutGuide.rightAnchor } else { return self.rightAnchor } } } Here is sample code in Objective-C: How to add a safe area programmatically Here is Apple Developer Official Documentation for Safe Area Layout Guide Safe Area is required to handle user interface design for iPhone-X. Here is basic guideline for How to design user interface for iPhone-X using Safe Area Layout
Swift
44,492,404
154
I noticed that the compiler won't let me override a stored property with another stored value (which seems odd): class Jedi { var lightSaberColor = "Blue" } class Sith: Jedi { override var lightSaberColor = "Red" // Cannot override with a stored property lightSaberColor } However, I'm allowed to do this with a computed property: class Jedi { let lightSaberColor = "Blue" } class Sith: Jedi { override var lightSaberColor : String{return "Red"} } Why am I not allowed to give it another value? Why is overriding with a stored property an abomination and doing it with a computed one kosher? What where they thinking?
Why am I not allowed to just give it another value? You are definitely allowed to give an inherited property a different value. You can do it if you initialize the property in a constructor that takes that initial value, and pass a different value from the derived class: class Jedi { // I made lightSaberColor read-only; you can make it writable if you prefer. let lightSaberColor : String init(_ lsc : String = "Blue") { lightSaberColor = lsc; } } class Sith : Jedi { init() { super.init("Red") } } let j1 = Jedi() let j2 = Sith() print(j1.lightSaberColor) print(j2.lightSaberColor) Overriding a property is not the same as giving it a new value - it is more like giving a class a different property. In fact, that is what happens when you override a computed property: the code that computes the property in the base class is replaced by code that computes the override for that property in the derived class. [Is it] possible to override the actual stored property, i.e. lightSaberColor that has some other behavior? Apart from observers, stored properties do not have behavior, so there is really nothing there to override. Giving the property a different value is possible through the mechanism described above. This does exactly what the example in the question is trying to achieve, with a different syntax.
Swift
26,691,935
154
I would like to perform some cleanup at the end of a view controller's life, namely to remove an NSNotificationCenter notification. Implementing dealloc results in a Swift compiler error: Cannot override 'dealloc' which has been marked unavailable What is the preferred way to perform some cleanup at the end of an object's life in Swift?
deinit { // perform the deinitialization } From the Swift Documentation: A deinitializer is called immediately before a class instance is deallocated. You write deinitializers with the deinit keyword, similar to how intializers are written with the init keyword. Deinitializers are only available on class types. Typically you don’t need to perform manual clean-up when your instances are deallocated. However, when you are working with your own resources, you might need to perform some additional clean-up yourself. For example, if you create a custom class to open a file and write some data to it, you might need to close the file before the class instance is deallocated.
Swift
25,497,928
154
Let's say I have these protocols: protocol SomeProtocol { } protocol SomeOtherProtocol { } Now, if I want a function that takes a generic type, but that type must conform to SomeProtocol I could do: func someFunc<T: SomeProtocol>(arg: T) { // do stuff } But is there a way to add a type constraint for multiple protocols? func bothFunc<T: SomeProtocol | SomeOtherProtocol>(arg: T) { } Similar things use commas, but in this case, it would start the declaration of a different type. Here's what I've tried. <T: SomeProtocol | SomeOtherProtocol> <T: SomeProtocol , SomeOtherProtocol> <T: SomeProtocol : SomeOtherProtocol>
You can use a where clause which lets you specify as many requirements as you want (all of which must be fulfilled) separated by commas Swift 2: func someFunc<T where T:SomeProtocol, T:SomeOtherProtocol>(arg: T) { // stuff } Swift 3 & 4: func someFunc<T: SomeProtocol & SomeOtherProtocol>(arg: T) { // stuff } or the more powerful where clause: func someFunc<T>(arg: T) where T:SomeProtocol, T:SomeOtherProtocol{ // stuff } You can of course use protocol composition (e.g., protocol<SomeProtocol, SomeOtherProtocol> ), but it's a little less flexible. Using where lets you deal with cases where multiple types are involved. You may still want to compose protocols for reuse in multiple places, or just to give the composed protocol a meaningful name. Swift 5: func someFunc(arg: SomeProtocol & SomeOtherProtocol) { // stuff } This feels more natural as the protocols are next to the argument.
Swift
24,089,145
154
I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing it has been a pain to understand things. Specifically I was trying the following: let str = "Hello, playground" let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) // error where the second line was giving me the following error 'advancedBy' is unavailable: To advance an index by n steps call 'index(_:offsetBy:)' on the CharacterView instance that produced the index. I see that String has the following methods. str.index(after: String.Index) str.index(before: String.Index) str.index(String.Index, offsetBy: String.IndexDistance) str.index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index) These were really confusing me at first so I started playing around with them until I understood them. I am adding an answer below to show how they are used.
All of the following examples use var str = "Hello, playground" startIndex and endIndex startIndex is the index of the first character endIndex is the index after the last character. Example // character str[str.startIndex] // H str[str.endIndex] // error: after last character // range let range = str.startIndex..<str.endIndex str[range] // "Hello, playground" With Swift 4's one-sided ranges, the range can be simplified to one of the following forms. let range = str.startIndex... let range = ..<str.endIndex I will use the full form in the follow examples for the sake of clarity, but for the sake of readability, you will probably want to use the one-sided ranges in your code. after As in: index(after: String.Index) after refers to the index of the character directly after the given index. Examples // character let index = str.index(after: str.startIndex) str[index] // "e" // range let range = str.index(after: str.startIndex)..<str.endIndex str[range] // "ello, playground" before As in: index(before: String.Index) before refers to the index of the character directly before the given index. Examples // character let index = str.index(before: str.endIndex) str[index] // d // range let range = str.startIndex..<str.index(before: str.endIndex) str[range] // Hello, playgroun offsetBy As in: index(String.Index, offsetBy: String.IndexDistance) The offsetBy value can be positive or negative and starts from the given index. Although it is of the type String.IndexDistance, you can give it an Int. Examples // character let index = str.index(str.startIndex, offsetBy: 7) str[index] // p // range let start = str.index(str.startIndex, offsetBy: 7) let end = str.index(str.endIndex, offsetBy: -6) let range = start..<end str[range] // play limitedBy As in: index(String.Index, offsetBy: String.IndexDistance, limitedBy: String.Index) The limitedBy is useful for making sure that the offset does not cause the index to go out of bounds. It is a bounding index. Since it is possible for the offset to exceed the limit, this method returns an Optional. It returns nil if the index is out of bounds. Example // character if let index = str.index(str.startIndex, offsetBy: 7, limitedBy: str.endIndex) { str[index] // p } If the offset had been 77 instead of 7, then the if statement would have been skipped. Why is String.Index needed? It would be much easier to use an Int index for Strings. The reason that you have to create a new String.Index for every String is that Characters in Swift are not all the same length under the hood. A single Swift Character might be composed of one, two, or even more Unicode code points. Thus each unique String must calculate the indexes of its Characters. It is possible to hide this complexity behind an Int index extension, but I am reluctant to do so. It is good to be reminded of what is actually happening.
Swift
39,676,939
153
I have a Person Type, and an Array of them: class Person { let name:String let position:Int } let myArray: [Person] = [p1, p1, p3] I want to map myArray to be a Dictionary of [position:name]. The classic solution is: var myDictionary = [Int:String]() for person in myArray { myDictionary[person.position] = person.name } Is there an elegant alternative in Swift via a functional programming approach using map, flatMap, or any other modern Swift style?
Since Swift 4 you can do @Tj3n's approach more cleanly and efficiently using the into version of reduce It gets rid of the temporary dictionary and the return value so it is faster and easier to read. Sample code setup: struct Person { let name: String let position: Int } let myArray = [Person(name:"h", position: 0), Person(name:"b", position:4), Person(name:"c", position:2)] Into parameter is passed empty dictionary of result type: let myDict = myArray.reduce(into: [Int: String]()) { $0[$1.position] = $1.name } Directly returns a dictionary of the type passed in into: print(myDict) // [2: "c", 0: "h", 4: "b"]
Swift
38,454,952
153
I tried changing the colors of the text for a button, but it's still staying white. isbeauty = UIButton() isbeauty.setTitle("Buy", forState: UIControlState.Normal) isbeauty.titleLabel?.textColor = UIColorFromRGB("F21B3F") isbeauty.titleLabel!.font = UIFont(name: "AppleSDGothicNeo-Thin" , size: 25) isbeauty.backgroundColor = UIColor.clearColor() isbeauty.layer.cornerRadius = 5 isbeauty.layer.borderWidth = 1 isbeauty.layer.borderColor = UIColorFromRGB("F21B3F").CGColor isbeauty.frame = CGRectMake(300, 134, 55, 26) isbeauty.addTarget(self,action: "first:", forControlEvents: UIControlEvents.TouchUpInside) self.view.addSubview(isbeauty) I also tried changing it the red, black, blue, but nothing is happening.
You have to use func setTitleColor(_ color: UIColor?, for state: UIControl.State) the same way you set the actual title text. Docs isbeauty.setTitleColor(UIColorFromRGB("F21B3F"), for: .normal)
Swift
31,088,172
153
My UITableViewController is causing a crash with the following error message: Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'unable to dequeue a cell with identifier Cell - must register a nib or a class for the identifier or connect a prototype cell in a storyboard' I understand that I need to register a nib or a class but I don't understand 'where or how?'. import UIKit class NotesListViewController: UITableViewController { @IBOutlet weak var menuButton: UIBarButtonItem! override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "preferredContentSizeChanged:", name: UIContentSizeCategoryDidChangeNotification, object: nil) // Side Menu if self.revealViewController() != nil { menuButton.target = self.revealViewController() menuButton.action = "revealToggle:" self.view.addGestureRecognizer(self.revealViewController().panGestureRecognizer()) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // whenever this view controller appears, reload the table. This allows it to reflect any changes // made whilst editing notes tableView.reloadData() } func preferredContentSizeChanged(notification: NSNotification) { tableView.reloadData() } // #pragma mark - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return notes.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell let note = notes[indexPath.row] let font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) let textColor = UIColor(red: 0.175, green: 0.458, blue: 0.831, alpha: 1) let attributes = [ NSForegroundColorAttributeName : textColor, NSFontAttributeName : font, NSTextEffectAttributeName : NSTextEffectLetterpressStyle ] let attributedString = NSAttributedString(string: note.title, attributes: attributes) cell.textLabel?.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) cell.textLabel?.attributedText = attributedString return cell } let label: UILabel = { let temporaryLabel = UILabel(frame: CGRect(x: 0, y: 0, width: Int.max, height: Int.max)) temporaryLabel.text = "test" return temporaryLabel }() override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { label.font = UIFont.preferredFontForTextStyle(UIFontTextStyleHeadline) label.sizeToFit() return label.frame.height * 1.7 } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { notes.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } } // #pragma mark - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject!) { if let editorVC = segue.destinationViewController as? NoteEditorViewController { if "CellSelected" == segue.identifier { if let path = tableView.indexPathForSelectedRow() { editorVC.note = notes[path.row] } } else if "AddNewNote" == segue.identifier { let note = Note(text: " ") editorVC.note = note notes.append(note) } } } }
You can register a class for your UITableViewCell like this: With Swift 3+: self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell") With Swift 2.2: self.tableView.registerClass(UITableViewCell.self, forCellReuseIdentifier: "cell") Make sure same identifier "cell" is also copied at your storyboard's UITableViewCell. "self" is for getting the class use the class name followed by .self.
Swift
29,282,447
153
There's a class called Employee. class Employee { var id: Int var firstName: String var lastName: String var dateOfBirth: NSDate? init(id: Int, firstName: String, lastName: String) { self.id = id self.firstName = firstName self.lastName = lastName } } And I have an array of Employee objects. What I now need is to extract the ids of all those objects in that array into a new array. I also found this similar question. But it's in Objective-C so it's using valueForKeyPath to accomplish this. How can I do this in Swift?
You can use the map method, which transform an array of a certain type to an array of another type - in your case, from array of Employee to array of Int: var array = [Employee]() array.append(Employee(id: 4, firstName: "", lastName: "")) array.append(Employee(id: 2, firstName: "", lastName: "")) let ids = array.map { $0.id }
Swift
28,393,334
153
I am working on an app the requires checking the due date for homework. I want to know if a due date is within the next week, and if it is then perform an action. Most of the documentation I could find is in Objective-C and I can't figure out how to do it in Swift. Thanks for the help!!
If you want to support ==, <, >, <=, or >= for NSDates, you just have to declare this somewhere: public func ==(lhs: NSDate, rhs: NSDate) -> Bool { return lhs === rhs || lhs.compare(rhs) == .OrderedSame } public func <(lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } extension NSDate: Comparable { }
Swift
26,198,526
153
I have a global variable that needs to be shared among my ViewControllers. In Objective-C, I can define a static variable, but I can't find a way to define a global variable in Swift. Do you know of a way to do it?
From the official Swift programming guide: Global variables are variables that are defined outside of any function, method, closure, or type context. Global constants and variables are always computed lazily. You can define it in any file and can access it in current module anywhere. So you can define it somewhere in the file outside of any scope. There is no need for static and all global variables are computed lazily. var yourVariable = "someString" You can access this from anywhere in the current module. However you should avoid this as Global variables are not good for application state and mainly reason of bugs. As shown in this answer, in Swift you can encapsulate them in struct and can access anywhere. You can define static variables or constant in Swift also. Encapsulate in struct struct MyVariables { static var yourVariable = "someString" } You can use this variable in any class or anywhere let string = MyVariables.yourVariable println("Global variable:\(string)") //Changing value of it MyVariables.yourVariable = "anotherString"
Swift
26,195,262
153
I noticed when writing an assert in Swift that the first value is typed as @autoclosure() -> Bool with an overloaded method to return a generic T value, to test existence via the LogicValue protocol. However sticking strictly to the question at hand. It appears to want an @autoclosure that returns a Bool. Writing an actual closure that takes no parameters and returns a Bool does not work, it wants me to call the closure to make it compile, like so: assert({() -> Bool in return false}(), "No user has been set", file: __FILE__, line: __LINE__) However simply passing a Bool works: assert(false, "No user has been set", file: __FILE__, line: __LINE__) So what is going on? What is @autoclosure? Edit: @auto_closure was renamed @autoclosure
Consider a function that takes one argument, a simple closure that takes no argument: func f(pred: () -> Bool) { if pred() { print("It's true") } } To call this function, we have to pass in a closure f(pred: {2 > 1}) // "It's true" If we omit the braces, we are passing in an expression and that's an error: f(pred: 2 > 1) // error: '>' produces 'Bool', not the expected contextual result type '() -> Bool' @autoclosure creates an automatic closure around the expression. So when the caller writes an expression like 2 > 1, it's automatically wrapped into a closure to become {2 > 1} before it is passed to f. So if we apply this to the function f: func f(pred: @autoclosure () -> Bool) { if pred() { print("It's true") } } f(pred: 2 > 1) // It's true So it works with just an expression without the need to wrap it in a closure.
Swift
24,102,617
153
Is there a relatively easy way of looping a video in AVFoundation? I've created my AVPlayer and AVPlayerLayer like so: avPlayer = [[AVPlayer playerWithURL:videoUrl] retain]; avPlayerLayer = [[AVPlayerLayer playerLayerWithPlayer:avPlayer] retain]; avPlayerLayer.frame = contentView.layer.bounds; [contentView.layer addSublayer: avPlayerLayer]; and then I play my video with: [avPlayer play]; The video plays fine but stops at the end. With the MPMoviePlayerController all you have to do is set its repeatMode property to the right value. There doesn't appear to be a similar property on AVPlayer. There also doesn't seem to be a callback that will tell me when the movie has finished so I can seek to the beginning and play it again. I'm not using MPMoviePlayerController because it has some serious limitations. I want to be able to play back multiple video streams at once.
You can get a Notification when the player ends. Check AVPlayerItemDidPlayToEndTimeNotification When setting up the player: ObjC avPlayer.actionAtItemEnd = AVPlayerActionAtItemEndNone; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(playerItemDidReachEnd:) name:AVPlayerItemDidPlayToEndTimeNotification object:[avPlayer currentItem]]; this will prevent the player to pause at the end. in the notification: - (void)playerItemDidReachEnd:(NSNotification *)notification { AVPlayerItem *p = [notification object]; [p seekToTime:kCMTimeZero]; } this will rewind the movie. Don't forget un unregister the notification when releasing the player. Swift avPlayer?.actionAtItemEnd = .none NotificationCenter.default.addObserver(self, selector: #selector(playerItemDidReachEnd(notification:)), name: .AVPlayerItemDidPlayToEndTime, object: avPlayer?.currentItem) @objc func playerItemDidReachEnd(notification: Notification) { if let playerItem = notification.object as? AVPlayerItem { playerItem.seek(to: kCMTimeZero) } } Swift 4+ @objc func playerItemDidReachEnd(notification: Notification) { if let playerItem = notification.object as? AVPlayerItem { playerItem.seek(to: CMTime.zero, completionHandler: nil) } }
Swift
5,361,145
153
I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel? @IBAction func timePickerClicked(sender: UIDatePicker) { var dateFormatter = NSDateFormatter() dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle var dateStr = dateFormatter.stringFromDate(startTime.date) let sttime = dateStr startTimeDisplay.text = dateStr } // How to advance time by 5 minutes for each section based on the start time selected and display time // section 1 = start time + 5 // section 2 = start time + 10*
Two approaches: Use Calendar and date(byAdding:to:wrappingComponents:). E.g., in Swift 3 and later: let calendar = Calendar.current let date = calendar.date(byAdding: .minute, value: 5, to: startDate) Just use + operator (see +(_:_:)) to add a TimeInterval (i.e. a certain number of seconds). E.g. to add five minutes, you can: let date = startDate + 5 * 60 (Note, the order is specific here: The date on the left side of the + and the seconds on the right side.) You can also use addingTimeInterval, if you’d prefer: let date = startDate.addingTimeInterval(5 * 60) Bottom line, +/addingTimeInterval is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval doesn’t. For Swift 2 renditions, see the previous revision of this answer.
Swift
29,465,205
152
I need to make the iPhone vibrate, but I don't know how to do that in Swift. I know that in Objective-C, you just write: import AudioToolbox AudioServicesPlayAlertSound(kSystemSoundID_Vibrate); But that is not working for me.
Short example: import UIKit import AudioToolbox class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() AudioServicesPlayAlertSound(SystemSoundID(kSystemSoundID_Vibrate)) } } load onto your phone and it will vibrate. You can put it in a function or IBAction as you wish. Code Update: AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate)) { } As apple code docs written: This function will be deprecated in a future release. Use AudioServicesPlaySystemSoundWithCompletion instead. NOTE: If vibrate doesn't work. check vibrate is enable in sounds and haptics settings
Swift
26,455,880
152
In the reference section of Apple's docs there's lots of instances of this sort of thing: func runAction(_action: SKAction!) The Objective-C 'equivalent' of this is: - (void)runAction:(SKAction *)action It strikes me that it's probably important that (in the Swift reference) there's a space after the underscore and "action" is written in italics. But I can't figure out what this is trying to convey. So perhaps the question is... is there a reference for the conventions used in the references? -- here's the page I'm referencing in this reference to the underscore use: https://developer.apple.com/documentation/spritekit/sknode#//apple_ref/occ/instm/SKNode/runAction Update Swift 3 has made some changes to how function/method parameter names and argument labels are used and named. This has ramifications on this question and its answer. @Rickster does an amazing job of answering a different question about _underscores in functions that clears much of this up, here: Why do I need underscores in swift?
Both answers were correct but I want to clarify a little bit more. _ is used to modify external parameter name behavior for methods. In Local and External Parameter Names for Methods section of the documentation, it says: Swift gives the first parameter name in a method a local parameter name by default, and gives the second and subsequent parameter names both local and external parameter names by default. On the other hand, functions by default don't have external parameter names. For example, we have this foo() method defined in class Bar: class Bar{ func foo(s1: String, s2: String) -> String { return s1 + s2; } } When you call foo(), it is called like bar.foo("Hello", s2: "World"). But, you can override this behavior by using _ in front of s2 where it's declared. func foo(s1: String, _ s2: String) -> String{ return s1 + s2; } Then, when you call foo, it could be simply called like bar.foo("Hello", "World") without the name of the second parameter. Back to your case, runAction is a method because it's associated with type SKNode, obviously. Thus, putting a _ before parameter action allows you to call runAction without an external name. Update for Swift 2.0 Function and method now work the same way in terms of local and external argument name declaration. Functions are now called by using external parameter name by default, starting at 2nd parameter. This rule only applies to pure Swift code. So, by providing an _ in front of a function, the caller won't have to specify external parameter name, just like what you would do for a method.
Swift
24,437,388
152
I want to pass my Swift Array account.chats to chatsViewController.chats by reference (so that when I add a chat to account.chats, chatsViewController.chats still points to account.chats). I.e., I don't want Swift to separate the two arrays when the length of account.chats changes.
For function parameter operator we use: let (it's default operator, so we can omit let) to make a parameter constant (it means we cannot modify even local copy); var to make it variable (we can modify it locally, but it wont affect the external variable that has been passed to the function); and inout to make it an in-out parameter. In-out means in fact passing variable by reference, not by value. And it requires not only to accept value by reference, by also to pass it by reference, so pass it with & - foo(&myVar) instead of just foo(myVar) So do it like this: var arr = [1, 2, 3] func addItem(_ localArr: inout [Int]) { localArr.append(4) } addItem(&arr) print(arr) // it will print [1, 2, 3, 4] To be exact it's not just a reference, but a real alias for the external variable, so you can do such a trick with any variable type, for example with integer (you can assign new value to it), though it may not be a good practice and it may be confusing to modify the primitive data types like this.
Swift
24,250,938
152
I have the following enum. enum EstimateItemStatus: Printable { case Pending case OnHold case Done var description: String { switch self { case .Pending: return "Pending" case .OnHold: return "On Hold" case .Done: return "Done" } } init?(id : Int) { switch id { case 1: self = .Pending case 2: self = .OnHold case 3: self = .Done default: return nil } } } I need to get all the raw values as an array of strings (like so ["Pending", "On Hold", "Done"]). I added this method to the enum. func toArray() -> [String] { var n = 1 return Array( GeneratorOf<EstimateItemStatus> { return EstimateItemStatus(id: n++)!.description } ) } But I'm getting the following error. Cannot find an initializer for type 'GeneratorOf' that accepts an argument list of type '(() -> _)' Is there is an easier, better or more elegant way to do this?
For Swift 4.2 (Xcode 10) and later There's a CaseIterable protocol: enum EstimateItemStatus: String, CaseIterable { case pending = "Pending" case onHold = "OnHold" case done = "Done" init?(id : Int) { switch id { case 1: self = .pending case 2: self = .onHold case 3: self = .done default: return nil } } } for value in EstimateItemStatus.allCases { print(value) } For Swift < 4.2 No, you can't query an enum for what values it contains. See this article. You have to define an array that list all the values you have. Also check out Frank Valbuena's solution in "How to get all enum values as an array". enum EstimateItemStatus: String { case Pending = "Pending" case OnHold = "OnHold" case Done = "Done" static let allValues = [Pending, OnHold, Done] init?(id : Int) { switch id { case 1: self = .Pending case 2: self = .OnHold case 3: self = .Done default: return nil } } } for value in EstimateItemStatus.allValues { print(value) }
Swift
32,952,248
151
I'm creating an app and i've browsed on the internet and i'm wondering how they make this transparent UINavigationBar like this: I've added following like in my appdelegate: UINavigationBar.appearance().translucent = true but this just makes it look like following: How can I make the navigation bar transparent like first image?
You can apply Navigation Bar Image like below for Translucent. Objective-C: [self.navigationController.navigationBar setBackgroundImage:[UIImage new] forBarMetrics:UIBarMetricsDefault]; //UIImageNamed:@"transparent.png" self.navigationController.navigationBar.shadowImage = [UIImage new];////UIImageNamed:@"transparent.png" self.navigationController.navigationBar.translucent = YES; self.navigationController.view.backgroundColor = [UIColor clearColor]; Swift 3: self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default) //UIImage.init(named: "transparent.png") self.navigationController?.navigationBar.shadowImage = UIImage() self.navigationController?.navigationBar.isTranslucent = true self.navigationController?.view.backgroundColor = .clear
Swift
25,845,855
151
Swift 4 introduced support for native JSON encoding and decoding via the Decodable protocol. How do I use custom keys for this? E.g., say I have a struct struct Address:Codable { var street:String var zip:String var city:String var state:String } I can encode this to JSON. let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California") if let encoded = try? encoder.encode(address) { if let json = String(data: encoded, encoding: .utf8) { // Print JSON String print(json) // JSON string is { "state":"California", "street":"Apple Bay Street", "zip":"94608", "city":"Emeryville" } } } I can encode this back to an object. let newAddress: Address = try decoder.decode(Address.self, from: encoded) But If I had a json object that was { "state":"California", "street":"Apple Bay Street", "zip_code":"94608", "city":"Emeryville" } How would I tell the decoder on Address that zip_code maps to zip? I believe you use the new CodingKey protocol, but I can't figure out how to use this.
Manually customising coding keys In your example, you're getting an auto-generated conformance to Codable as all your properties also conform to Codable. This conformance automatically creates a key type that simply corresponds to the property names – which is then used in order to encode to/decode from a single keyed container. However one really neat feature of this auto-generated conformance is that if you define a nested enum in your type called "CodingKeys" (or use a typealias with this name) that conforms to the CodingKey protocol – Swift will automatically use this as the key type. This therefore allows you to easily customise the keys that your properties are encoded/decoded with. So what this means is you can just say: struct Address : Codable { var street: String var zip: String var city: String var state: String private enum CodingKeys : String, CodingKey { case street, zip = "zip_code", city, state } } The enum case names need to match the property names, and the raw values of these cases need to match the keys that you're encoding to/decoding from (unless specified otherwise, the raw values of a String enumeration will the same as the case names). Therefore, the zip property will now be encoded/decoded using the key "zip_code". The exact rules for the auto-generated Encodable/Decodable conformance are detailed by the evolution proposal (emphasis mine): In addition to automatic CodingKey requirement synthesis for enums, Encodable & Decodable requirements can be automatically synthesized for certain types as well: Types conforming to Encodable whose properties are all Encodable get an automatically generated String-backed CodingKey enum mapping properties to case names. Similarly for Decodable types whose properties are all Decodable Types falling into (1) — and types which manually provide a CodingKey enum (named CodingKeys, directly, or via a typealias) whose cases map 1-to-1 to Encodable/Decodable properties by name — get automatic synthesis of init(from:) and encode(to:) as appropriate, using those properties and keys Types which fall into neither (1) nor (2) will have to provide a custom key type if needed and provide their own init(from:) and encode(to:), as appropriate Example encoding: import Foundation let address = Address(street: "Apple Bay Street", zip: "94608", city: "Emeryville", state: "California") do { let encoded = try JSONEncoder().encode(address) print(String(decoding: encoded, as: UTF8.self)) } catch { print(error) } //{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"} Example decoding: // using the """ multi-line string literal here, as introduced in SE-0168, // to avoid escaping the quotation marks let jsonString = """ {"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"} """ do { let decoded = try JSONDecoder().decode(Address.self, from: Data(jsonString.utf8)) print(decoded) } catch { print(error) } // Address(street: "Apple Bay Street", zip: "94608", // city: "Emeryville", state: "California") Automatic snake_case JSON keys for camelCase property names In Swift 4.1, if you rename your zip property to zipCode, you can take advantage of the key encoding/decoding strategies on JSONEncoder and JSONDecoder in order to automatically convert coding keys between camelCase and snake_case. Example encoding: import Foundation struct Address : Codable { var street: String var zipCode: String var city: String var state: String } let address = Address(street: "Apple Bay Street", zipCode: "94608", city: "Emeryville", state: "California") do { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToSnakeCase let encoded = try encoder.encode(address) print(String(decoding: encoded, as: UTF8.self)) } catch { print(error) } //{"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"} Example decoding: let jsonString = """ {"state":"California","street":"Apple Bay Street","zip_code":"94608","city":"Emeryville"} """ do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromSnakeCase let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8)) print(decoded) } catch { print(error) } // Address(street: "Apple Bay Street", zipCode: "94608", // city: "Emeryville", state: "California") One important thing to note about this strategy however is that it won't be able to round-trip some property names with acronyms or initialisms which, according to the Swift API design guidelines, should be uniformly upper or lower case (depending on the position). For example, a property named someURL will be encoded with the key some_url, but on decoding, this will be transformed to someUrl. To fix this, you'll have to manually specify the coding key for that property to be string that the decoder expects, e.g someUrl in this case (which will still be transformed to some_url by the encoder): struct S : Codable { private enum CodingKeys : String, CodingKey { case someURL = "someUrl", someOtherProperty } var someURL: String var someOtherProperty: String } (This doesn't strictly answer your specific question, but given the canonical nature of this Q&A, I feel it's worth including) Custom automatic JSON key mapping In Swift 4.1, you can take advantage of the custom key encoding/decoding strategies on JSONEncoder and JSONDecoder, allowing you to provide a custom function to map coding keys. The function you provide takes a [CodingKey], which represents the coding path for the current point in encoding/decoding (in most cases, you'll only need to consider the last element; that is, the current key). The function returns a CodingKey that will replace the last key in this array. For example, UpperCamelCase JSON keys for lowerCamelCase property names: import Foundation // wrapper to allow us to substitute our mapped string keys. struct AnyCodingKey : CodingKey { var stringValue: String var intValue: Int? init(_ base: CodingKey) { self.init(stringValue: base.stringValue, intValue: base.intValue) } init(stringValue: String) { self.stringValue = stringValue } init(intValue: Int) { self.stringValue = "\(intValue)" self.intValue = intValue } init(stringValue: String, intValue: Int?) { self.stringValue = stringValue self.intValue = intValue } } extension JSONEncoder.KeyEncodingStrategy { static var convertToUpperCamelCase: JSONEncoder.KeyEncodingStrategy { return .custom { codingKeys in var key = AnyCodingKey(codingKeys.last!) // uppercase first letter if let firstChar = key.stringValue.first { let i = key.stringValue.startIndex key.stringValue.replaceSubrange( i ... i, with: String(firstChar).uppercased() ) } return key } } } extension JSONDecoder.KeyDecodingStrategy { static var convertFromUpperCamelCase: JSONDecoder.KeyDecodingStrategy { return .custom { codingKeys in var key = AnyCodingKey(codingKeys.last!) // lowercase first letter if let firstChar = key.stringValue.first { let i = key.stringValue.startIndex key.stringValue.replaceSubrange( i ... i, with: String(firstChar).lowercased() ) } return key } } } You can now encode with the .convertToUpperCamelCase key strategy: let address = Address(street: "Apple Bay Street", zipCode: "94608", city: "Emeryville", state: "California") do { let encoder = JSONEncoder() encoder.keyEncodingStrategy = .convertToUpperCamelCase let encoded = try encoder.encode(address) print(String(decoding: encoded, as: UTF8.self)) } catch { print(error) } //{"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"} and decode with the .convertFromUpperCamelCase key strategy: let jsonString = """ {"Street":"Apple Bay Street","City":"Emeryville","State":"California","ZipCode":"94608"} """ do { let decoder = JSONDecoder() decoder.keyDecodingStrategy = .convertFromUpperCamelCase let decoded = try decoder.decode(Address.self, from: Data(jsonString.utf8)) print(decoded) } catch { print(error) } // Address(street: "Apple Bay Street", zipCode: "94608", // city: "Emeryville", state: "California")
Swift
44,396,500
150
I am very new to Swift (got started this week) and I'm migrating my app from Objective-C. I have basically the following code in Objective-C that works fine: typedef enum : int { MyTimeFilter1Hour = 1, MyTimeFilter1Day = 2, MyTimeFilter7Day = 3, MyTimeFilter1Month = 4, } MyTimeFilter; ... - (void)selectFilter:(id)sender { self.timeFilterSelected = (MyTimeFilter)((UIButton *)sender).tag; [self closeAnimated:YES]; } When translating it to Swift, I did the following: enum MyTimeFilter : Int { case OneHour = 1 case OneDay = 2 case SevenDays = 3 case OneMonth = 4 } ... @IBAction func selectFilter(sender: AnyObject) { self.timeFilterSelected = (sender as UIButton).tag as MyTimeFilter self.close(true) } By doing that, I get the error : 'Int' is not convertible to 'MyTimeFilter' I don't know if my approach (using the tag property) is the best, but anyway I need to do this kind of casting in different places in my app. Does anyone have an idea of how to get rid of this error? Thanks!
Use the rawValue initializer: it's an initializer automatically generated for enums. self.timeFilterSelected = MyTimeFilter(rawValue: (sender as UIButton).tag)! see: The Swift Programming Language § Enumerations NOTE: This answer has changed. Earlier version of Swift use the class method fromRaw() to convert raw values to enumerated values.
Swift
25,276,775
150
How do you access command line arguments for a command line application in Swift?
Update 01/17/17: Updated the example for Swift 3. Process has been renamed to CommandLine. Update 09/30/2015: Updated the example to work in Swift 2. It's actually possible to do this without Foundation or C_ARGV and C_ARGC. The Swift standard library contains a struct CommandLine which has a collection of Strings called arguments. So you could switch on arguments like this: for argument in CommandLine.arguments { switch argument { case "arg1": print("first argument") case "arg2": print("second argument") default: print("an argument") } }
Swift
24,029,633
150
Is there a way to call C routines from Swift? A lot of iOS / Apple libraries are C only and I'd still like to be able to call those. For example, I'd like to be able to call the objc runtime libraries from swift. In particular, how do you bridge iOS C headers?
Yes, you can of course interact with Apple's C libraries. Here is explained how. Basically, the C types, C pointers, etc., are translated into Swift objects, for example a C int in Swift is a CInt. I've built a tiny example, for another question, which can be used as a little explanation, on how to bridge between C and Swift: main.swift import Foundation var output: CInt = 0 getInput(&output) println(output) UserInput.c #include <stdio.h> void getInput(int *output) { scanf("%i", output); } cliinput-Bridging-Header.h void getInput(int *output); Here is the original answer.
Swift
24,004,732
150
I am looking at Xcode 7.3 notes and I notice this issue. The ++ and -- operators have been deprecated Could some one explain why it is deprecated? And am I right that in new version of Xcode now you going to use instead of ++ this x += 1; Example: for var index = 0; index < 3; index += 1 { print("index is \(index)") }
A full explanation here from Chris Lattner, Swift's creator. I'll summarize the points: It's another function you have to learn while learning Swift Not much shorter than x += 1 Swift is not C. Shouldn't carry them over just to please C programmers Its main use is in C-style for loop: for i = 0; i < n; i++ { ... }, which Swift has better alternatives, like for i in 0..<n { ... } (C-style for loop is going out as well) Can be tricky to read and maintain, for eg, what's the value of x - ++x or foo(++x, x++)? Chris Lattner doesn't like it. For those interested (and to avoid link rot), Lattner's reasons in his own words are: These operators increase the burden to learn Swift as a first programming language - or any other case where you don't already know these operators from a different language. Their expressive advantage is minimal - x++ is not much shorter than x += 1. Swift already deviates from C in that the =, += and other assignment-like operations returns Void (for a number of reasons). These operators are inconsistent with that model. Swift has powerful features that eliminate many of the common reasons you'd use ++i in a C-style for loop in other languages, so these are relatively infrequently used in well-written Swift code. These features include the for-in loop, ranges, enumerate, map, etc. Code that actually uses the result value of these operators is often confusing and subtle to a reader/maintainer of code. They encourage "overly tricky" code which may be cute, but difficult to understand. While Swift has well defined order of evaluation, any code that depended on it (like foo(++a, a++)) would be undesirable even if it was well-defined. These operators are applicable to relatively few types: integer and floating point scalars, and iterator-like concepts. They do not apply to complex numbers, matrices, etc. Finally, these fail the metric of "if we didn't already have these, would we add them to Swift 3?"
Swift
35,158,422
149
How do I append one Dictionary to another Dictionary using Swift? I am using the AlamoFire library to send JSON content to a REST server. Dictionary 1 var dict1: [String: AnyObject] = [ kFacebook: [ kToken: token ] ] Dictionary 2 var dict2: [String: AnyObject] = [ kRequest: [ kTargetUserId: userId ] ] How do I combine the two dictionaries to make a new dictionary as shown below? let parameters: [String: AnyObject] = [ kFacebook: [ kToken: token ], kRequest: [ kTargetUserId: userId ] ] I have tried dict1 += dict2, but I got a compile error: Binary operator '+=' cannot be applied to two '[String : AnyObject]' operands
I love this approach: dicFrom.forEach { (key, value) in dicTo[key] = value } Swift 4 and 5 With Swift 4 Apple introduces a better approach to merge two dictionaries: let dictionary = ["a": 1, "b": 2] let newKeyValues = ["a": 3, "b": 4] let keepingCurrent = dictionary.merging(newKeyValues) { (current, _) in current } // ["b": 2, "a": 1] let replacingCurrent = dictionary.merging(newKeyValues) { (_, new) in new } // ["b": 4, "a": 3] You have 2 options here (as with most functions operating on containers): merge mutates an existing dictionary merging returns a new dictionary
Swift
26,728,477
149
What is swift equivalent of next code: [NSBundle bundleForClass:[self class]] I need load resources from test bundle (JSON data)
Never used, but I think it should be this: Swift <= 2.x NSBundle(forClass: self.dynamicType) Swift 3.x Bundle(for: type(of: self))
Swift
25,651,403
149
I'm wondering if there is some new and awesome possibility to get the amount of days between two NSDates in Swift / the "new" Cocoa? E.g. like in Ruby I would do: (end_date - start_date).to_i
You have to consider the time difference as well. For example if you compare the dates 2015-01-01 10:00 and 2015-01-02 09:00, days between those dates will return as 0 (zero) since the difference between those dates is less than 24 hours (it's 23 hours). If your purpose is to get the exact day number between two dates, you can work around this issue like this: // Assuming that firstDate and secondDate are defined // ... let calendar = NSCalendar.currentCalendar() // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDayForDate(firstDate) let date2 = calendar.startOfDayForDate(secondDate) let flags = NSCalendarUnit.Day let components = calendar.components(flags, fromDate: date1, toDate: date2, options: []) components.day // This will return the number of day(s) between dates Swift 3 and Swift 4 Version let calendar = Calendar.current // Replace the hour (time) of both dates with 00:00 let date1 = calendar.startOfDay(for: firstDate) let date2 = calendar.startOfDay(for: secondDate) let components = calendar.dateComponents([.day], from: date1, to: date2)
Swift
24,723,431
148
I want to create a UILabel in which the text is like this How can I do this? When the text is small, the line should also be small.
SWIFT 5 UPDATE CODE let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your Text") attributeString.addAttribute(NSAttributedString.Key.strikethroughStyle, value: 2, range: NSRange(location: 0, length: attributeString.length)) then: yourLabel.attributedText = attributeString To make some part of string to strike then provide range let somePartStringRange = (yourStringHere as NSString).range(of: "Text") attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: somePartStringRange) Objective-C In iOS 6.0 > UILabel supports NSAttributedString NSMutableAttributedString *attributeString = [[NSMutableAttributedString alloc] initWithString:@"Your String here"]; [attributeString addAttribute:NSStrikethroughStyleAttributeName value:@2 range:NSMakeRange(0, [attributeString length])]; Swift let attributeString: NSMutableAttributedString = NSMutableAttributedString(string: "Your String here") attributeString.addAttribute(NSStrikethroughStyleAttributeName, value: 2, range: NSMakeRange(0, attributeString.length)) Definition : - (void)addAttribute:(NSString *)name value:(id)value range:(NSRange)aRange Parameters List: name : A string specifying the attribute name. Attribute keys can be supplied by another framework or can be custom ones you define. For information about where to find the system-supplied attribute keys, see the overview section in NSAttributedString Class Reference. value : The attribute value associated with name. aRange : The range of characters to which the specified attribute/value pair applies. Then yourLabel.attributedText = attributeString; For lesser than iOS 6.0 versions you need 3-rd party component to do this. One of them is TTTAttributedLabel, another is OHAttributedLabel.
Swift
13,133,014
148
How can I access to consul UI externally? I want to access consul UI writing <ANY_MASTER_OR_SLAVE_NODE_IP>:8500 I have try doing a ssh tunnel to acces: ssh -N -f -L 8500:localhost:8500 [email protected] Then if I access http://localhost:8500 It works, but it is not what I want. I need to access externally, without ssh tunnel. My config.json file is the next: { "bind_addr":"172.16.8.216", "server": false, "datacenter": "nyc2", "data_dir": "/var/consul", "ui_dir": "/home/ikerlan/dist", "log_level": "INFO", "enable_syslog": true, "start_join": ["172.16.8.211","172.16.8.212","172.16.8.213"] } Any help? Thanks
Add { "client_addr": "0.0.0.0" } to your configuration or add the option -client 0.0.0.0 to the command line of consul to make your Web UI accessible from the outside (see the docs for more information). Please note that this will also make your Consul REST API accessible from the outside. Depending on your environment you might want to activate Consul's ACLs to restrict access.
Consul
35,132,687
32
So I have 2 similar deployments on k8s that pulls the same image from GitLab. Apparently this resulted in my second deployment to go on a CrashLoopBackOff error and I can't seem to connect to the port to check on the /healthz of my pod. Logging the pod shows that the pod received an interrupt signal while describing the pod shows the following message. FirstSeen LastSeen Count From SubObjectPath Type Reason Message --------- -------- ----- ---- ------------- -------- ------ ------- 29m 29m 1 default-scheduler Normal Scheduled Successfully assigned java-kafka-rest-kafka-data-2-development-5c6f7f597-5t2mr to 172.18.14.110 29m 29m 1 kubelet, 172.18.14.110 Normal SuccessfulMountVolume MountVolume.SetUp succeeded for volume "default-token-m4m55" 29m 29m 1 kubelet, 172.18.14.110 spec.containers{consul} Normal Pulled Container image "..../consul-image:0.0.10" already present on machine 29m 29m 1 kubelet, 172.18.14.110 spec.containers{consul} Normal Created Created container 29m 29m 1 kubelet, 172.18.14.110 spec.containers{consul} Normal Started Started container 28m 28m 1 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Normal Killing Killing container with id docker://java-kafka-rest-development:Container failed liveness probe.. Container will be killed and recreated. 29m 28m 2 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Normal Created Created container 29m 28m 2 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Normal Started Started container 29m 27m 10 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Warning Unhealthy Readiness probe failed: Get http://10.5.59.35:7533/healthz: dial tcp 10.5.59.35:7533: getsockopt: connection refused 28m 24m 13 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Warning Unhealthy Liveness probe failed: Get http://10.5.59.35:7533/healthz: dial tcp 10.5.59.35:7533: getsockopt: connection refused 29m 19m 8 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Normal Pulled Container image "r..../java-kafka-rest:0.3.2-dev" already present on machine 24m 4m 73 kubelet, 172.18.14.110 spec.containers{java-kafka-rest-development} Warning BackOff Back-off restarting failed container I have tried to redeploy the deployments under different images and it seems to work just fine. However I don't think this will be efficient as the images are the same throughout. How do I go on about this? Here's what my deployment file looks like: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: "java-kafka-rest-kafka-data-2-development" labels: repository: "java-kafka-rest" project: "java-kafka-rest" service: "java-kafka-rest-kafka-data-2" env: "development" spec: replicas: 1 selector: matchLabels: repository: "java-kafka-rest" project: "java-kafka-rest" service: "java-kafka-rest-kafka-data-2" env: "development" template: metadata: labels: repository: "java-kafka-rest" project: "java-kafka-rest" service: "java-kafka-rest-kafka-data-2" env: "development" release: "0.3.2-dev" spec: imagePullSecrets: - name: ... containers: - name: java-kafka-rest-development image: registry...../java-kafka-rest:0.3.2-dev env: - name: DEPLOYMENT_COMMIT_HASH value: "0.3.2-dev" - name: DEPLOYMENT_PORT value: "7533" livenessProbe: httpGet: path: /healthz port: 7533 initialDelaySeconds: 30 timeoutSeconds: 1 readinessProbe: httpGet: path: /healthz port: 7533 timeoutSeconds: 1 ports: - containerPort: 7533 resources: requests: cpu: 0.5 memory: 6Gi limits: cpu: 3 memory: 10Gi command: - /envconsul - -consul=127.0.0.1:8500 - -sanitize - -upcase - -prefix=java-kafka-rest/ - -prefix=java-kafka-rest/kafka-data-2 - java - -jar - /build/libs/java-kafka-rest-0.3.2-dev.jar securityContext: readOnlyRootFilesystem: true - name: consul image: registry.../consul-image:0.0.10 env: - name: SERVICE_NAME value: java-kafka-rest-kafka-data-2 - name: SERVICE_ENVIRONMENT value: development - name: SERVICE_PORT value: "7533" - name: CONSUL1 valueFrom: configMapKeyRef: name: consul-config-... key: node1 - name: CONSUL2 valueFrom: configMapKeyRef: name: consul-config-... key: node2 - name: CONSUL3 valueFrom: configMapKeyRef: name: consul-config-... key: node3 - name: CONSUL_ENCRYPT valueFrom: configMapKeyRef: name: consul-config-... key: encrypt ports: - containerPort: 8300 - containerPort: 8301 - containerPort: 8302 - containerPort: 8400 - containerPort: 8500 - containerPort: 8600 command: [ entrypoint, agent, -config-dir=/config, -join=$(CONSUL1), -join=$(CONSUL2), -join=$(CONSUL3), -encrypt=$(CONSUL_ENCRYPT) ] terminationGracePeriodSeconds: 30 nodeSelector: env: ...
To those having this problem, I've discovered the problem and solution to my question. Apparently the problem lies with my service.yml where my targetPort was aimed to a port different than the one I opened in my docker image. Make sure the port that's opened in the docker image connects to the right port. Hope this helps.
Consul
53,535,540
31
What are the different ports used by consul? What is the purpose of each port? Is there any way to configure consul to run using different ports?
When reading the consul documentation you will find following information. Ports Used Consul requires up to 4 different ports to work properly, some on TCP, UDP, or both protocols. Below we document the requirements for each port. Server RPC (Default 8300). This is used by servers to handle incoming requests from other agents. TCP only. Serf LAN (Default 8301). This is used to handle gossip in the LAN. Required by all agents. TCP and UDP. Serf WAN (Default 8302). This is used by servers to gossip over the WAN to other servers. TCP and UDP. HTTP API (Default 8500). This is used by clients to talk to the HTTP API. TCP only. DNS Interface (Default 8600). Used to resolve DNS queries. TCP and UDP. You can configure consul services to run on different ports by editing the config file. For example setting the dns interface on port 53 and the HTTP API on port 80. More details on port configuration is here. { "ports": { "dns": 53, "http": 80 } }
Consul
30,684,262
26
I'm evaluating a few distributed key-value stores, and etcd and Consul looks both very promising. I am interested in service discovery, health monitoring and config services. I like the extra features that Consul gives, but I cannot determine whether it persists the Key-Value store when the service goes down? It seems that etcd offers persistence. Any advice?
Consul agents (cilent & server) persist data into data-dir. The only case where agent doesn't persist data is where its started in "-dev" mode.
Consul
30,802,422
20
Recently several service discovery tools have become popular/"mainstream", and I’m wondering under what primary use cases one should employ them instead of traditional load balancers. With LBs, you cluster a bunch of nodes behind the balancer, and then clients make requests to the balancer, who then (typically) round robins those requests to all the nodes in the cluster. With service discovery (Consul, ZK, etc.), you let a centralized “consensus” service determine what nodes for particular service are healthy, and your app connects to the nodes that the service deems as being healthy. So while service discovery and load balancing are two separate concepts, service discovery gives you load balancing as a convenient side effect. But, if the load balancer (say HAProxy or nginx) has monitoring and health checks built into it, then you pretty much get service discovery as a side effect of load balancing! Meaning, if my LB knows not to forward a request to an unhealthy node in its cluster, then that’s functionally equivalent to a consensus server telling my app not to connect to an unhealty node. So to me, service discovery tools feel like the “6-in-one,half-dozen-in-the-other” equivalent to load balancers. Am I missing something here? If someone had an application architecture entirely predicated on load balanced microservices, what is the benefit (or not) to switching over to a service discovery-based model?
Load balancers typically need the endpoints of the resources it balances the traffic load. With the growth of microservices and container based applications, runtime created dynamic containers (docker containers) are ephemeral and doesnt have static end points. These container endpoints are ephemeral and they change as they are evicted and created for scaling or other reasons. Service discovery tools like Consul are used to store the endpoints info of dynamically created containers (docker containers). Tools like consul-registrator running on container hosts registers container end points in service discovery tools like consul. Tools like Consul-template will listen for changes to containers end points in consul and update the load balancer (nginx) for sending the traffic to. Thus both Service Discovery Tools like Consul and Load Balancing tools like Nginx co-exist to provide runtime service discovery and load balancing capability respectively. Follow up: what are the benefits of ephemeral nodes (ones that come and go, live and die) vs. "permanent" nodes like traditional VMs? [DDG]: Things that come quickly to my mind: Ephemeral nodes like docker containers are suited for stateless services like APIs etc. (There is traction for persistent containers using external volumes - volume drivers etc) Speed: Spinning up or destroying ephemeral containers (docker containers from image) takes less than 500 milliseconds as opposed to minutes in standing up traditional VMs Elastic Infrastructure: In the age of cloud we want to scale out and in according to users demand which implies there will be be containers of ephemeral in nature (cant hold on to IPs etc). Think of a markerting campaign for a week for which we expect 200% increase in traffic TPS, quickly scale with containers and then post campaign, destroy it. Resource Utilization: Data Center or Cloud is now one big computer (compute cluster) and containers pack the compute cluster for max resource utilization and during weak demand destroy the infrastructure for lower bill/resource usage. Much of this is possible because of lose coupling with ephemeral containers and runtime discovery using service discovery tool like consul. Traditional VMs and tight binding of IPs can stifle this capability.
Consul
32,334,161
20
I have: one mesos-master in which I configured a consul server; one mesos-slave in which I configure consul client, and; one bootstrap server for consul. When I hit start I am seeing the following error: 2016/04/21 19:31:31 [ERR] agent: failed to sync remote state: rpc error: No cluster leader 2016/04/21 19:31:44 [ERR] agent: coordinate update error: rpc error: No cluster leader How do I recover from this state?
Did you look at the Consul docs ? It looks like you have performed a ungraceful stop and now need to clean your raft/peers.json file by removing all entries there to perform an outage recovery. See the above link for more details.
Consul
36,772,098
17
I am attempting to move from Eureka to Consul for service discovery and am having an issue - my gateway service registers and my customer-service registers, but the gateway service will not route requests to the customer-service automatically. Routes I have specifically defined in the gateway Controller that use Feign clients to route work fine, but before (with Eureka) I could make a request to any path like "/customer-service/blah" (where customer-service is the registered name) and the gateway would just forward the request on to the downstream microservice. Here is my gateway bootstrap.yml (it's in bootstrap and not application because I am also using consul for config) spring: application: name: gateway-api cloud: consul: config: watch: wait-time: 30 discovery: prefer-ip-address: true instanceId: ${spring.application.name}:${spring.application.instance_id:${random.value}}
Try this I think this help you to solve your problem.. This is my gateway bootstrap.yml file spring: application: name: gateway-service --- spring: profiles: default cloud: consul: config: prefix: config/dev/ format: FILES host: localhost port: 8500 discovery: prefer-ip-address: true spring.profiles.active: dev I use this dependency for gateway and for all applications <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-discovery</artifactId> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-consul-config</artifactId> </dependency> consul use as my configuration server. then I add consul to this configurations. configuration path is /config/dev/gateway.yml zuul: prefix: /api ignoredServices: '*' host: connect-timeout-millis: 20000 socket-timeout-millis: 20000 routes: customer-service: path: /customer/** serviceId: customer-service stripPrefix: false sensitiveHeaders: Cookie,Set-Cookie Gateway service spring boot application annotate like below @SpringBootApplication @EnableDiscoveryClient @EnableZuulProxy public class GatewayServiceApplication { public static void main(String[] args) { SpringApplication.run(GatewayServiceApplication.class, args); } // End main () }// End GatewayServiceApplication if you make your application like this you can use routs your prefer way. sample consul configuration
Consul
42,983,145
15
I am using consul's healthcheck feature, and I keep getting these these "dead" containers: CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES 20fd397ba638 progrium/consul:latest "\"/bin/bash -c 'cur 15 minutes ago Dead What is exactly a "Dead" container? When does a stopped container become "Dead"? For the record, I run progrium/consul + gliderlabs/registrator images + SERVICE_XXXX_CHECK env variables to do health checking. It runs a healthcheck script running an image every X secs, something like docker run --rm my/img healthcheck.sh I'm interested in general to what "dead" means and how to prevent it from happening. Another peculiar thing is that my dead containers have no name. this is some info from the container inspection: "State": { "Dead": true, "Error": "", "ExitCode": 1, "FinishedAt": "2015-05-30T19:00:01.814291614Z", "OOMKilled": false, "Paused": false, "Pid": 0, "Restarting": false, "Running": false, "StartedAt": "2015-05-30T18:59:51.739464262Z" }, The strange thing is that only every now and then a container becomes dead and isn't removed. Thank you Edit: Looking at the logs, I found what makes the container stop fail: Handler for DELETE /containers/{name:.*} returned error: Cannot destroy container 003876e41429013e46187ebcf6acce1486bc5011435c610bd163b159ba550fbc: Driver aufs failed to remove root filesystem 003876e41429013e46187ebcf6acce1486bc5011435c610bd163b159ba550fbc: rename /var/lib/docker/aufs/diff/003876e41429013e46187ebcf6acce1486bc5011435c610bd163b159ba550fbc /var/lib/docker/aufs/ diff/003876e41429013e46187ebcf6acce1486bc5011435c610bd163b159ba550fbc-removing: device or resource busy Why does this happen? edit2: found this: https://github.com/docker/docker/issues/9665
Update March 2016: issue 9665 has just been closed by PR 21107 (for docker 1.11 possibly) That should help avoid the "Driver aufs failed to remove root filesystem", "device or resource busy" problem. Original answer May 2015 Dead is one if the container states, which is tested by Container.Start() if container.removalInProgress || container.Dead { return fmt.Errorf("Container is marked for removal and cannot be started.") } It is set Dead when stopping fails, in order to prevent that container to be restarting. Amongst the possible cause of failure, see container.Kill(). It means kill -15 and kill -9 are both failing. // 1. Send a SIGTERM if err := container.killPossiblyDeadProcess(15); err != nil { logrus.Infof("Failed to send SIGTERM to the process, force killing") if err := container.killPossiblyDeadProcess(9); err != nil { That usually mean, as the OP mention, a busy device or resource, preventing the process to be killed.
Consul
30,550,472
14
I am getting this error when I am running any "consul members" on consul server and clients. The port is in LISTENING state and I made sure there is no firewall blocking. I get this error when in run the same in the consul client: Error retrieving members: Get http://127.0.0.1:8500/v1/agent/members: dial tcp 127.0.0.1:8500: connectex: No connection could be made because the target machine actively refused it. When I make the above request with the private IP, I get the required output. Can I change the configuration anywhere so that it listens on the private IP for requests?
It seems that your consul members lacks the option -http-addr=.... Example consul members -http-addr=10.10.10.10:8500 while assuming you use the standard port 8500 of the consul agent and that you started consul via: consul agent -client=10.10.10.10 #... Where to find the documentation? In the Consul Documentation under Running an Agent: "Client Addr": If you change this address or port, you'll have to specify a -http-addr whenever you run commands such as consul members to indicate how to reach the agent. Or offline via consul members -help: http-addr=<address> Theaddressand port of the Consul HTTP agent. The value can be an IP address or DNS address, but it must also include the port. This can also be specified via the CONSUL_HTTP_ADDR environment variable. The default value is http://127.0.0.1:8500. The scheme can also be set to HTTPS by setting the environment variable CONSUL_HTTP_SSL=true.
Consul
43,730,582
13
We're dockerizing our micro services app, and I ran into some discovery issues. The app is configured as follows: When the a service is started in 'non-local' mode, it uses Consul as its Discovery registry. When a service is started in 'local' mode, it automatically binds an address per service (For example, tcp://localhost:61001, tcp://localhost:61002 and so on. Hard coded addresses) After dockerizing the app (for local mode only, for now) each service is a container (Docker images orchestrated with docker-compose. And with docker-machine, if that matters) But one service can not interact with another service since they are not on the same machine and tcp://localhost:61001 will obviously not work. Using docker-compose with links and specifying localhost as an alias (service:localhost) didn't work. Is there a way for 2 containers to "share" the same localhost? If not, what is the best way to approach this? I thought about using specific hostname per service, and then specify the hostname in the links section of the docker-compose. (But I doubt that this is the elegant solution) Or maybe use a dockerized version of Consul and integrate with it? This post: How to share localhost between two different Docker containers? provided some insights about why localhost shouldn't be messed with - but I'm still quite puzzled on what's the correct approach here. Thanks!
But one service can not interact with another service since they are not on the same machine and tcp://localhost:61001 will obviously not work. Actually, they can. You are right that tcp://localhost:61001 will not work, because using localhost within a container would be referring to the container itself, similar to how localhost works on any system by default. This means that your services cannot share the same host. If you want them to, you can use one container for both services, although this really isn't the best design since it defeats one of the main purposes of Docker Compose. The ideal way to do it is with docker-compose links, the guide you referenced shows how to define them, but to actually use them you need to use the linked container's name in URLs as if the linked container's name had an IP mapping defined in the original container's /etc/hosts (not that it actually does, but just so you get the idea). If you want to change it to be something different from the name of the linked container, you can use a link alias, which are explained in the same guide you referenced. For example, with a docker-compose.yml file like this: a: expose: - "9999" b: links: - a With a listening on 0.0.0.0:9999, b can interact with a by making requests from within b to tcp://a:9999. It would also be possible to shell into b and run ping a which would send ping requests to the a container from the b container. So in conclusion, try replacing localhost in the request URL with the literal name of the linked container (or the link alias, if the link is defined with an alias). That means that tcp://<container_name>:61001 should work instead of tcp://localhost:61001 Just make sure you define the link in docker-compose.yml. Hope this helps
Consul
45,551,966
13
What is the best way to get the current docker container IP address within the container itself using .net core? I try to register my container to a Consul server which is hosted on the Docker host (not as a container) and I need to get the container IP address on startup to make the registration. Because the IP addresses change on any container startup I can't just hard-code it into the appsettings.json. I followed this tutorial. And when it comes to this section: // Get server IP address var features = app.Properties["server.Features"] as FeatureCollection; var addresses = features.Get<IServerAddressesFeature>(); var address = addresses.Addresses.First(); // Register service with consul var uri = new Uri(address); var registration = new AgentServiceRegistration() { ID = $"{consulConfig.Value.ServiceID}-{uri.Port}", Name = consulConfig.Value.ServiceName, Address = $"{uri.Scheme}://{uri.Host}", Port = uri.Port, Tags = new[] { "Students", "Courses", "School" } }; The received address contains only the loopback address and not the actual container address (as seen from outside - the host where Consul is running). I already tried to use the HttpContext (which is null in the startup class) and the IHttpContextAccessor which also does not contain anything at this time. EDIT: This is a part of my appsettings.json: "ServiceRegistry": { "Uri": "http://172.28.112.1:8500", "Name": "AuthServiceApi", "Id": "auth-service-api-v1", "ContainerAddress": "http://<CONTAINER_IP/DNS>", "Checks": [ { "Service": "/health", "Timeout": 5, "Interval": 10 } ], "Tags": [ "Auth", "User" ] } The Uri is the one from my host system and I managed to register the service in Consul. The missing part is the <CONTAINER_IP/DNS> which is needed for Consul to perform some checks for that particular container. Here I need either the IP of the container or the DNS on which it is accessible from the host system. I know that this IP will switch with every container starup and it's in the settings only for demonstration purpose (I'm happy if I can get the IP at startup time).
Ok, I got it working and it was much easier than I thought. var name = Dns.GetHostName(); // get container id var ip = Dns.GetHostEntry(name).AddressList.FirstOrDefault(x => x.AddressFamily == AddressFamily.InterNetwork); With the container_id/name I could get the IP with an easy compare if it's an IP4 address. I then can use this address and pass it to Consul. The health checks can now successfully call the container with it's IP from the outside host. I'm still not 100% satisfied with the result because it relies on the "first" valid IP4 address in the AddressList (currently, there are no more so I got this going for me). Any better / more generic solution would still be welcome.
Consul
51,925,599
13
I am trying to spin a Consul server on docker container and use it as config server for my SpringBoot cloud application. For that I want to have some pre-configured data(Key-Value pairs) in Consul. My current config in docker-compose.yml is: consul: image: "progrium/consul:latest" container_name: "consul" ports: - '9330:8300' - '9400:8400' - '9500:8500' - '9600:53' command: "-server -bootstrap -ui-dir /ui" Is there a way to pre-populate key-value pairs?
Here a very similar approach but maybe simpler and it works. Does not require compose, just Docker and all is done in the image. This directory structure: bootstrap/values.json bootstrap/start.sh bootstrap/init.sh Dockerfile Dockerfile FROM consul RUN mkdir /tmp/bootstrap COPY bootstrap/* /tmp/bootstrap/ RUN chmod 755 /tmp/bootstrap/* RUN dos2unix /tmp/bootstrap/* CMD /tmp/bootstrap/start.sh bootstrap/start.sh #!/bin/sh /tmp/bootstrap/init.sh & consul agent -dev -client=0.0.0.0 bootstrap/init.sh #!/bin/sh echo "bootstrap values - wait until port is available" while ! nc -z localhost 8500; do sleep 1 done echo "executing consul kv command" consul kv import @/tmp/bootstrap/values.json bootstrap/values.json [ { "key": "config/", "flags": 0, "value": "" }, { "key": "config/yoursoftware/", "flags": 0, "value": "" }, ] The main challenge is that RUN can not process background tasks and CMD is the only main executable which must run at the end. So background processes can be started in via CMD, which uses here a shell script (start.sh). In that script the ampersand symbol gives under linux a way to start a process and throw it to background. It will execute the init.sh. In that it must now wait until the port is ready and then it can use the import.
Consul
43,598,002
12
In Consul you can have many agents as servers or clients. Amongst all servers one is chosen as the leader. From the agent's point of view, how does it know it is the leader?
The Consul leader is elected via an implementation of the Raft Protocol from amongst the Quorum of Consul Servers. Only Consul instances that are configured as Servers participate in the Raft Protocol communication. The Consul Agent (the daemon) can be started as either a Client or a Server. Only a Server can be the leader of a Datacenter. The Raft Protocol was created by Diego Ongaro and John Ousterhout from Stanford University in response to the complexity of existing consensus protocols such as Paxos. Raft elects a leader via the use of randomized timers. The algorithm is detailed in Ongaro and Ousterhout's paper. Consul instances that are configured as Clients communicate with the cluster via the Gossip Protocol which is based on Serf. Serf communication is eventually consistent. The Serf cluster has no central server, each node is considered equal. All nodes (Clients and Servers) in participating the Gossip/Serf Protocol spread messages to their neighbors, which in turn spread messages to their neighbors until the message has propagated to the entire cluster. Sort of like the infection path of a zombie apocalypse. This is done to greatly reduce communication overhead in the cluster as it scales to potentially tens of thousands of nodes. Consul Clients can forward messages to any Consul Server which will then forward the message to the Leader. Consul Clients do not need to care which Consul Server is the Leader. Only the Servers need to care. The Consul HTTP API running on any Consul Server will tell you which Server is the leader at $ANY_CONSUL_SERVER/v1/status/leader. However, this has nothing to do with how Consul Agents do leader election.
Consul
27,724,519
11
I am new to both Docker and Consul, and am trying to get a feel for how containerized apps could use Consul for both service registry and KV pair config management ("configuration"). My understanding was that I could: Create an image that runs Consul server, so something like this; then Spin up three of these Docker-Consul containers (thus forming a cluster/quorum) on myvm01.example.com (an Ubuntu VM); then Refactor my app to use Consul and create a Docker image that runs my app and Consul agent, with the agent configured to join the 3-node quorum at startup. On startup, my app uses the local Consul agent to pull down all of its configurations, stored as KV pairs. It also pulls in registered/healthy services, and uses a local load balancing tool to balance the services it integrates with. Run my app's containers on, say, myvm02.example.com (another Ubuntu VM). So to begin with, if any of this seems like I am misunderstanding the normal/proper uses of Docker and Consul (sans Registrator), please begin by correcting me! Assuming I'm more or less correct, I recently stumbled across Registrator and am now even more confused. Registrator seems to be some middleman between your app containers and your Consul (or whatever registry you use) servers. After reading their Quickstart tutorial, it sounds like what you're supposed to do is: Deploy my Consul cluster/quorum containers to myvm01.example.com like before Instead of "Dockerizing" my app to use Consul directly, I simply integrate it with Registrator Then I deploy a Registrator container somewhere, and configure it to integrate with Consul Then I deploy my app containers. They integrate with Registrator, and Registrator in turn integrates with Consul. My concerns: Is my understanding here correct or way off base? If so, how? What is actually gained by the addition of Registrator. It doesn't seem (to the untrained eye at least) like anything more than a layer of indirection between the app and the service registry. Will I still be able to leverage Consul's KV config service through Registrator?
Is my understanding here correct or way off base? If so, how? It seems to me, that it's not a good solution, to have all cluster/quorum members running inside the same VM. It's not so bad if you use it for development or tetsing or something, where you don't care much about reliability, but not for production. Once your VM dies, you'll loose all the advantages you have by creating a cluster. And even more, you can loose all the data you have in K/V store, because you are running Consul servers inside a docker containers, which should be additionaly configured to share the configuration between runs. As for the rest, I see it the same as you. What is actually gained by the addition of Registrator. From my point of view, the main thing is, that you don't have to provide an instance of Consul Agent in every container you run. And the container with the image you run is responsible only for their main functions, not for registering itself somewhere. You may simply pull an image and just run a container with it, to make it's service available, without making additional work. Will I still be able to leverage Consul's KV config service through Registrator? Unfortunately, no. At least, we didn't find a solution to use it this way, when we were looking for something to make service discovering and configuration management. We came to conclusion, that Registrator is not a proxy for K/V store and is used only to automate service discovery. So you have to use some other logic to access consul's K/V store. Update: furthermore, here is 2 articles: "Automatic Docker Service Announcement with Registrator" and "Automatic container registration with Consul and Registrator", I found usefull to understand Registrator role in service discovery process.
Consul
32,745,275
11
How do I use Consul to make sure only one service is performing a task? I've followed the examples in http://www.consul.io/ but I am not 100% sure which way to go. Should I use KV? Should I use services? Or should I use a register a service as a Health Check and make it be callable by the cluster at a given interval? For example, imagine there are several data centers. Within every data center there are many services running. Every one of these services can send emails. These services have to check if there are any emails to be sent. If there are, then send the emails. However, I don't want the same email be sent more than once. How would it make sure all emails are sent and none was sent more than once? I could do this using other technologies, but I am trying to implement this using Consul.
This is exactly the use case for Consul Distributed Locks For example, let's say you have three servers in different AWS availability zones for fail over. Each one is launched with: consul lock -verbose lock-name ./run_server.sh Consul agent will only run the ./run_server.sh command on which ever server acquires the lock first. If ./run_server.sh fails on the server with the lock Consul agent will release the lock and another node which acquires it first will execute ./run_server.sh. This way you get fail over and only one server running at a time. If you registered your Consul health checks properly you'll be able to see that the server on the first node failed and you can repair and restart the consul lock ... on that node and it will block until it can acquire the lock. Currently, Distributed Locking can only happen within a single Consul Datacenter. But, since it is up to you to decide what a Consul Servers make up a Datacenter, you should be able to solve your issue. If you want locking across Federated Consul Datacenters you'll have to wait for it, since it's a roadmap item.
Consul
27,679,341
10
I'm trying to self register my ASP.NET Core application to Consul registry on startup and deregister it on shutdown. From here I can gather that calling the http api [put /v1/agent/service/register] might be the way to go (or maybe not!). From my app, I thought I'll target the Startup class, starting with adding the my .json file public Startup(IHostingEnvironment env) { var builder = new Configuration().AddJsonFile("consulconfig.json"); Configuration = builder.Build(); } But now, I'm stuck as ConfigureServices method tells me thats where I add services to the container, and Configure method is where I configure the Http request pipeline. Anybody to point me in the right directions, online readings, examples, etc.
First of all I recommend to use Consul.NET to interact with Consul. Using it, a service registration may look like: var registration = new AgentServiceRegistration { Name = "foo", Port = 4242, Address = "http://bar" }; using (var client = new ConsulClient()) { await client.Agent.ServiceRegister(registration); } Now let's integrate this code into ASP.NET Core startup process with help of DI and loose coupling. Read your json file into ConsulOptions instance (DTO without any logic): public void ConfigureServices(IServiceCollection services) { services.AddOptions(); services.Configure<ConsulOptions>(Configuration); } Encapsulate all Consul-related logic in class ConsulService accepting ConsulOptions as a dependency: public class ConsulService : IDisposable { public ConsulService(IOptions<ConsulOptions> optAccessor) { } public void Register() { //possible implementation of synchronous API client.Agent.ServiceRegister(registration).GetAwaiter().GetResult(); } } Add the class itself to the DI container: services.AddTransient<ConsulService>(); Then create an extention method of IApplicationBuilder and call it: public void Configure(IApplicationBuilder app) { app.ConsulRegister(); } In ConsulRegister implementation we add our hooks on application start/stop: public static class ApplicationBuilderExtensions { public static ConsulService Service { get; set; } public static IApplicationBuilder ConsulRegister(this IApplicationBuilder app) { //design ConsulService class as long-lived or store ApplicationServices instead Service = app.ApplicationServices.GetService<ConsulService>(); var life = app.ApplicationServices.GetService<IApplicationLifetime>(); life.ApplicationStarted.Register(OnStarted); life.ApplicationStopping.Register(OnStopping); return app; } private static void OnStarted() { Service.Register(); //finally, register the API in Consul } } Locking absence and static fields are OK because the Startup class is executed exactly once on application start. Don't forget to de-register the API in OnStopping method!
Consul
39,467,200
10
I'm in the process of upgrading an environment with new versions of Ubuntu, Consul and Spring Boot. At first glance, everything seems to be working just fine. The app connects to Consul, requests its configuration and boots up. After a few minutes however, something breaks and this message is repeated approximately every 2 seconds: com.ecwid.consul.transport.TransportException: javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake at com.ecwid.consul.transport.AbstractHttpTransport.executeRequest(AbstractHttpTransport.java:77) at com.ecwid.consul.transport.AbstractHttpTransport.makeGetRequest(AbstractHttpTransport.java:34) at com.ecwid.consul.v1.ConsulRawClient.makeGetRequest(ConsulRawClient.java:128) at com.ecwid.consul.v1.catalog.CatalogConsulClient.getCatalogServices(CatalogConsulClient.java:120) at com.ecwid.consul.v1.ConsulClient.getCatalogServices(ConsulClient.java:372) at org.springframework.cloud.consul.discovery.ConsulCatalogWatch.catalogServicesWatch(ConsulCatalogWatch.java:129) at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54) at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515) at java.base/java.util.concurrent.FutureTask.runAndReset(FutureTask.java:305) at java.base/java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:305) at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) at java.base/java.lang.Thread.run(Thread.java:834) Caused by: javax.net.ssl.SSLHandshakeException: Remote host terminated the handshake at java.base/sun.security.ssl.SSLSocketImpl.handleEOF(SSLSocketImpl.java:1313) at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1152) at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1055) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:395) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) I traced the fact that the message appears every 2 seconds to the apps health-check. Once the error occurs for the first time, it continues to occur on each subsequent health-check. This was confirmed by turning the health-check off and rebooting. This caused the error to occur exactly once, when the TTL on the Consul-data was reached. This is where my understanding of the problem ends. I've tried to trace it to several things, but none of these led to a solution: Checking the certificates - The certificates used are generated by Vault, signed by an intermediate certificate, signed by a self-signed root-certificate. These are then placed in a pkcs12 bundle, with the key and provided to the application. This works on all TLS-connections, also from the CLI tools and with curl. This seems like a dead end. Network Connectivity - Since the connection is being reset, I tried to see if it was due to firewall or security-group issues. However, the relevant port (8501) is open for both TCP and UDP traffic and all manual tests with nc show the ports to be reachable. IPv6 bug - Somewhere, I found a post saying this could be due to a bug with IPv6. I tried turning IPv6 off on the machine, reboot everything and try again. No luck, still the same error. Versions of Consul - I tried running the application in our old environment, where Consul 1.2.3 is running and the error there does not show up. I'm still in the process of trying to find out if there is a specific Consul-version where this problem begins to occur, but haven't found it yet. TLS bugs - Between Consul 1.2.3 and 1.7.2 there have been some changes to Consul's TLS-support as well as to the underlying Go TLS implementations. This came to light when testing with Consul 1.4.0, which provided a slightly different TLS error. Some suggestions on the internet were that there are conflicting implementations between Go and OpenJDK. I tried forcing the Java-application to use TLS 1.2, but again, no luck. Handshake Debugging - Based on a tip from the comments, I used -Djavax.net.debug=ssl:handshake to find out what is happening during the handshake. During the first couple of minutes, the produced extra output shows what looks to me like normal handshakes. Once the problem occurs, the output of the handshakes stops right after "Produced Client Hello message" with a "Remote host terminated the handshake". I haven't been able to do the same with the other side of this connection. Consul is a Golang application. If anyone knows how to get the same debugging-information for a Golan app, please advise. I hope someone has an idea about how to find the cause of this problem, or better yet, have a solution for it.
After some more digging and trying other versions of things. I found that using GraalVM produces a different, but slightly more descriptive error. When trying to connect to the Consul-application, it immediately terminates with this message: Caused by: javax.net.ssl.SSLHandshakeException: extension (5) should not be presented in certificate_request at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:131) at java.base/sun.security.ssl.Alert.createSSLException(Alert.java:117) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:307) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:263) at java.base/sun.security.ssl.TransportContext.fatal(TransportContext.java:254) at java.base/sun.security.ssl.SSLExtensions.<init>(SSLExtensions.java:90) at java.base/sun.security.ssl.CertificateRequest$T13CertificateRequestMessage.<init>(CertificateRequest.java:818) at java.base/sun.security.ssl.CertificateRequest$T13CertificateRequestConsumer.consume(CertificateRequest.java:922) at java.base/sun.security.ssl.SSLHandshake.consume(SSLHandshake.java:392) at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:443) at java.base/sun.security.ssl.HandshakeContext.dispatch(HandshakeContext.java:421) at java.base/sun.security.ssl.TransportContext.dispatch(TransportContext.java:177) at java.base/sun.security.ssl.SSLTransport.decode(SSLTransport.java:164) at java.base/sun.security.ssl.SSLSocketImpl.decode(SSLSocketImpl.java:1151) at java.base/sun.security.ssl.SSLSocketImpl.readHandshakeRecord(SSLSocketImpl.java:1062) at java.base/sun.security.ssl.SSLSocketImpl.startHandshake(SSLSocketImpl.java:402) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.createLayeredSocket(SSLConnectionSocketFactory.java:394) at org.apache.http.conn.ssl.SSLConnectionSocketFactory.connectSocket(SSLConnectionSocketFactory.java:353) at org.apache.http.impl.conn.DefaultHttpClientConnectionOperator.connect(DefaultHttpClientConnectionOperator.java:134) at org.apache.http.impl.conn.PoolingHttpClientConnectionManager.connect(PoolingHttpClientConnectionManager.java:353) at org.apache.http.impl.execchain.MainClientExec.establishRoute(MainClientExec.java:380) at org.apache.http.impl.execchain.MainClientExec.execute(MainClientExec.java:236) at org.apache.http.impl.execchain.ProtocolExec.execute(ProtocolExec.java:184) at org.apache.http.impl.execchain.RetryExec.execute(RetryExec.java:88) at org.apache.http.impl.execchain.RedirectExec.execute(RedirectExec.java:110) at org.apache.http.impl.client.InternalHttpClient.doExecute(InternalHttpClient.java:184) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:71) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:220) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:164) at org.apache.http.impl.client.CloseableHttpClient.execute(CloseableHttpClient.java:139) at com.ecwid.consul.transport.AbstractHttpTransport.executeRequest(AbstractHttpTransport.java:61) This then led me to an issue on the Golang GitHub-page: https://github.com/golang/go/issues/35722. It details similar issues from various people, but constantly with slightly different details. In that thread, there is mention of a discrepancy between TLS 1.3 implementations between Go and Java. The OpenJDK-maintainers also chip in and refer to this issue: https://bugs.openjdk.java.net/browse/JDK-8236039. It has been fixed and closed, but is not yet available in any of my regular binary distributions. I will try to check whether that version actually fixes the problem. However, there is a workaround by forcing Java to use only TLS1.2. You can do this by adding -Djdk.tls.client.protocols=TLSv1.2 to the startup arguments.
Consul
61,813,667
10
Nomad has three different ways to map ports: Network stanza under group level Network stanza under config -> resources level port_map stanza under config level What is the difference and when I should use which?
First of all port_map is deprecated, so you shouldn't be using that as part of task driver configuration. Up until Nomad 0.12, ports could be specified in a task's resource stanza and set using the docker port_map field. As more features have been added to the group network resource allocation, task based network resources are deprecated. With it the port_map field is also deprecated and can only be used with task network resources. Users should migrate their jobs to define ports in the group network stanza and specified which ports a task maps with the ports field. port in the group network stanza defines labels that can be used to identify the port in service discovery. This label is also used as apart of environment variable name that indicates which port your application should bind to. ports at the task level specifies which port from network stanza should be available inside task allocation/container. From official docs A Docker container typically specifies which port a service will listen on by specifying the EXPOSE directive in the Dockerfile. Because dynamic ports will not match the ports exposed in your Dockerfile, Nomad will automatically expose any ports specified in the ports field. TLDR; So there is only one correct definition: job "example" { group "example-group" { network { # Dynamic ports port "foo" {} port "bar" {} # Mapped ports port "http" { to = 80 } port "https" { to = 443 } # Static ports port "lb" { static = 8080 } } task "task-1" { driver = "docker" config { ... ports = [ "foo", "http", ] } } task "task-2" { driver = "docker" config { ... ports = [ "bar", "https", ] } } task "task-3" { driver = "docker" config { ... ports = [ "lb", ] } } } } Consider running this type of job file (with whatever images). Then you will get the following port mapping between a backend and containers: for port in $(docker ps --format "{{.Ports}}"); do echo $port; done | grep tcp | cut -d':' -f 2 # Dynamic ports 'foo' and 'bar' # 25968->25968/tcp, # 29080->29080/tcp, # Mapped ports 'http' and 'https' # 29936->80/tcp, # 20987->443/tcp, # Static port 'lb' # 8080->8080/tcp, Now, if you get inside task-1 allocation/container and check env variables, then you would be able to get values for allocated ports if your tasks need to communicate with one another. env | grep NOMAD | grep PORT # NOMAD_PORT_bar=29080 # NOMAD_HOST_PORT_bar=29080 # NOMAD_PORT_foo=25968 # NOMAD_HOST_PORT_foo=25968 # NOMAD_PORT_http=80 # NOMAD_HOST_PORT_http=29936 # NOMAD_PORT_https=443 # NOMAD_HOST_PORT_https=20987 # NOMAD_PORT_lb=8080 # NOMAD_HOST_PORT_lb=8080 In order to make communication between services easier, it is better to use service discovery, e.g. Consul (also from HashiCorp) and to make you life even easier consider some sort of load balancer, e.g. Fabio or Traefik. Here is a nice blog post from HashiCorp's Engineer about it.
Consul
63,601,913
10
As I understand, Istio VirtualService is kind of abstract thing, which tries to add an interface to the actual implementation like the service in Kubernetes or something similar in Consul. When use Kubernetes as the underlying platform for Istio, is there any difference between Istio VirtualService and Kubernetes Service or are they the same?
Kubernetes service Kubernetes service manage a pod's networking. It specifies whether your pods are exposed internally (ClusterIP), externally (NodePort or LoadBalancer) or as a CNAME of other DNS entries (externalName). As an example this foo-service will expose the pods with label app: foo. Any requests sent to the node on port 30007 will be forwarded to the pod on port 80. apiVersion: v1 kind: Service metadata: name: foo-service spec: type: NodePort selector: app: foo ports: - port: 80 targetPort: 80 nodePort: 30007 Istio virtualservice Istio virtualservice is one level higher than Kuberenetes service. It can be used to apply traffic routing, fault injection, retries and many other configurations to services. As an example this foo-retry-virtualservice will retry 3 times with a timeout 2s each for failed requests to foo. apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: foo-retry-virtualservice spec: hosts: - foo http: - route: - destination: host: foo retries: attempts: 3 perTryTimeout: 2s Another example of this foo-delay-virtualservice will apply a 0.5s delay to 0.1% of requests to foo. apiVersion: networking.istio.io/v1alpha3 kind: VirtualService metadata: name: foo-delay-virtualservice spec: hosts: - foo http: - fault: delay: percentage: value: 0.1 fixedDelay: 5s route: - destination: host: foo Ref https://kubernetes.io/docs/concepts/services-networking/service/ https://kubernetes.io/docs/concepts/services-networking/dns-pod-service/ https://istio.io/latest/docs/reference/config/networking/virtual-service/ https://istio.io/latest/docs/concepts/traffic-management/#virtual-services
Istio
53,743,219
38
Traefik is a reverse HTTP proxy with several supported backends, Kubernetes included. How does Istio compare?
It's something of an apples-to-oranges comparison. Edge proxies like Traefik or Nginx are best compared to Envoy - the proxy that Istio leverages. An Envoy proxy is installed automatically by Istio adjacent to every pod. Istio provides several higher level capabilities beyond Envoy, including routing, ACLing and service discovery and access policy across a set of services. In effect, it stitches a set of Envoy enabled services together. This design pattern is often called a service mesh. Istio is also currently limited to Kubernetes deployments in a single cluster, though work is in place to remove these restrictions in time.
Istio
44,212,356
35