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 currently coding in Swift, and I've got an error: No such module Social But I don't understand, because the module is in my project, declared in "Linked frameworks and Libraries" and in "Embedded Binaries". The frameworks is in Objective-C, so I wrote a Bridge Header for it. Please, how can I make Xcode recognize the framework?
In case it's Friday afternoon or anytime after 1am: Opening xcodeproj instead of xcworkspace will cause an error like this...
Swift
29,500,227
553
Is there a way to get the device model name (iPhone 4S, iPhone 5, iPhone 5S, etc) in Swift? I know there is a property named UIDevice.currentDevice().model but it only returns device type (iPod touch, iPhone, iPad, iPhone Simulator, etc). I also know it can be done easily in Objective-C with this method: #import <sys/utsname.h> struct utsname systemInfo; uname(&systemInfo); NSString* deviceModel = [NSString stringWithCString:systemInfo.machine encoding:NSUTF8StringEncoding]; But I'm developing my iPhone app in Swift so could someone please help me with the equivalent way to solve this in Swift?
I made this "pure Swift" extension on UIDevice. If you are looking for a more elegant solution you can use my µ-framework DeviceKit published on GitHub (also available via CocoaPods, Carthage and Swift Package Manager). Here's the code: import UIKit public extension UIDevice { static let modelName: String = { var systemInfo = utsname() uname(&systemInfo) let machineMirror = Mirror(reflecting: systemInfo.machine) let identifier = machineMirror.children.reduce("") { identifier, element in guard let value = element.value as? Int8, value != 0 else { return identifier } return identifier + String(UnicodeScalar(UInt8(value))) } func mapToDevice(identifier: String) -> String { // swiftlint:disable:this cyclomatic_complexity #if os(iOS) switch identifier { case "iPod5,1": return "iPod touch (5th generation)" case "iPod7,1": return "iPod touch (6th generation)" case "iPod9,1": return "iPod touch (7th generation)" case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4" case "iPhone4,1": return "iPhone 4s" case "iPhone5,1", "iPhone5,2": return "iPhone 5" case "iPhone5,3", "iPhone5,4": return "iPhone 5c" case "iPhone6,1", "iPhone6,2": return "iPhone 5s" case "iPhone7,2": return "iPhone 6" case "iPhone7,1": return "iPhone 6 Plus" case "iPhone8,1": return "iPhone 6s" case "iPhone8,2": return "iPhone 6s Plus" case "iPhone9,1", "iPhone9,3": return "iPhone 7" case "iPhone9,2", "iPhone9,4": return "iPhone 7 Plus" case "iPhone10,1", "iPhone10,4": return "iPhone 8" case "iPhone10,2", "iPhone10,5": return "iPhone 8 Plus" case "iPhone10,3", "iPhone10,6": return "iPhone X" case "iPhone11,2": return "iPhone XS" case "iPhone11,4", "iPhone11,6": return "iPhone XS Max" case "iPhone11,8": return "iPhone XR" case "iPhone12,1": return "iPhone 11" case "iPhone12,3": return "iPhone 11 Pro" case "iPhone12,5": return "iPhone 11 Pro Max" case "iPhone13,1": return "iPhone 12 mini" case "iPhone13,2": return "iPhone 12" case "iPhone13,3": return "iPhone 12 Pro" case "iPhone13,4": return "iPhone 12 Pro Max" case "iPhone14,4": return "iPhone 13 mini" case "iPhone14,5": return "iPhone 13" case "iPhone14,2": return "iPhone 13 Pro" case "iPhone14,3": return "iPhone 13 Pro Max" case "iPhone14,7": return "iPhone 14" case "iPhone14,8": return "iPhone 14 Plus" case "iPhone15,2": return "iPhone 14 Pro" case "iPhone15,3": return "iPhone 14 Pro Max" case "iPhone15,4": return "iPhone 15" case "iPhone15,5": return "iPhone 15 Plus" case "iPhone16,1": return "iPhone 15 Pro" case "iPhone16,2": return "iPhone 15 Pro Max" case "iPhone8,4": return "iPhone SE" case "iPhone12,8": return "iPhone SE (2nd generation)" case "iPhone14,6": return "iPhone SE (3rd generation)" case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4": return "iPad 2" case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad (3rd generation)" case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad (4th generation)" case "iPad6,11", "iPad6,12": return "iPad (5th generation)" case "iPad7,5", "iPad7,6": return "iPad (6th generation)" case "iPad7,11", "iPad7,12": return "iPad (7th generation)" case "iPad11,6", "iPad11,7": return "iPad (8th generation)" case "iPad12,1", "iPad12,2": return "iPad (9th generation)" case "iPad13,18", "iPad13,19": return "iPad (10th generation)" case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air" case "iPad5,3", "iPad5,4": return "iPad Air 2" case "iPad11,3", "iPad11,4": return "iPad Air (3rd generation)" case "iPad13,1", "iPad13,2": return "iPad Air (4th generation)" case "iPad13,16", "iPad13,17": return "iPad Air (5th generation)" case "iPad14,8", "iPad14,9": return "iPad Air (11-inch) (M2)" case "iPad14,10", "iPad14,11": return "iPad Air (13-inch) (M2)" case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad mini" case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad mini 2" case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad mini 3" case "iPad5,1", "iPad5,2": return "iPad mini 4" case "iPad11,1", "iPad11,2": return "iPad mini (5th generation)" case "iPad14,1", "iPad14,2": return "iPad mini (6th generation)" case "iPad6,3", "iPad6,4": return "iPad Pro (9.7-inch)" case "iPad7,3", "iPad7,4": return "iPad Pro (10.5-inch)" case "iPad8,1", "iPad8,2", "iPad8,3", "iPad8,4": return "iPad Pro (11-inch) (1st generation)" case "iPad8,9", "iPad8,10": return "iPad Pro (11-inch) (2nd generation)" case "iPad13,4", "iPad13,5", "iPad13,6", "iPad13,7": return "iPad Pro (11-inch) (3rd generation)" case "iPad14,3", "iPad14,4": return "iPad Pro (11-inch) (4th generation)" case "iPad16,3", "iPad16,4": return "iPad Pro (11-inch) (M4)" case "iPad6,7", "iPad6,8": return "iPad Pro (12.9-inch) (1st generation)" case "iPad7,1", "iPad7,2": return "iPad Pro (12.9-inch) (2nd generation)" case "iPad8,5", "iPad8,6", "iPad8,7", "iPad8,8": return "iPad Pro (12.9-inch) (3rd generation)" case "iPad8,11", "iPad8,12": return "iPad Pro (12.9-inch) (4th generation)" case "iPad13,8", "iPad13,9", "iPad13,10", "iPad13,11":return "iPad Pro (12.9-inch) (5th generation)" case "iPad14,5", "iPad14,6": return "iPad Pro (12.9-inch) (6th generation)" case "iPad16,5", "iPad16,6": return "iPad Pro (13-inch) (M4)" case "AppleTV5,3": return "Apple TV" case "AppleTV6,2": return "Apple TV 4K" case "AudioAccessory1,1": return "HomePod" case "AudioAccessory5,1": return "HomePod mini" case "i386", "x86_64", "arm64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "iOS"))" default: return identifier } #elseif os(tvOS) switch identifier { case "AppleTV5,3": return "Apple TV 4" case "AppleTV6,2", "AppleTV11,1", "AppleTV14,1": return "Apple TV 4K" case "i386", "x86_64": return "Simulator \(mapToDevice(identifier: ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "tvOS"))" default: return identifier } #elseif os(visionOS) switch identifier { case "RealityDevice14,1": return "Apple Vision Pro" default: return identifier } #endif } return mapToDevice(identifier: identifier) }() } You call it like this: let modelName = UIDevice.modelName For real devices it returns e.g. "iPad Pro (12.9-inch) (5th generation)", for simulators it returns e.g. "Simulator iPad Pro (12.9-inch) (5th generation)" Here's the model references: https://theiphonewiki.com/wiki/Models https://theiphonewiki.com/wiki/BORD
Swift
26,028,918
552
Can anyone tell me how to round a double value to x number of decimal places in Swift? I have: var totalWorkTimeInHours = (totalWorkTime/60/60) With totalWorkTime being an NSTimeInterval (double) in second. totalWorkTimeInHours will give me the hours, but it gives me the amount of time in such a long precise number e.g. 1.543240952039...... How do I round this down to, say, 1.543 when I print totalWorkTimeInHours?
You can use Swift's round function to accomplish this. To round a Double with 3 digits precision, first multiply it by 1000, round it and divide the rounded result by 1000: let x = 1.23556789 let y = Double(round(1000 * x) / 1000) print(y) /// 1.236 Unlike any kind of printf(...) or String(format: ...) solutions, the result of this operation is still of type Double. Regarding the comments that it sometimes does not work, please read this: What Every Programmer Should Know About Floating-Point Arithmetic
Swift
27,338,573
552
The Swift Programming Language guide has the following example: class Person { let name: String init(name: String) { self.name = name } var apartment: Apartment? deinit { println("\(name) is being deinitialized") } } class Apartment { let number: Int init(number: Int) { self.number = number } var tenant: Person? deinit { println("Apartment #\(number) is being deinitialized") } } var john: Person? var number73: Apartment? john = Person(name: "John Appleseed") number73 = Apartment(number: 73) //From Apple's “The Swift Programming Language” guide (https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/AutomaticReferenceCounting.html) Then when assigning the apartment to the person, they use an exclamation point to "unwrap the instance": john!.apartment = number73 What does it mean to "unwrap the instance"? Why is it necessary? How is it different from just doing the following: john.apartment = number73 I'm very new to the Swift language. Just trying to get the basics down. UPDATE: The big piece of the puzzle that I was missing (not directly stated in the answers - at least not at the time of writing this) is that when you do the following: var john: Person? that does NOT mean that "john is of type Person and it might be nil", as I originally thought. I was simply misunderstanding that Person and Person? are completely separate types. Once I grasped that, all of the other ?, ! madness, and the great answers below, made a lot more sense.
What does it mean to "unwrap the instance"? Why is it necessary? As far as I can work out (this is very new to me, too)... The term "wrapped" implies we should think of an Optional variable as a present, wrapped in shiny paper, which might (sadly!) be empty. When "wrapped", the value of an Optional variable is an enum with two possible values (a little like a Boolean). This enum describes whether the variable holds a value (Some(T)), or not (None). If there is a value, this can be obtained by "unwrapping" the variable (obtaining the T from Some(T)). How is john!.apartment = number73 different from john.apartment = number73? (Paraphrased) If you write the name of an Optional variable (eg text john, without the !), this refers to the "wrapped" enum (Some/None), not the value itself (T). So john isn't an instance of Person, and it doesn't have an apartment member: john.apartment // 'Person?' does not have a member named 'apartment' The actual Person value can be unwrapped in various ways: "forced unwrapping": john! (gives the Person value if it exists, runtime error if it is nil) "optional binding": if let p = john { println(p) } (executes the println if the value exists) "optional chaining": john?.learnAboutSwift() (executes this made-up method if the value exists) I guess you choose one of these ways to unwrap, depending upon what should happen in the nil case, and how likely that is. This language design forces the nil case to be handled explicitly, which I suppose improves safety over Obj-C (where it is easy to forget to handle the nil case). Update: The exclamation mark is also used in the syntax for declaring "Implicitly Unwrapped Optionals". In the examples so far, the john variable has been declared as var john:Person?, and it is an Optional. If you want the actual value of that variable, you must unwrap it, using one of the three methods above. If it were declared as var john:Person! instead, the variable would be an Implicitly Unwrapped Optional (see the section with this heading in Apple's book). There is no need to unwrap this kind of variable when accessing the value, and john can be used without additional syntax. But Apple's book says: Implicitly unwrapped optionals should not be used when there is a possibility of a variable becoming nil at a later point. Always use a normal optional type if you need to check for a nil value during the lifetime of a variable. Update 2: The article "Interesting Swift Features" by Mike Ash gives some motivation for optional types. I think it is great, clear writing. Update 3: Another useful article about the implicitly unwrapped optional use for the exclamation mark: "Swift and the Last Mile" by Chris Adamson. The article explains that this is a pragmatic measure by Apple used to declare the types used by their Objective-C frameworks which might contain nil. Declaring a type as optional (using ?) or implicitly unwrapped (using !) is "a tradeoff between safety and convenience". In the examples given in the article, Apple have chosen to declare the types as implicitly unwrapped, making the calling code more convenient, but less safe. Perhaps Apple might comb through their frameworks in the future, removing the uncertainty of implicitly unwrapped ("probably never nil") parameters and replacing them with optional ("certainly could be nil in particular [hopefully, documented!] circumstances") or standard non-optional ("is never nil") declarations, based on the exact behaviour of their Objective-C code.
Swift
24,018,327
545
I realize the Swift book provided an implementation of a random number generator. Is the best practice to copy and paste this implementation? Or is there a library that does this that we can use now?
Swift 4.2+ Swift 4.2 shipped with Xcode 10 introduces new easy-to-use random functions for many data types. You simply call the random() method on numeric types. let randomInt = Int.random(in: 0..<6) let randomDouble = Double.random(in: 2.71828...3.14159) let randomBool = Bool.random()
Swift
24,007,129
544
I have an app that sometimes needs its navigation bar to blend in with the content. Does anyone know how to get rid of or to change color of this annoying little bar? On the image below situation i have - i'm talking about this 1px height line below "Root View Controller"
For iOS 13: Use the .shadowColor property If this property is nil or contains the clear color, the bar displays no shadow For instance: let navigationBar = navigationController?.navigationBar let navigationBarAppearance = UINavigationBarAppearance() navigationBarAppearance.shadowColor = .clear navigationBar?.scrollEdgeAppearance = navigationBarAppearance For iOS 12 and below: To do this, you should set a custom shadow image. But for the shadow image to be shown you also need to set a custom background image, quote from Apple's documentation: For a custom shadow image to be shown, a custom background image must also be set with the setBackgroundImage(_:for:) method. If the default background image is used, then the default shadow image will be used regardless of the value of this property. So: let navigationBar = navigationController!.navigationBar navigationBar.setBackgroundImage(#imageLiteral(resourceName: "BarBackground"), for: .default) navigationBar.shadowImage = UIImage() Above is the only "official" way to hide it. Unfortunately, it removes bar's translucency. I don't want background image, just color. You have those options: Solid color, no translucency: navigationBar.barTintColor = UIColor.redColor() navigationBar.isTranslucent = false navigationBar.setBackgroundImage(UIImage(), for: .default) navigationBar.shadowImage = UIImage() Create small background image filled with color and use it. Use 'hacky' method described below. It will also keep bar translucent. How to keep bar translucent? To keep translucency you need another approach, it looks like a hack but works well. The shadow we're trying to remove is a hairline UIImageView somewhere under UINavigationBar. We can find it and hide/show it when needed. Instructions below assume you need hairline hidden only in one controller of your UINavigationController hierarchy. Declare instance variable: private var shadowImageView: UIImageView? Add method which finds this shadow (hairline) UIImageView: private func findShadowImage(under view: UIView) -> UIImageView? { if view is UIImageView && view.bounds.size.height <= 1 { return (view as! UIImageView) } for subview in view.subviews { if let imageView = findShadowImage(under: subview) { return imageView } } return nil } Add/edit viewWillAppear/viewWillDisappear methods: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) if shadowImageView == nil { shadowImageView = findShadowImage(under: navigationController!.navigationBar) } shadowImageView?.isHidden = true } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) shadowImageView?.isHidden = false } The same method should also work for UISearchBar hairline, and (almost) anything else you need to hide :) Many thanks to @Leo Natan for the original idea!
Swift
19,226,965
537
I am trying to find an item index by searching a list. Does anybody know how to do that? I see there is list.StartIndex and list.EndIndex but I want something like python's list.index("text").
As swift is in some regards more functional than object-oriented (and Arrays are structs, not objects), use the function "find" to operate on the array, which returns an optional value, so be prepared to handle a nil value: let arr:Array = ["a","b","c"] find(arr, "c")! // 2 find(arr, "d") // nil Use firstIndex and lastIndex - depending on whether you are looking for the first or last index of the item: let arr = ["a","b","c","a"] let indexOfA = arr.firstIndex(of: "a") // 0 let indexOfB = arr.lastIndex(of: "a") // 3
Swift
24,028,860
534
I'd like to load an image from a URL in my application, so I first tried with Objective-C and it worked, however, with Swift, I've a compilation error: 'imageWithData' is unavailable: use object construction 'UIImage(data:)' My function: @IBOutlet var imageView : UIImageView override func viewDidLoad() { super.viewDidLoad() var url:NSURL = NSURL.URLWithString("http://myURL/ios8.png") var data:NSData = NSData.dataWithContentsOfURL(url, options: nil, error: nil) imageView.image = UIImage.imageWithData(data)// Error here } In Objective-C: - (void)viewDidLoad { [super viewDidLoad]; NSURL *url = [NSURL URLWithString:(@"http://myURL/ios8.png")]; NSData *data = [NSData dataWithContentsOfURL:url]; _imageView.image = [UIImage imageWithData: data]; _labelURL.text = @"http://www.urltest.fr/assets/img/iOS%20icon's%20Style/ios8.png"; } Can someone please explain me why the imageWithData: doesn't work with Swift, and how can I solve the problem.
Xcode 8 or later • Swift 3 or later Synchronously: if let filePath = Bundle.main.path(forResource: "imageName", ofType: "jpg"), let image = UIImage(contentsOfFile: filePath) { imageView.contentMode = .scaleAspectFit imageView.image = image } Asynchronously: Create a method with a completion handler to get the image data from your url func getData(from url: URL, completion: @escaping (Data?, URLResponse?, Error?) -> ()) { URLSession.shared.dataTask(with: url, completionHandler: completion).resume() } Create a method to download the image (start the task) func downloadImage(from url: URL) { print("Download Started") getData(from: url) { data, response, error in guard let data = data, error == nil else { return } print(response?.suggestedFilename ?? url.lastPathComponent) print("Download Finished") // always update the UI from the main thread DispatchQueue.main.async() { [weak self] in self?.imageView.image = UIImage(data: data) } } } Usage: override func viewDidLoad() { super.viewDidLoad() print("Begin of code") let url = URL(string: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")! downloadImage(from: url) print("End of code. The image will continue downloading in the background and it will be loaded when it ends.") } Extension: extension UIImageView { func downloaded(from url: URL, contentMode mode: ContentMode = .scaleAspectFit) { contentMode = mode URLSession.shared.dataTask(with: url) { data, response, error in guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let mimeType = response?.mimeType, mimeType.hasPrefix("image"), let data = data, error == nil, let image = UIImage(data: data) else { return } DispatchQueue.main.async() { [weak self] in self?.image = image } }.resume() } func downloaded(from link: String, contentMode mode: ContentMode = .scaleAspectFit) { guard let url = URL(string: link) else { return } downloaded(from: url, contentMode: mode) } } Usage: imageView.downloaded(from: "https://cdn.arstechnica.net/wp-content/uploads/2018/06/macOS-Mojave-Dynamic-Wallpaper-transition.jpg")
Swift
24,231,680
521
Why would you create a "Implicitly Unwrapped Optional" vs creating just a regular variable or constant? If you know that it can be successfully unwrapped then why create an optional in the first place? For example, why is this: let someString: String! = "this is the string" going to be more useful than: let someString: String = "this is the string" If ”optionals indicate that a constant or variable is allowed to have 'no value'”, but “sometimes it is clear from a program’s structure that an optional will always have a value after that value is first set”, what is the point of making it an optional in the first place? If you know an optional is always going to have a value, doesn't that make it not optional?
Before I can describe the use cases for Implicitly Unwrapped Optionals, you should already understand what Optionals and Implicitly Unwrapped Optionals are in Swift. If you do not, I recommend you first read my article on optionals When To Use An Implicitly Unwrapped Optional There are two main reasons that one would create an Implicitly Unwrapped Optional. All have to do with defining a variable that will never be accessed when nil because otherwise, the Swift compiler will always force you to explicitly unwrap an Optional. 1. A Constant That Cannot Be Defined During Initialization Every member constant must have a value by the time initialization is complete. Sometimes, a constant cannot be initialized with its correct value during initialization, but it can still be guaranteed to have a value before being accessed. Using an Optional variable gets around this issue because an Optional is automatically initialized with nil and the value it will eventually contain will still be immutable. However, it can be a pain to be constantly unwrapping a variable that you know for sure is not nil. Implicitly Unwrapped Optionals achieve the same benefits as an Optional with the added benefit that one does not have to explicitly unwrap it everywhere. A great example of this is when a member variable cannot be initialized in a UIView subclass until the view is loaded: class MyView: UIView { @IBOutlet var button: UIButton! var buttonOriginalWidth: CGFloat! override func awakeFromNib() { self.buttonOriginalWidth = self.button.frame.size.width } } Here, you cannot calculate the original width of the button until the view loads, but you know that awakeFromNib will be called before any other method on the view (other than initialization). Instead of forcing the value to be explicitly unwrapped pointlessly all over your class, you can declare it as an Implicitly Unwrapped Optional. 2. When Your App Cannot Recover From a Variable Being nil This should be extremely rare, but if your app can not continue to run if a variable is nil when accessed, it would be a waste of time to bother testing it for nil. Normally if you have a condition that must absolutely be true for your app to continue running, you would use an assert. An Implicitly Unwrapped Optional has an assert for nil built right into it. Even then, it is often good to unwrap the optional and use a more descriptive assert if it is nil. When Not To Use An Implicitly Unwrapped Optional 1. Lazily Calculated Member Variables Sometimes you have a member variable that should never be nil, but it cannot be set to the correct value during initialization. One solution is to use an Implicitly Unwrapped Optional, but a better way is to use a lazy variable: class FileSystemItem { } class Directory : FileSystemItem { lazy var contents : [FileSystemItem] = { var loadedContents = [FileSystemItem]() // load contents and append to loadedContents return loadedContents }() } Now, the member variable contents is not initialized until the first time it is accessed. This gives the class a chance to get into the correct state before calculating the initial value. Note: This may seem to contradict #1 from above. However, there is an important distinction to be made. The buttonOriginalWidth above must be set during viewDidLoad to prevent anyone changing the buttons width before the property is accessed. 2. Everywhere Else For the most part, Implicitly Unwrapped Optionals should be avoided because if used mistakenly, your entire app will crash when it is accessed while nil. If you are ever not sure about whether a variable can be nil, always default to using a normal Optional. Unwrapping a variable that is never nil certainly doesn't hurt very much.
Swift
24,006,975
515
How can I get the nth character of a string? I tried bracket([]) accessor with no luck. var string = "Hello, world!" var firstChar = string[0] // Throws error ERROR: 'subscript' is unavailable: cannot subscript String with an Int, see the documentation comment for discussion
Attention: Please see Leo Dabus' answer for a proper implementation for Swift 4 and Swift 5. Swift 4 or later The Substring type was introduced in Swift 4 to make substrings faster and more efficient by sharing storage with the original string, so that's what the subscript functions should return. Try it out here extension StringProtocol { subscript(offset: Int) -> Character { self[index(startIndex, offsetBy: offset)] } subscript(range: Range<Int>) -> SubSequence { let startIndex = index(self.startIndex, offsetBy: range.lowerBound) return self[startIndex..<index(startIndex, offsetBy: range.count)] } subscript(range: ClosedRange<Int>) -> SubSequence { let startIndex = index(self.startIndex, offsetBy: range.lowerBound) return self[startIndex..<index(startIndex, offsetBy: range.count)] } subscript(range: PartialRangeFrom<Int>) -> SubSequence { self[index(startIndex, offsetBy: range.lowerBound)...] } subscript(range: PartialRangeThrough<Int>) -> SubSequence { self[...index(startIndex, offsetBy: range.upperBound)] } subscript(range: PartialRangeUpTo<Int>) -> SubSequence { self[..<index(startIndex, offsetBy: range.upperBound)] } } To convert the Substring into a String, you can simply do String(string[0..2]), but you should only do that if you plan to keep the substring around. Otherwise, it's more efficient to keep it a Substring. It would be great if someone could figure out a good way to merge these two extensions into one. I tried extending StringProtocol without success, because the index method does not exist there. Note: This answer has been already edited, it is properly implemented and now works for substrings as well. Just make sure to use a valid range to avoid crashing when subscripting your StringProtocol type. For subscripting with a range that won't crash with out of range values you can use this implementation Why is this not built-in? The error message says "see the documentation comment for discussion". Apple provides the following explanation in the file UnavailableStringAPIs.swift: Subscripting strings with integers is not available. The concept of "the ith character in a string" has different interpretations in different libraries and system components. The correct interpretation should be selected according to the use case and the APIs involved, so String cannot be subscripted with an integer. Swift provides several different ways to access the character data stored inside strings. String.utf8 is a collection of UTF-8 code units in the string. Use this API when converting the string to UTF-8. Most POSIX APIs process strings in terms of UTF-8 code units. String.utf16 is a collection of UTF-16 code units in string. Most Cocoa and Cocoa touch APIs process strings in terms of UTF-16 code units. For example, instances of NSRange used with NSAttributedString and NSRegularExpression store substring offsets and lengths in terms of UTF-16 code units. String.unicodeScalars is a collection of Unicode scalars. Use this API when you are performing low-level manipulation of character data. String.characters is a collection of extended grapheme clusters, which are an approximation of user-perceived characters. Note that when processing strings that contain human-readable text, character-by-character processing should be avoided to the largest extent possible. Use high-level locale-sensitive Unicode algorithms instead, for example, String.localizedStandardCompare(), String.localizedLowercaseString, String.localizedStandardRangeOfString() etc.
Swift
24,092,884
515
In WWDC 2014 session 403 Intermediate Swift and transcript, there was the following slide The speaker said in that case, if we don't use [unowned self] there, it will be a memory leak. Does it mean we should always use [unowned self] inside closure? On line 64 of ViewController.swift of the Swift Weather app, I don't use [unowned self]. But I update the UI by using some @IBOutlets like self.temperature and self.loadingIndicator. It may be OK because all @IBOutlets I defined are weak. But for safety, should we always use [unowned self]? class TempNotifier { var onChange: (Int) -> Void = {_ in } var currentTemp = 72 init() { onChange = { [unowned self] temp in self.currentTemp = temp } } }
No, there are definitely times where you would not want to use [unowned self]. Sometimes you want the closure to capture self in order to make sure that it is still around by the time the closure is called. Example: Making an asynchronous network request If you are making an asynchronous network request you do want the closure to retain self for when the request finishes. That object may have otherwise been deallocated but you still want to be able to handle the request finishing. When to use unowned self or weak self The only time where you really want to use [unowned self] or [weak self] is when you would create a strong reference cycle. A strong reference cycle is when there is a loop of ownership where objects end up owning each other (maybe through a third party) and therefore they will never be deallocated because they are both ensuring that each other stick around. In the specific case of a closure, you just need to realize that any variable that is referenced inside of it, gets "owned" by the closure. As long as the closure is around, those objects are guaranteed to be around. The only way to stop that ownership, is to do the [unowned self] or [weak self]. So if a class owns a closure, and that closure captures a strong reference to that class, then you have a strong reference cycle between the closure and the class. This also includes if the class owns something that owns the closure. Specifically in the example from the video In the example on the slide, TempNotifier owns the closure through the onChange member variable. If they did not declare self as unowned, the closure would also own self creating a strong reference cycle. Difference between unowned and weak The difference between unowned and weak is that weak is declared as an Optional while unowned is not. By declaring it weak you get to handle the case that it might be nil inside the closure at some point. If you try to access an unowned variable that happens to be nil, it will crash the whole program. So only use unowned when you are positive that variable will always be around while the closure is around
Swift
24,320,347
510
I have been looking all over for this but I can't seem to find it. I know how to dismiss the keyboard using Objective-C but I have no idea how to do that using Swift? Does anyone know?
override func viewDidLoad() { super.viewDidLoad() //Looks for single or multiple taps. let tap = UITapGestureRecognizer(target: self, action: #selector(UIInputViewController.dismissKeyboard)) //Uncomment the line below if you want the tap not not interfere and cancel other interactions. //tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } //Calls this function when the tap is recognized. @objc func dismissKeyboard() { //Causes the view (or one of its embedded text fields) to resign the first responder status. view.endEditing(true) } Here is another way to do this task if you are going to use this functionality in multiple UIViewControllers: // Put this piece of code anywhere you like extension UIViewController { func hideKeyboardWhenTappedAround() { let tap = UITapGestureRecognizer(target: self, action: #selector(UIViewController.dismissKeyboard)) tap.cancelsTouchesInView = false view.addGestureRecognizer(tap) } @objc func dismissKeyboard() { view.endEditing(true) } } Now in every UIViewController, all you have to do is call this function: override func viewDidLoad() { super.viewDidLoad() self.hideKeyboardWhenTappedAround() } This function is included as a standard function in my repo which contains a lot of useful Swift Extensions like this one, check it out: https://github.com/goktugyil/EZSwiftExtensions
Swift
24,126,678
509
My Swift program is crashing with EXC_BAD_INSTRUCTION and one of the following similar errors. What does this error mean, and how do I fix it? Fatal error: Unexpectedly found nil while unwrapping an Optional value or Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value This post is intended to collect answers to "unexpectedly found nil" issues, so that they are not scattered and hard to find. Feel free to add your own answer or edit the existing wiki answer.
Background: What’s an Optional? In Swift, Optional<Wrapped> is an option type: it can contain any value from the original ("Wrapped") type, or no value at all (the special value nil). An optional value must be unwrapped before it can be used. Optional is a generic type, which means that Optional<Int> and Optional<String> are distinct types — the type inside <> is called the Wrapped type. Under the hood, an Optional is an enum with two cases: .some(Wrapped) and .none, where .none is equivalent to nil. Optionals can be declared using the named type Optional<T>, or (most commonly) as a shorthand with a ? suffix. var anInt: Int = 42 var anOptionalInt: Int? = 42 var anotherOptionalInt: Int? // `nil` is the default when no value is provided var aVerboseOptionalInt: Optional<Int> // equivalent to `Int?` anOptionalInt = nil // now this variable contains nil instead of an integer Optionals are a simple yet powerful tool to express your assumptions while writing code. The compiler can use this information to prevent you from making mistakes. From The Swift Programming Language: Swift is a type-safe language, which means the language helps you to be clear about the types of values your code can work with. If part of your code requires a String, type safety prevents you from passing it an Int by mistake. Likewise, type safety prevents you from accidentally passing an optional String to a piece of code that requires a non-optional String. Type safety helps you catch and fix errors as early as possible in the development process. Some other programming languages also have generic option types: for example, Maybe in Haskell, option in Rust, and optional in C++17. In programming languages without option types, a particular "sentinel" value is often used to indicate the absence of a valid value. In Objective-C, for example, nil (the null pointer) represents the lack of an object. For primitive types such as int, a null pointer can't be used, so you would need either a separate variable (such as value: Int and isValid: Bool) or a designated sentinel value (such as -1 or INT_MIN). These approaches are error-prone because it's easy to forget to check isValid or to check for the sentinel value. Also, if a particular value is chosen as the sentinel, that means it can no longer be treated as a valid value. Option types such as Swift's Optional solve these problems by introducing a special, separate nil value (so you don't have to designate a sentinel value), and by leveraging the strong type system so the compiler can help you remember to check for nil when necessary. Why did I get “Fatal error: Unexpectedly found nil while unwrapping an Optional value”? In order to access an optional’s value (if it has one at all), you need to unwrap it. An optional value can be unwrapped safely or forcibly. If you force-unwrap an optional, and it didn't have a value, your program will crash with the above message. Xcode will show you the crash by highlighting a line of code. The problem occurs on this line. This crash can occur with two different kinds of force-unwrap: 1. Explicit Force Unwrapping This is done with the ! operator on an optional. For example: let anOptionalString: String? print(anOptionalString!) // <- CRASH Fatal error: Unexpectedly found nil while unwrapping an Optional value As anOptionalString is nil here, you will get a crash on the line where you force unwrap it. 2. Implicitly Unwrapped Optionals These are defined with a !, rather than a ? after the type. var optionalDouble: Double! // this value is implicitly unwrapped wherever it's used These optionals are assumed to contain a value. Therefore whenever you access an implicitly unwrapped optional, it will automatically be force unwrapped for you. If it doesn’t contain a value, it will crash. print(optionalDouble) // <- CRASH Fatal error: Unexpectedly found nil while implicitly unwrapping an Optional value In order to work out which variable caused the crash, you can hold ⌥ while clicking to show the definition, where you might find the optional type. IBOutlets, in particular, are usually implicitly unwrapped optionals. This is because your xib or storyboard will link up the outlets at runtime, after initialization. You should therefore ensure that you’re not accessing outlets before they're loaded in. You also should check that the connections are correct in your storyboard/xib file, otherwise the values will be nil at runtime, and therefore crash when they are implicitly unwrapped. When fixing connections, try deleting the lines of code that define your outlets, then reconnect them. When should I ever force unwrap an Optional? Explicit Force Unwrapping As a general rule, you should never explicitly force unwrap an optional with the ! operator. There may be cases where using ! is acceptable – but you should only ever be using it if you are 100% sure that the optional contains a value. While there may be an occasion where you can use force unwrapping, as you know for a fact that an optional contains a value – there is not a single place where you cannot safely unwrap that optional instead. Implicitly Unwrapped Optionals These variables are designed so that you can defer their assignment until later in your code. It is your responsibility to ensure they have a value before you access them. However, because they involve force unwrapping, they are still inherently unsafe – as they assume your value is non-nil, even though assigning nil is valid. You should only be using implicitly unwrapped optionals as a last resort. If you can use a lazy variable, or provide a default value for a variable – you should do so instead of using an implicitly unwrapped optional. However, there are a few scenarios where implicitly unwrapped optionals are beneficial, and you are still able to use various ways of safely unwrapping them as listed below – but you should always use them with due caution. How can I safely deal with Optionals? The simplest way to check whether an optional contains a value, is to compare it to nil. if anOptionalInt != nil { print("Contains a value!") } else { print("Doesn’t contain a value.") } However, 99.9% of the time when working with optionals, you’ll actually want to access the value it contains, if it contains one at all. To do this, you can use Optional Binding. Optional Binding Optional Binding allows you to check if an optional contains a value – and allows you to assign the unwrapped value to a new variable or constant. It uses the syntax if let x = anOptional {...} or if var x = anOptional {...}, depending if you need to modify the value of the new variable after binding it. For example: if let number = anOptionalInt { print("Contains a value! It is \(number)!") } else { print("Doesn’t contain a number") } What this does is first check that the optional contains a value. If it does, then the ‘unwrapped’ value is assigned to a new variable (number) – which you can then freely use as if it were non-optional. If the optional doesn’t contain a value, then the else clause will be invoked, as you would expect. What’s neat about optional binding, is you can unwrap multiple optionals at the same time. You can just separate the statements with a comma. The statement will succeed if all the optionals were unwrapped. var anOptionalInt : Int? var anOptionalString : String? if let number = anOptionalInt, let text = anOptionalString { print("anOptionalInt contains a value: \(number). And so does anOptionalString, it’s: \(text)") } else { print("One or more of the optionals don’t contain a value") } Another neat trick is that you can also use commas to check for a certain condition on the value, after unwrapping it. if let number = anOptionalInt, number > 0 { print("anOptionalInt contains a value: \(number), and it’s greater than zero!") } The only catch with using optional binding within an if statement, is that you can only access the unwrapped value from within the scope of the statement. If you need access to the value from outside of the scope of the statement, you can use a guard statement. A guard statement allows you to define a condition for success – and the current scope will only continue executing if that condition is met. They are defined with the syntax guard condition else {...}. So, to use them with an optional binding, you can do this: guard let number = anOptionalInt else { return } (Note that within the guard body, you must use one of the control transfer statements in order to exit the scope of the currently executing code). If anOptionalInt contains a value, it will be unwrapped and assigned to the new number constant. The code after the guard will then continue executing. If it doesn’t contain a value – the guard will execute the code within the brackets, which will lead to transfer of control, so that the code immediately after will not be executed. The real neat thing about guard statements is the unwrapped value is now available to use in code that follows the statement (as we know that future code can only execute if the optional has a value). This is a great for eliminating ‘pyramids of doom’ created by nesting multiple if statements. For example: guard let number = anOptionalInt else { return } print("anOptionalInt contains a value, and it’s: \(number)!") Guards also support the same neat tricks that the if statement supported, such as unwrapping multiple optionals at the same time and using the where clause. Whether you use an if or guard statement completely depends on whether any future code requires the optional to contain a value. Nil Coalescing Operator The Nil Coalescing Operator is a nifty shorthand version of the ternary conditional operator, primarily designed to convert optionals to non-optionals. It has the syntax a ?? b, where a is an optional type and b is the same type as a (although usually non-optional). It essentially lets you say “If a contains a value, unwrap it. If it doesn’t then return b instead”. For example, you could use it like this: let number = anOptionalInt ?? 0 This will define a number constant of Int type, that will either contain the value of anOptionalInt, if it contains a value, or 0 otherwise. It’s just shorthand for: let number = anOptionalInt != nil ? anOptionalInt! : 0 Optional Chaining You can use Optional Chaining in order to call a method or access a property on an optional. This is simply done by suffixing the variable name with a ? when using it. For example, say we have a variable foo, of type an optional Foo instance. var foo : Foo? If we wanted to call a method on foo that doesn’t return anything, we can simply do: foo?.doSomethingInteresting() If foo contains a value, this method will be called on it. If it doesn’t, nothing bad will happen – the code will simply continue executing. (This is similar behaviour to sending messages to nil in Objective-C) This can therefore also be used to set properties as well as call methods. For example: foo?.bar = Bar() Again, nothing bad will happen here if foo is nil. Your code will simply continue executing. Another neat trick that optional chaining lets you do is check whether setting a property or calling a method was successful. You can do this by comparing the return value to nil. (This is because an optional value will return Void? rather than Void on a method that doesn’t return anything) For example: if (foo?.bar = Bar()) != nil { print("bar was set successfully") } else { print("bar wasn’t set successfully") } However, things become a little bit more tricky when trying to access properties or call methods that return a value. Because foo is optional, anything returned from it will also be optional. To deal with this, you can either unwrap the optionals that get returned using one of the above methods – or unwrap foo itself before accessing methods or calling methods that return values. Also, as the name suggests, you can ‘chain’ these statements together. This means that if foo has an optional property baz, which has a property qux – you could write the following: let optionalQux = foo?.baz?.qux Again, because foo and baz are optional, the value returned from qux will always be an optional regardless of whether qux itself is optional. map and flatMap An often underused feature with optionals is the ability to use the map and flatMap functions. These allow you to apply non-optional transforms to optional variables. If an optional has a value, you can apply a given transformation to it. If it doesn’t have a value, it will remain nil. For example, let’s say you have an optional string: let anOptionalString:String? By applying the map function to it – we can use the stringByAppendingString function in order to concatenate it to another string. Because stringByAppendingString takes a non-optional string argument, we cannot input our optional string directly. However, by using map, we can use allow stringByAppendingString to be used if anOptionalString has a value. For example: var anOptionalString:String? = "bar" anOptionalString = anOptionalString.map {unwrappedString in return "foo".stringByAppendingString(unwrappedString) } print(anOptionalString) // Optional("foobar") However, if anOptionalString doesn’t have a value, map will return nil. For example: var anOptionalString:String? anOptionalString = anOptionalString.map {unwrappedString in return "foo".stringByAppendingString(unwrappedString) } print(anOptionalString) // nil flatMap works similarly to map, except it allows you to return another optional from within the closure body. This means you can input an optional into a process that requires a non-optional input, but can output an optional itself. try! Swift's error handling system can be safely used with Do-Try-Catch: do { let result = try someThrowingFunc() } catch { print(error) } If someThrowingFunc() throws an error, the error will be safely caught in the catch block. The error constant you see in the catch block has not been declared by us - it's automatically generated by catch. You can also declare error yourself, it has the advantage of being able to cast it to a useful format, for example: do { let result = try someThrowingFunc() } catch let error as NSError { print(error.debugDescription) } Using try this way is the proper way to try, catch and handle errors coming from throwing functions. There's also try? which absorbs the error: if let result = try? someThrowingFunc() { // cool } else { // handle the failure, but there's no error information available } But Swift's error handling system also provides a way to "force try" with try!: let result = try! someThrowingFunc() The concepts explained in this post also apply here: if an error is thrown, the application will crash. You should only ever use try! if you can prove that its result will never fail in your context - and this is very rare. Most of the time you will use the complete Do-Try-Catch system - and the optional one, try?, in the rare cases where handling the error is not important. Resources Apple documentation on Swift Optionals When to use and when not to use implicitly unwrapped optionals Learn how to debug an iOS app crash
Swift
32,170,456
505
If there are two arrays created in swift like this: var a:[CGFloat] = [1, 2, 3] var b:[CGFloat] = [4, 5, 6] How can they be merged to [1, 2, 3, 4, 5, 6]?
You can concatenate the arrays with +, building a new array let c = a + b print(c) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] or append one array to the other with += (or append): a += b // Or: a.append(contentsOf: b) // Swift 3 a.appendContentsOf(b) // Swift 2 a.extend(b) // Swift 1.2 print(a) // [1.0, 2.0, 3.0, 4.0, 5.0, 6.0]
Swift
25,146,382
501
I've been updating some of my old code and answers with Swift 3 but when I got to Swift Strings and Indexing with substrings things got confusing. Specifically I was trying the following: let str = "Hello, playground" let prefixRange = str.startIndex..<str.startIndex.advancedBy(5) let prefix = str.substringWithRange(prefixRange) where the second line was giving me the following error Value of type 'String' has no member 'substringWithRange' I see that String does have the following methods now: str.substring(to: String.Index) str.substring(from: String.Index) str.substring(with: Range<String.Index>) These were really confusing me at first so I started playing around index and range. This is a followup question and answer for substring. I am adding an answer below to show how they are used.
All of the following examples use var str = "Hello, playground" Swift 4 Strings got a pretty big overhaul in Swift 4. When you get some substring from a String now, you get a Substring type back rather than a String. Why is this? Strings are value types in Swift. That means if you use one String to make a new one, then it has to be copied over. This is good for stability (no one else is going to change it without your knowledge) but bad for efficiency. A Substring, on the other hand, is a reference back to the original String from which it came. Here is an image from the documentation illustrating that. No copying is needed so it is much more efficient to use. However, imagine you got a ten character Substring from a million character String. Because the Substring is referencing the String, the system would have to hold on to the entire String for as long as the Substring is around. Thus, whenever you are done manipulating your Substring, convert it to a String. let myString = String(mySubstring) This will copy just the substring over and the memory holding old String can be reclaimed. Substrings (as a type) are meant to be short lived. Another big improvement in Swift 4 is that Strings are Collections (again). That means that whatever you can do to a Collection, you can do to a String (use subscripts, iterate over the characters, filter, etc). The following examples show how to get a substring in Swift. Getting substrings You can get a substring from a string by using subscripts or a number of other methods (for example, prefix, suffix, split). You still need to use String.Index and not an Int index for the range, though. (See my other answer if you need help with that.) Beginning of a string You can use a subscript (note the Swift 4 one-sided range): let index = str.index(str.startIndex, offsetBy: 5) let mySubstring = str[..<index] // Hello or prefix: let index = str.index(str.startIndex, offsetBy: 5) let mySubstring = str.prefix(upTo: index) // Hello or even easier: let mySubstring = str.prefix(5) // Hello End of a string Using subscripts: let index = str.index(str.endIndex, offsetBy: -10) let mySubstring = str[index...] // playground or suffix: let index = str.index(str.endIndex, offsetBy: -10) let mySubstring = str.suffix(from: index) // playground or even easier: let mySubstring = str.suffix(10) // playground Note that when using the suffix(from: index) I had to count back from the end by using -10. That is not necessary when just using suffix(x), which just takes the last x characters of a String. Range in a string Again we simply use subscripts here. let start = str.index(str.startIndex, offsetBy: 7) let end = str.index(str.endIndex, offsetBy: -6) let range = start..<end let mySubstring = str[range] // play Converting Substring to String Don't forget, when you are ready to save your substring, you should convert it to a String so that the old string's memory can be cleaned up. let myString = String(mySubstring) Using an Int index extension? I'm hesitant to use an Int based index extension after reading the article Strings in Swift 3 by Airspeed Velocity and Ole Begemann. Although in Swift 4, Strings are collections, the Swift team purposely hasn't used Int indexes. It is still String.Index. This has to do with Swift Characters being composed of varying numbers of Unicode codepoints. The actual index has to be uniquely calculated for every string. I have to say, I hope the Swift team finds a way to abstract away String.Index in the future. But until then, I am choosing to use their API. It helps me to remember that String manipulations are not just simple Int index lookups.
Swift
39,677,330
500
The following code compiles in Swift 1.2: class myClass { static func myMethod1() { } class func myMethod2() { } static var myVar1 = "" } func doSomething() { myClass.myMethod1() myClass.myMethod2() myClass.myVar1 = "abc" } What is the difference between a static function and a class function? Which one should I use, and when? If I try to define another variable class var myVar2 = "", it says: Class stored properties not yet supported in classes; did you mean 'static'? When this feature is supported, what will the difference be between a static variable and a class variable (i.e. when both are defined in a class)? Which one should I use, and when? (Xcode 6.3)
static and class both associate a method with a class, rather than an instance of a class. The difference is that subclasses can override class methods; they cannot override static methods. class properties function in the same way (subclasses can override them).
Swift
29,636,633
485
In Swift 2, I was able to use dispatch_after to delay an action using grand central dispatch: var dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(0.1 * Double(NSEC_PER_SEC))) dispatch_after(dispatchTime, dispatch_get_main_queue(), { // your function here }) But this no longer seems to compile since Swift 3. What is the preferred way to write this in modern Swift?
The syntax is simply: // to run something in 0.1 seconds DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { // your code here } Note, the above syntax of adding seconds as a Double seems to be a source of confusion (esp since we were accustomed to adding nsec). That “add seconds as Double” syntax works because deadline is a DispatchTime and, behind the scenes, there is a + operator that will take a Double and add that many seconds to the DispatchTime: public func +(time: DispatchTime, seconds: Double) -> DispatchTime But, if you really want to add an integer number of msec, μs, or nsec to the DispatchTime, you can also add a DispatchTimeInterval to a DispatchTime. That means you can do: DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(500)) { // 500 msec, i.e. 0.5 seconds … } DispatchQueue.main.asyncAfter(deadline: .now() + .microseconds(1_000_000)) { // 1m microseconds, i.e. 1 second … } DispatchQueue.main.asyncAfter(deadline: .now() + .nanoseconds(1_500_000_000)) { // 1.5b nanoseconds, i.e. 1.5 seconds … } These all seamlessly work because of this separate overload method for the + operator in the DispatchTime class. public func +(time: DispatchTime, interval: DispatchTimeInterval) -> DispatchTime It was asked how one goes about canceling a dispatched task. To do this, use DispatchWorkItem. For example, this starts a task that will fire in five seconds, or if the view controller is dismissed and deallocated, its deinit will cancel the task: class ViewController: UIViewController { private var item: DispatchWorkItem? override func viewDidLoad() { super.viewDidLoad() item = DispatchWorkItem { [weak self] in self?.doSomething() self?.item = nil } DispatchQueue.main.asyncAfter(deadline: .now() + 5, execute: item!) } deinit { item?.cancel() } func doSomething() { … } } Note the use of the [weak self] capture list in the DispatchWorkItem. This is essential to avoid a strong reference cycle. Also note that this does not do a preemptive cancelation, but rather just stops the task from starting if it hasn’t already. But if it has already started by the time it encounters the cancel() call, the block will finish its execution (unless you’re manually checking isCancelled inside the block). Swift concurrency While the original question was about the old GCD dispatch_after vs. the newer asyncAfter API, this raises the question of how to achieve the same behavior in the newer Swift concurrency and its async-await. As of iOS 16 and macOS 13 we would prefer Task.sleep(for:): try await Task.sleep(for: .seconds(2)) // 2 seconds … Or try await Task.sleep(for: .milliseconds(200)) // 0.2 seconds … Or if we need to support back to iOS 13 and macOS 10.15, we would use Task.sleep(nanoseconds:) instead. And to support cancelation, save a Task: class ViewController: UIViewController { private var task: Task<Void, Error>? override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) task = Task { try await Task.sleep(for: .seconds(5)) await doSomething() } } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) task?.cancel() } func doSomething() async { … } } Or in SwiftUI, we might use the .task {…} view modifier, which “will automatically cancel the task at some point after the view disappears before the action completes.” We do not even need to save the Task to manually cancel later. We should recognize that before we had Swift concurrency, calling any sleep function used to be an anti-pattern, one that we would studiously avoid, because it would block the current thread. That was a serious error when done from the main thread, but even was problematic when used in background threads as the GCD worker thread pool is so limited. But the new Task.sleep functions do not block the current thread, and are therefore safe to use from any actor (including the main actor).
Swift
37,801,436
485
How do I get a reference to AppDelegate in Swift? Ultimately, I want to use the reference to access the managed object context.
The other solution is correct in that it will get you a reference to the application's delegate, but this will not allow you to access any methods or variables added by your subclass of UIApplication, like your managed object context. To resolve this, simply downcast to "AppDelegate" or what ever your UIApplication subclass happens to be called. In Swift 3, 4 & 5, this is done as follows: let appDelegate = UIApplication.shared.delegate as! AppDelegate let aVariable = appDelegate.someVariable
Swift
24,046,164
482
I have an UIImageView called "theImageView", with UIImage in a single color (transparent background) just like the left black heart below. How can I change the tint color of this image programmatically in iOS 7 or above, as per the tint method used in the iOS 7+ Navigation Bar icons? Can this method also work in WatchKit for an Apple Watch app?
iOS For an iOS app, in Swift 3, 4 or 5: theImageView.image = theImageView.image?.withRenderingMode(.alwaysTemplate) theImageView.tintColor = UIColor.red For Swift 2: theImageView.image = theImageView.image?.imageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate) theImageView.tintColor = UIColor.redColor() Meanwhile, the modern Objective-C solution is: theImageView.image = [theImageView.image imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate]; [theImageView setTintColor:[UIColor redColor]]; Watchkit In WatchKit for Apple Watch apps, you can set the tint color for a template image. You must add your image to an Asset Catalog in your WatchKit App, and set the image set to be rendered as a Template Image in the Attributes Inspector. Unlike for an iPhone app, you cannot set the template rendering in code in the WatchKit Extension at present. Set that image to be used in your WKInterfaceImage in interface builder for your app Create an IBOutlet in your WKInterfaceController for the WKInterfaceImage called 'theImage'... To then set the tint color in Swift 3 or 4: theImage.setTintColor(UIColor.red) Swift 2: theImage.setTintColor(UIColor.redColor()) To then set the tint color in Objective-C: [self.theImage setTintColor:[UIColor redColor]]; If you use a template image and do not apply a tint colour, the Global Tint for your WatchKit app will be applied. If you have not set a Global Tint, theImage will be tinted light blue by default when used as a template image.
Swift
19,274,789
467
How do you add an observer in Swift to the default notification center? I'm trying to port this line of code that sends a notification when the battery level changes. [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(batteryLevelChanged:) name:UIDeviceBatteryLevelDidChangeNotification object:nil];
Swift 4.0 & Xcode 9.0+: Send(Post) Notification: NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil) OR NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil, userInfo: ["Renish":"Dadhaniya"]) Receive(Get) Notification: NotificationCenter.default.addObserver(self, selector: #selector(self.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil) Function-Method handler for received Notification: @objc func methodOfReceivedNotification(notification: Notification) {} Swift 3.0 & Xcode 8.0+: Send(Post) Notification: NotificationCenter.default.post(name: Notification.Name("NotificationIdentifier"), object: nil) Receive(Get) Notification: NotificationCenter.default.addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(notification:)), name: Notification.Name("NotificationIdentifier"), object: nil) Method handler for received Notification: func methodOfReceivedNotification(notification: Notification) { // Take Action on Notification } Remove Notification: deinit { NotificationCenter.default.removeObserver(self, name: Notification.Name("NotificationIdentifier"), object: nil) } Swift 2.3 & Xcode 7: Send(Post) Notification NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil) Receive(Get) Notification NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(YourClassName.methodOfReceivedNotification(_:)), name:"NotificationIdentifier", object: nil) Method handler for received Notification func methodOfReceivedNotification(notification: NSNotification){ // Take Action on Notification } For historic Xcode versions... Send(Post) Notification NSNotificationCenter.defaultCenter().postNotificationName("NotificationIdentifier", object: nil) Receive(Get) Notification NSNotificationCenter.defaultCenter().addObserver(self, selector: "methodOfReceivedNotification:", name:"NotificationIdentifier", object: nil) Remove Notification NSNotificationCenter.defaultCenter().removeObserver(self, name: "NotificationIdentifier", object: nil) NSNotificationCenter.defaultCenter().removeObserver(self) // Remove from all notifications being observed Method handler for received Notification func methodOfReceivedNotification(notification: NSNotification) { // Take Action on Notification } Annotate either the class or the target method with @objc @objc private func methodOfReceivedNotification(notification: NSNotification) { // Take Action on Notification } // Or dynamic private func methodOfReceivedNotification(notification: NSNotification) { // Take Action on Notification }
Swift
24,049,020
465
I read The Programming Language Swift by Apple in iBooks, but cannot figure out how to make an HTTP request (something like cURL) in Swift. Do I need to import Obj-C classes or do I just need to import default libraries? Or is it not possible to make an HTTP request based on native Swift code?
You can use URL, URLRequest and URLSession or NSURLConnection as you'd normally do in Objective-C. Note that for iOS 7.0 and later, URLSession is preferred. Using URLSession Initialize a URL object and a URLSessionDataTask from URLSession. Then run the task with resume(). let url = URL(string: "http://www.stackoverflow.com")! let task = URLSession.shared.dataTask(with: url) {(data, response, error) in guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } task.resume() Using NSURLConnection First, initialize a URL and a URLRequest: let url = URL(string: "http://www.stackoverflow.com")! var request = URLRequest(url: url) request.httpMethod = "POST" Then, you can load the request asynchronously with: NSURLConnection.sendAsynchronousRequest(request, queue: OperationQueue.main) {(response, data, error) in guard let data = data else { return } print(String(data: data, encoding: .utf8)!) } Or you can initialize an NSURLConnection: let connection = NSURLConnection(request: request, delegate:nil, startImmediately: true) Just make sure to set your delegate to something other than nil and use the delegate methods to work with the response and data received. For more detail, check the documentation for the NSURLConnectionDataDelegate protocol Testing on an Xcode playground If you want to try this code on a Xcode playground, add import PlaygroundSupport to your playground, as well as the following call: PlaygroundPage.current.needsIndefiniteExecution = true This will allow you to use asynchronous code in playgrounds.
Swift
24,016,142
458
Below is how I would have previously truncated a float to two decimal places NSLog(@" %.02f %.02f %.02f", r, g, b); I checked the docs and the eBook but haven't been able to figure it out. Thanks!
The following code: import Foundation // required for String(format: _, _) print(String(format: "a float number: %.2f", 1.0321)) will output: a float number: 1.03
Swift
24,051,314
455
I am trying to use hex color values in Swift, instead of the few standard ones that UIColor allows you to use, but I have no idea how to do it. Example: how would I use #ffffff as a color?
#ffffff are actually 3 color components in hexadecimal notation - red ff, green ff and blue ff. You can write hexadecimal notation in Swift using 0x prefix, e.g 0xFF To simplify the conversion, let's create an initializer that takes integer (0 - 255) values: extension UIColor { convenience init(red: Int, green: Int, blue: Int) { assert(red >= 0 && red <= 255, "Invalid red component") assert(green >= 0 && green <= 255, "Invalid green component") assert(blue >= 0 && blue <= 255, "Invalid blue component") self.init(red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: 1.0) } convenience init(rgb: Int) { self.init( red: (rgb >> 16) & 0xFF, green: (rgb >> 8) & 0xFF, blue: rgb & 0xFF ) } } Usage: let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF) let color2 = UIColor(rgb: 0xFFFFFF) How to get alpha? Depending on your use case, you can simply use the native UIColor.withAlphaComponent method, e.g. let semitransparentBlack = UIColor(rgb: 0x000000).withAlphaComponent(0.5) Or you can add an additional (optional) parameter to the above methods: convenience init(red: Int, green: Int, blue: Int, a: CGFloat = 1.0) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: a ) } convenience init(rgb: Int, a: CGFloat = 1.0) { self.init( red: (rgb >> 16) & 0xFF, green: (rgb >> 8) & 0xFF, blue: rgb & 0xFF, a: a ) } (we cannot name the parameter alpha because of a name collision with the existing initializer). Called as: let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0.5) let color2 = UIColor(rgb: 0xFFFFFF, a: 0.5) To get the alpha as an integer 0-255, we can convenience init(red: Int, green: Int, blue: Int, a: Int = 0xFF) { self.init( red: CGFloat(red) / 255.0, green: CGFloat(green) / 255.0, blue: CGFloat(blue) / 255.0, alpha: CGFloat(a) / 255.0 ) } // let's suppose alpha is the first component (ARGB) convenience init(argb: Int) { self.init( red: (argb >> 16) & 0xFF, green: (argb >> 8) & 0xFF, blue: argb & 0xFF, a: (argb >> 24) & 0xFF ) } Called as let color = UIColor(red: 0xFF, green: 0xFF, blue: 0xFF, a: 0xFF) let color2 = UIColor(argb: 0xFFFFFFFF) Or a combination of the previous methods. There is absolutely no need to use strings.
Swift
24,263,007
450
I know how to programmatically do it, but I'm sure there's a built-in way... Every language I've used has some sort of default textual representation for a collection of objects that it will spit out when you try to concatenate the Array with a string, or pass it to a print() function, etc. Does Apple's Swift language have a built-in way of easily turning an Array into a String, or do we always have to be explicit when stringifying an array?
If the array contains strings, you can use the String's join method: var array = ["1", "2", "3"] let stringRepresentation = "-".join(array) // "1-2-3" In Swift 2: var array = ["1", "2", "3"] let stringRepresentation = array.joinWithSeparator("-") // "1-2-3" This can be useful if you want to use a specific separator (hyphen, blank, comma, etc). Otherwise, you can simply use the description property, which returns a string representation of the array: let stringRepresentation = [1, 2, 3].description // "[1, 2, 3]" Hint: any object implementing the Printable protocol has a description property. If you adopt that protocol in your classes/structs, you make them print-friendly as well In Swift 3 join becomes joined, example [nil, "1", "2"].flatMap({$0}).joined() joinWithSeparator becomes joined(separator:) (only available to Array of Strings) In Swift 4 var array = ["1", "2", "3"] array.joined(separator:"-")
Swift
25,827,033
447
I can see these definitions in the Swift library: extension Bool : BooleanLiteralConvertible { static func convertFromBooleanLiteral(value: Bool) -> Bool } protocol BooleanLiteralConvertible { typealias BooleanLiteralType class func convertFromBooleanLiteral(value: BooleanLiteralType) -> Self } What's the difference between a member function defined as static func and another one defined as class func? Is it simply that static is for static functions of structs and enums, and class for classes and protocols? Are there any other differences that one should know about? What is the rationale for having this distinction in the syntax itself?
To be clearer, I make an example here, class ClassA { class func func1() -> String { return "func1" } static func func2() -> String { return "func2" } } /* same as above final class func func2() -> String { return "func2" } */ static func is same as final class func Because it is final, we can not override it in subclass as below: class ClassB: ClassA { override class func func1() -> String { return "func1 in ClassB" } // ERROR: Class method overrides a 'final` class method override static func func2() -> String { return "func2 in ClassB" } }
Swift
25,156,377
443
The new SwiftUI tutorial has the following code: struct ContentView: View { var body: some View { Text("Hello World") } } The second line the word some, and on their site is highlighted as if it were a keyword. Swift 5.1 does not appear to have some as a keyword, and I don't see what else the word some could be doing there, since it goes where the type usually goes. Is there a new, unannounced version of Swift? Is it a function that's being used on a type in a way I didn't know about? What does the keyword some do?
some View is an opaque result type as introduced by SE-0244 and is available in Swift 5.1 with Xcode 11. You can think of this as being a "reverse" generic placeholder. Unlike a regular generic placeholder which is satisfied by the caller: protocol P {} struct S1 : P {} struct S2 : P {} func foo<T : P>(_ x: T) {} foo(S1()) // Caller chooses T == S1. foo(S2()) // Caller chooses T == S2. An opaque result type is an implicit generic placeholder satisfied by the implementation, so you can think of this: func bar() -> some P { return S1() // Implementation chooses S1 for the opaque result. } as looking like this: func bar() -> <Output : P> Output { return S1() // Implementation chooses Output == S1. } In fact, the eventual goal with this feature is to allow reverse generics in this more explicit form, which would also let you add constraints, e.g -> <T : Collection> T where T.Element == Int. See this post for more info. The main thing to take away from this is that a function returning some P is one that returns a value of a specific single concrete type that conforms to P. Attempting to return different conforming types within the function yields a compiler error: // error: Function declares an opaque return type, but the return // statements in its body do not have matching underlying types. func bar(_ x: Int) -> some P { if x > 10 { return S1() } else { return S2() } } As the implicit generic placeholder cannot be satisfied by multiple types. This is in contrast to a function returning P, which can be used to represent both S1 and S2 because it represents an arbitrary P conforming value: func baz(_ x: Int) -> P { if x > 10 { return S1() } else { return S2() } } Okay, so what benefits do opaque result types -> some P have over protocol return types -> P? 1. Opaque result types can be used with PATs A major current limitation of protocols is that PATs (protocols with associated types) cannot be used as actual types. Although this is a restriction that will likely be lifted in a future version of the language, because opaque result types are effectively just generic placeholders, they can be used with PATs today. This means you can do things like: func giveMeACollection() -> some Collection { return [1, 2, 3] } let collection = giveMeACollection() print(collection.count) // 3 2. Opaque result types have identity Because opaque result types enforce a single concrete type is returned, the compiler knows that two calls to the same function must return two values of the same type. This means you can do things like: // foo() -> <Output : Equatable> Output { func foo() -> some Equatable { return 5 // The opaque result type is inferred to be Int. } let x = foo() let y = foo() print(x == y) // Legal both x and y have the return type of foo. This is legal because the compiler knows that both x and y have the same concrete type. This is an important requirement for ==, where both parameters of type Self. protocol Equatable { static func == (lhs: Self, rhs: Self) -> Bool } This means that it expects two values that are both the same type as the concrete conforming type. Even if Equatable were usable as a type, you wouldn't be able to compare two arbitrary Equatable conforming values with each other, for example: func foo(_ x: Int) -> Equatable { // Assume this is legal. if x > 10 { return 0 } else { return "hello world" } } let x = foo(20) let y = foo(5) print(x == y) // Illegal. As the compiler cannot prove that two arbitrary Equatable values have the same underlying concrete type. In a similar manner, if we introduced another opaque type returning function: // foo() -> <Output1 : Equatable> Output1 { func foo() -> some Equatable { return 5 // The opaque result type is inferred to be Int. } // bar() -> <Output2 : Equatable> Output2 { func bar() -> some Equatable { return "" // The opaque result type is inferred to be String. } let x = foo() let y = bar() print(x == y) // Illegal, the return type of foo != return type of bar. The example becomes illegal because although both foo and bar return some Equatable, their "reverse" generic placeholders Output1 and Output2 could be satisfied by different types. 3. Opaque result types compose with generic placeholders Unlike regular protocol-typed values, opaque result types compose well with regular generic placeholders, for example: protocol P { var i: Int { get } } struct S : P { var i: Int } func makeP() -> some P { // Opaque result type inferred to be S. return S(i: .random(in: 0 ..< 10)) } func bar<T : P>(_ x: T, _ y: T) -> T { return x.i < y.i ? x : y } let p1 = makeP() let p2 = makeP() print(bar(p1, p2)) // Legal, T is inferred to be the return type of makeP. This wouldn't have worked if makeP had just returned P, as two P values may have different underlying concrete types, for example: struct T : P { var i: Int } func makeP() -> P { if .random() { // 50:50 chance of picking each branch. return S(i: 0) } else { return T(i: 1) } } let p1 = makeP() let p2 = makeP() print(bar(p1, p2)) // Illegal. Why use an opaque result type over the concrete type? At this point you may be thinking to yourself, why not just write the code as: func makeP() -> S { return S(i: 0) } Well, the use of an opaque result type allows you to make the type S an implementation detail by exposing only the interface provided by P, giving you flexibility of changing the concrete type later down the line without breaking any code that depends on the function. For example, you could replace: func makeP() -> some P { return S(i: 0) } with: func makeP() -> some P { return T(i: 1) } without breaking any code that calls makeP(). See the Opaque Types section of the language guide and the Swift evolution proposal for further information on this feature.
Swift
56,433,665
437
Is it possible in Swift? If not then is there a workaround to do it?
1. Using default implementations (preferred). protocol MyProtocol { func doSomething() } extension MyProtocol { func doSomething() { /* return a default value or just leave empty */ } } struct MyStruct: MyProtocol { /* no compile error */ } Advantages No Objective-C runtime is involved (well, no explicitly at least). This means you can conform structs, enums and non-NSObject classes to it. Also, this means you can take advantage of powerful generics system. You can always be sure that all requirements are met when encountering types that conform to such protocol. It's always either concrete implementation or default one. This is how "interfaces" or "contracts" behave in other languages. Disadvantages For non-Void requirements, you need to have a reasonable default value, which is not always possible. However, when you encounter this problem, it means that either such requirement should really have no default implementation, or that your you made a mistake during API design. You can't distinguish between a default implementation and no implementation at all, at least without addressing that problem with special return values. Consider the following example: protocol SomeParserDelegate { func validate(value: Any) -> Bool } If you provide a default implementation which just returns true — it's fine at the first glance. Now, consider the following pseudo code: final class SomeParser { func parse(data: Data) -> [Any] { if /* delegate.validate(value:) is not implemented */ { /* parse very fast without validating */ } else { /* parse and validate every value */ } } } There's no way to implement such an optimization — you can't know if your delegate implements a method or not. Although there's a number of different ways to overcome this problem (using optional closures, different delegate objects for different operations to name a few), that example presents the problem clearly. 2. Using @objc optional. @objc protocol MyProtocol { @objc optional func doSomething() } class MyClass: NSObject, MyProtocol { /* no compile error */ } Advantages No default implementation is needed. You just declare an optional method or a variable and you're ready to go. Disadvantages It severely limits your protocol's capabilities by requiring all conforming types to be Objective-C compatible. This means, only classes that inherit from NSObject can conform to such protocol. No structs, no enums, no associated types. You must always check if an optional method is implemented by either optionally calling or checking if the conforming type implements it. This might introduce a lot of boilerplate if you're calling optional methods often.
Swift
24,032,754
435
Does swift have a trim method on String? For example: let result = " abc ".trim() // result == "abc"
Here's how you remove all the whitespace from the beginning and end of a String. (Example tested with Swift 2.0.) let myString = " \t\t Let's trim all the whitespace \n \t \n " let trimmedString = myString.stringByTrimmingCharactersInSet( NSCharacterSet.whitespaceAndNewlineCharacterSet() ) // Returns "Let's trim all the whitespace" (Example tested with Swift 3+.) let myString = " \t\t Let's trim all the whitespace \n \t \n " let trimmedString = myString.trimmingCharacters(in: .whitespacesAndNewlines) // Returns "Let's trim all the whitespace"
Swift
26,797,739
433
Suppose I have an array, for example: var myArray = ["Steve", "Bill", "Linus", "Bret"] And later I want to push/append an element to the end of said array, to get: ["Steve", "Bill", "Linus", "Bret", "Tim"] What method should I use? And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?
As of Swift 3 / 4 / 5, this is done as follows. To add a new element to the end of an Array. anArray.append("This String") To append a different Array to the end of your Array. anArray += ["Moar", "Strings"] anArray.append(contentsOf: ["Moar", "Strings"]) To insert a new element into your Array. anArray.insert("This String", at: 0) To insert the contents of a different Array into your Array. anArray.insert(contentsOf: ["Moar", "Strings"], at: 0) More information can be found in the "Collection Types" chapter of "The Swift Programming Language", starting on page 110.
Swift
24,002,733
429
Does anyone know how to validate an e-mail address in Swift? I found this code: - (BOOL) validEmail:(NSString*) emailString { if([emailString length]==0){ return NO; } NSString *regExPattern = @"[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}"; NSRegularExpression *regEx = [[NSRegularExpression alloc] initWithPattern:regExPattern options:NSRegularExpressionCaseInsensitive error:nil]; NSUInteger regExMatches = [regEx numberOfMatchesInString:emailString options:0 range:NSMakeRange(0, [emailString length])]; NSLog(@"%i", regExMatches); if (regExMatches == 0) { return NO; } else { return YES; } } but I can't translate it to Swift.
I would use NSPredicate: func isValidEmail(_ email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } for versions of Swift earlier than 3.0: func isValidEmail(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) return emailPred.evaluate(with: email) } for versions of Swift earlier than 1.2: func isValidEmail(email: String) -> Bool { let emailRegEx = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,64}" if let emailPred = NSPredicate(format:"SELF MATCHES %@", emailRegEx) { return emailPred.evaluateWithObject(email) } return false }
Swift
25,471,114
425
In earlier versions of Swift, one could create a delay with the following code: let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { //put your code which should be executed with a delay here } But now, in Swift 3, Xcode automatically changes 6 different things but then the following error appears: "Cannot convert DispatchTime.now to expected value dispatch_time_t aka UInt64." How can one create a delay before running a sequence of code in Swift 3?
After a lot of research, I finally figured this one out. DispatchQueue.main.asyncAfter(deadline: .now() + 2.0) { // Change `2.0` to the desired number of seconds. // Code you want to be delayed } This creates the desired "wait" effect in Swift 3 and Swift 4. Inspired by a part of this answer.
Swift
38,031,137
413
How can I add a placeholder in a UITextView, similar to the one you can set for UITextField, in Swift?
Updated for Swift 4 UITextView doesn't inherently have a placeholder property so you'd have to create and manipulate one programmatically using UITextViewDelegate methods. I recommend using either solution #1 or #2 below depending on the desired behavior. Note: For either solution, add UITextViewDelegate to the class and set textView.delegate = self to use the text view’s delegate methods. Solution #1 - If you want the placeholder to disappear as soon as the user selects the text view: First set the UITextView to contain the placeholder text and set it to a light gray color to mimic the look of a UITextField's placeholder text. Either do so in the viewDidLoad or upon the text view's creation. textView.text = "Placeholder" textView.textColor = UIColor.lightGray Then when the user begins to edit the text view, if the text view contains a placeholder (i.e. if its text color is light gray) clear the placeholder text and set the text color to black in order to accommodate the user's entry. func textViewDidBeginEditing(_ textView: UITextView) { if textView.textColor == UIColor.lightGray { textView.text = nil textView.textColor = UIColor.black } } Then when the user finishes editing the text view and it's resigned as the first responder, if the text view is empty, reset its placeholder by re-adding the placeholder text and setting its color to light gray. func textViewDidEndEditing(_ textView: UITextView) { if textView.text.isEmpty { textView.text = "Placeholder" textView.textColor = UIColor.lightGray } } Solution #2 - If you want the placeholder to show whenever the text view is empty, even if the text view’s selected: First set the placeholder in the viewDidLoad: textView.text = "Placeholder" textView.textColor = UIColor.lightGray textView.becomeFirstResponder() textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) (Note: Since the OP wanted to have the text view selected as soon as the view loads, I incorporated text view selection into the above code. If this is not your desired behavior and you do not want the text view selected upon view load, remove the last two lines from the above code chunk.) Then utilize the shouldChangeTextInRange UITextViewDelegate method, like so: func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { // Combine the textView text and the replacement text to // create the updated text string let currentText:String = textView.text let updatedText = (currentText as NSString).replacingCharacters(in: range, with: text) // If updated text view will be empty, add the placeholder // and set the cursor to the beginning of the text view if updatedText.isEmpty { textView.text = "Placeholder" textView.textColor = UIColor.lightGray textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) } // Else if the text view's placeholder is showing and the // length of the replacement string is greater than 0, set // the text color to black then set its text to the // replacement string else if textView.textColor == UIColor.lightGray && !text.isEmpty { textView.textColor = UIColor.black textView.text = text } // For every other case, the text should change with the usual // behavior... else { return true } // ...otherwise return false since the updates have already // been made return false } And also implement textViewDidChangeSelection to prevent the user from changing the position of the cursor while the placeholder's visible. (Note: textViewDidChangeSelection is called before the view loads so only check the text view's color if the window is visible): func textViewDidChangeSelection(_ textView: UITextView) { if self.view.window != nil { if textView.textColor == UIColor.lightGray { textView.selectedTextRange = textView.textRange(from: textView.beginningOfDocument, to: textView.beginningOfDocument) } } }
Swift
27,652,227
411
I'd like to convert an Int in Swift to a String with leading zeros. For example consider this code: for myInt in 1 ... 3 { print("\(myInt)") } Currently the result of it is: 1 2 3 But I want it to be: 01 02 03 Is there a clean way of doing this within the Swift standard libraries?
Assuming you want a field length of 2 with leading zeros you'd do this: import Foundation for myInt in 1 ... 3 { print(String(format: "%02d", myInt)) } output: 01 02 03 This requires import Foundation so technically it is not a part of the Swift language but a capability provided by the Foundation framework. Note that both import UIKit and import Cocoa include Foundation so it isn't necessary to import it again if you've already imported Cocoa or UIKit. The format string can specify the format of multiple items. For instance, if you are trying to format 3 hours, 15 minutes and 7 seconds into 03:15:07 you could do it like this: let hours = 3 let minutes = 15 let seconds = 7 print(String(format: "%02d:%02d:%02d", hours, minutes, seconds)) output: 03:15:07
Swift
25,566,581
410
I want to pause my app at a certain in point. In other words, I want my app to execute the code, but then at a certain point, pause for 4 seconds, and then continue on with the rest of the code. How can I do this? I am using Swift.
Using a dispatch_after block is in most cases better than using sleep(time) as the thread on which the sleep is performed is blocked from doing other work. when using dispatch_after the thread which is worked on does not get blocked so it can do other work in the meantime. If you are working on the main thread of your application, using sleep(time) is bad for the user experience of your app as the UI is unresponsive during that time. Dispatch after schedules the execution of a block of code instead of freezing the thread: Swift ≥ 3.0 let seconds = 4.0 DispatchQueue.main.asyncAfter(deadline: .now() + seconds) { // Put your code which should be executed with a delay here } Swift ≥ 5.5 in an async context: func foo() async { try await Task.sleep(nanoseconds: UInt64(seconds * Double(NSEC_PER_SEC))) // Put your code which should be executed with a delay here } Swift < 3.0 let time = dispatch_time(dispatch_time_t(DISPATCH_TIME_NOW), 4 * Int64(NSEC_PER_SEC)) dispatch_after(time, dispatch_get_main_queue()) { // Put your code which should be executed with a delay here }
Swift
27,517,632
404
The application basically calculates acceleration by inputting Initial and final velocity and time and then use a formula to calculate acceleration. However, since the values in the text boxes are string, I am unable to convert them to integers. @IBOutlet var txtBox1 : UITextField @IBOutlet var txtBox2 : UITextField @IBOutlet var txtBox3 : UITextField @IBOutlet var lblAnswer : UILabel @IBAction func btn1(sender : AnyObject) { let answer1 = "The acceleration is" var answer2 = txtBox1 var answer3 = txtBox2 var answer4 = txtBox3
Updated answer for Swift 2.0+: toInt() method gives an error, as it was removed from String in Swift 2.x. Instead, the Int type now has an initializer that accepts a String: let a: Int? = Int(firstTextField.text) let b: Int? = Int(secondTextField.text)
Swift
24,115,141
399
The ObjectiveC.swift file from the standard library contains the following few lines of code around line 228: extension NSObject : Equatable, Hashable { /// ... open var hashValue: Int { return hash } } What does open var mean in this context, or what is the open keyword in general?
open is a new access level in Swift 3, introduced with the implementation of SE-0117 Allow distinguishing between public access and public overridability It is available with the Swift 3 snapshot from August 7, 2016, and with Xcode 8 beta 6. In short: An open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module. A public class is accessible but not subclassable outside of the defining module. A public class member is accessible but not overridable outside of the defining module. So open is what public used to be in previous Swift releases and the access of public has been restricted. Or, as Chris Lattner puts it in SE-0177: Allow distinguishing between public access and public overridability: “open” is now simply “more public than public”, providing a very simple and clean model. In your example, open var hashValue is a property which is accessible and can be overridden in NSObject subclasses. For more examples and details, have a look at SE-0117.
Swift
38,947,101
396
If I encode a string like this: var escapedString = originalString.stringByAddingPercentEscapesUsingEncoding(NSUTF8StringEncoding) it doesn't escape the slashes /. I've searched and found this Objective C code: NSString *encodedString = (NSString *)CFURLCreateStringByAddingPercentEscapes( NULL, (CFStringRef)unencodedString, NULL, (CFStringRef)@"!*'();:@&=+$,/?%#[]", kCFStringEncodingUTF8 ); Is there an easier way to encode an URL and if not, how do I write this in Swift?
Swift 3 In Swift 3 there is addingPercentEncoding let originalString = "test/test" let escapedString = originalString.addingPercentEncoding(withAllowedCharacters: .urlHostAllowed) print(escapedString!) Output: test%2Ftest Swift 1 In iOS 7 and above there is stringByAddingPercentEncodingWithAllowedCharacters var originalString = "test/test" var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(.URLHostAllowedCharacterSet()) println("escapedString: \(escapedString)") Output: test%2Ftest The following are useful (inverted) character sets: URLFragmentAllowedCharacterSet "#%<>[\]^`{|} URLHostAllowedCharacterSet "#%/<>?@\^`{|} URLPasswordAllowedCharacterSet "#%/:<>?@[\]^`{|} URLPathAllowedCharacterSet "#%;<>?[\]^`{|} URLQueryAllowedCharacterSet "#%<>[\]^`{|} URLUserAllowedCharacterSet "#%/:<>?@[\]^` If you want a different set of characters to be escaped create a set: Example with added "=" character: var originalString = "test/test=42" var customAllowedSet = NSCharacterSet(charactersInString:"=\"#%/<>?@\\^`{|}").invertedSet var escapedString = originalString.stringByAddingPercentEncodingWithAllowedCharacters(customAllowedSet) println("escapedString: \(escapedString)") Output: test%2Ftest%3D42 Example to verify ascii characters not in the set: func printCharactersInSet(set: NSCharacterSet) { var characters = "" let iSet = set.invertedSet for i: UInt32 in 32..<127 { let c = Character(UnicodeScalar(i)) if iSet.longCharacterIsMember(i) { characters = characters + String(c) } } print("characters not in set: \'\(characters)\'") }
Swift
24,551,816
393
There has been many Questions recently about drawing PDF's. Yes, you can render PDF's very easily with a UIWebView but this cant give the performance and functionality that you would expect from a good PDF viewer. You can draw a PDF page to a CALayer or to a UIImage. Apple even have sample code to show how draw a large PDF in a Zoomable UIScrollview But the same issues keep cropping up. UIImage Method: PDF's in a UIImage don't optically scale as well as a Layer approach. The CPU and memory hit on generating the UIImages from a PDFcontext limits/prevents using it to create a real-time render of new zoom-levels. CATiledLayer Method: Theres a significant Overhead (time) drawing a full PDF page to a CALayer: individual tiles can be seen rendering (even with a tileSize tweak) CALayers cant be prepared ahead of time (rendered off-screen). Generally PDF viewers are pretty heavy on memory too. Even monitor the memory usage of apple's zoomable PDF example. In my current project, I'm developing a PDF viewer and am rendering a UIImage of a page in a separate thread (issues here too!) and presenting it while the scale is x1. CATiledLayer rendering kicks in once the scale is >1. iBooks takes a similar double take approach as if you scroll the pages you can see a lower res version of the page for just less than a second before a crisp version appears. Im rendering 2 pages each side of the page in focus so that the PDF image is ready to mask the layer before it starts drawing.Pages are destroyed again when they are +2 pages away from the focused page. Does anyone have any insights, no matter how small or obvious to improve the performance/ memory handling of Drawing PDF's? or any other issues discussed here? EDIT: Some Tips (Credit- Luke Mcneice,VdesmedT,Matt Gallagher,Johann): Save any media to disk when you can. Use larger tileSizes if rendering on TiledLayers init frequently used arrays with placeholder objects, alternitively another design approach is this one Note that images will render faster than a CGPDFPageRef Use NSOperations or GCD & Blocks to prepare pages ahead of time. call CGContextSetInterpolationQuality(ctx, kCGInterpolationHigh); CGContextSetRenderingIntent(ctx, kCGRenderingIntentDefault); before CGContextDrawPDFPage to reduce memory usage while drawing init'ing your NSOperations with a docRef is a bad idea (memory), wrap the docRef into a singleton. Cancel needless NSOperations When you can, especially if they will be using memory, beware of leaving contexts open though! Recycle page objects and destroy unused views Close any open Contexts as soon as you don't need them on receiving memory warnings release and reload the DocRef and any page Caches Other PDF Features: Getting Links inside a PDF (and here and here) Understanding the PDF Rect for link positioning Converting PDF annot datestrings Getting the target of the link (Getting the page number from the /Dest array) Getting a table of contents Document title and Keywords Getting Raw Text (and here and Here and here (positioning focused)) Searching(and here) (doesn't work with all PDFs (some just show weird characters, I guess it's an encoding issue but I'm not sure) -Credit BrainFeeder) CALayer and Off-Screen Rendering - render the next page for fast/smooth display Documentation Quartz PDFObjects (Used for meta info, annotations, thumbs) Abobe PDF Spec Example projects Apple/ ZoomingPDF - zooming, UIScrollView, CATiledLayer vfr/ reader - zooming, paging, UIScrollView, CATiledView brow/ leaves - paging with nice transitions / skim - everything it seems (PDF reader/editor for OSX)
I have build such kind of application using approximatively the same approach except : I cache the generated image on the disk and always generate two to three images in advance in a separate thread. I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued. Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like : CGAffineTransform currentCTM = CGContextGetCTM(context); if (currentCTM.a == 1.0 && baseImage) { //Calculate ideal scale CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width; CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight); CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor); CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height); CGContextDrawImage(context, imageRect, [baseImage CGImage]); } else { @synchronized(issue) { CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1); pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true); CGContextConcatCTM(context, pdfToPageTransform); CGContextDrawPDFPage(context, pdfPage); } } issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.
Swift
3,889,634
379
I need to read and write data to/from a text file, but I haven't been able to figure out how. I found this sample code in the Swift's iBook, but I still don't know how to write or read data. import Cocoa class DataImporter { /* DataImporter is a class to import data from an external file. The class is assumed to take a non-trivial amount of time to initialize. */ var fileName = "data.txt" // the DataImporter class would provide data importing functionality here } class DataManager { @lazy var importer = DataImporter() var data = String[]() // the DataManager class would provide data management functionality here } let manager = DataManager() manager.data += "Some data" manager.data += "Some more data" // the DataImporter instance for the importer property has not yet been created” println(manager.importer.fileName) // the DataImporter instance for the importer property has now been created // prints "data.txt” var str = "Hello World in Swift Language."
For reading and writing you should use a location that is writeable, for example documents directory. The following code shows how to read and write a simple string. You can test it on a playground. Swift 3.x - 5.x let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first { let fileURL = dir.appendingPathComponent(file) //writing do { try text.write(to: fileURL, atomically: false, encoding: .utf8) } catch {/* error handling here */} //reading do { let text2 = try String(contentsOf: fileURL, encoding: .utf8) } catch {/* error handling here */} } Swift 2.2 let file = "file.txt" //this is the file. we will write to and read from it let text = "some text" //just a text if let dir = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first { let path = NSURL(fileURLWithPath: dir).URLByAppendingPathComponent(file) //writing do { try text.writeToURL(path, atomically: false, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} //reading do { let text2 = try NSString(contentsOfURL: path, encoding: NSUTF8StringEncoding) } catch {/* error handling here */} } Swift 1.x let file = "file.txt" if let dirs : [String] = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true) as? [String] { let dir = dirs[0] //documents directory let path = dir.stringByAppendingPathComponent(file); let text = "some text" //writing text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding, error: nil); //reading let text2 = String(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) }
Swift
24,097,826
378
In my Objective-C projects I often use a global constants file to store things like notification names and keys for NSUserDefaults. It looks something like this: @interface GlobalConstants : NSObject extern NSString *someNotification; @end @implementation GlobalConstants NSString *someNotification = @"aaaaNotification"; @end How do I do exactly the same thing in Swift?
Structs as namespace IMO the best way to deal with that type of constants is to create a Struct. struct Constants { static let someNotification = "TEST" } Then, for example, call it like this in your code: print(Constants.someNotification) Nesting If you want a better organization I advise you to use segmented sub structs struct K { struct NotificationKey { static let Welcome = "kWelcomeNotif" } struct Path { static let Documents = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as String static let Tmp = NSTemporaryDirectory() } } Then you can just use for instance K.Path.Tmp Real world example This is just a technical solution, the actual implementation in my code looks more like: struct GraphicColors { static let grayDark = UIColor(0.2) static let grayUltraDark = UIColor(0.1) static let brown = UIColor(rgb: 126, 99, 89) // etc. } and enum Env: String { case debug case testFlight case appStore } struct App { struct Folders { static let documents: NSString = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString static let temporary: NSString = NSTemporaryDirectory() as NSString } static let version: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as! String static let build: String = Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as! String // This is private because the use of 'appConfiguration' is preferred. private static let isTestFlight = Bundle.main.appStoreReceiptURL?.lastPathComponent == "sandboxReceipt" // This can be used to add debug statements. static var isDebug: Bool { #if DEBUG return true #else return false #endif } static var env: Env { if isDebug { return .debug } else if isTestFlight { return .testFlight } else { return .appStore } } }
Swift
26,252,233
373
What is the difference between let and var in Apple's Swift language? In my understanding, it is a compiled language but it does not check the type at compile time. It makes me confused. How does the compiler know about the type error? If the compiler doesn't check the type, isn't it a problem with production environment? This error is given when I try to assign a value to a let: Cannot assign to property: 'variableName' is a 'let' constant Change 'let' to 'var' to make it mutable
The let keyword defines a constant: let theAnswer = 42 The theAnswer cannot be changed afterwards. This is why anything weak can't be written using let. They need to change during runtime and you must be using var instead. The var defines an ordinary variable. What is interesting: The value of a constant doesn’t need to be known at compile time, but you must assign the value exactly once. Another strange feature: You can use almost any character you like for constant and variable names, including Unicode characters: let 🐶🐮 = "dogcow" Excerpts From: Apple Inc. “The Swift Programming Language.” iBooks. https://itunes.apple.com/WebObjects/MZStore.woa/wa/viewBook?id=881256329 Community Wiki Because comments are asking for adding other facts to the answer, converting this to community wiki answer. Feel free edit the answer to make it better.
Swift
24,002,092
371
I am trying to check when a text field changes, equivalent too the function used for textView - textViewDidChange so far I have done this: func textFieldDidBeginEditing(textField: UITextField) { if self.status.text == "" && self.username.text == "" { self.topRightButton.enabled = false } else { self.topRightButton.enabled = true } } Which kind of works, but the topRightButton is enabled as soon as the text field is pressed on, I want it to be enabled only when text is actually typed in?
SWIFT Swift 4.2 textfield.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged) and @objc func textFieldDidChange(_ textField: UITextField) { } SWIFT 3 & swift 4.1 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), for: .editingChanged) and func textFieldDidChange(_ textField: UITextField) { } SWIFT 2.2 textField.addTarget(self, action: #selector(ViewController.textFieldDidChange(_:)), forControlEvents: UIControlEvents.EditingChanged) and func textFieldDidChange(textField: UITextField) { //your code } OBJECTIVE-C [textField addTarget:self action:@selector(textFieldDidChange:) forControlEvents:UIControlEventEditingChanged]; and textFieldDidChange method is -(void)textFieldDidChange :(UITextField *) textField{ //your code }
Swift
28,394,933
369
I have the following simple code written in Swift 3: let str = "Hello, playground" let index = str.index(of: ",")! let newStr = str.substring(to: index) From Xcode 9 beta 5, I get the following warning: 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator. How can this slicing subscript with partial range from be used in Swift 4?
You should leave one side empty, hence the name "partial range". let newStr = str[..<index] The same stands for partial range from operators, just leave the other side empty: let newStr = str[index...] Keep in mind that these range operators return a Substring. If you want to convert it to a string, use String's initialization function: let newStr = String(str[..<index]) You can read more about the new substrings here.
Swift
45,562,662
367
I might have an array that looks like the following: [1, 4, 2, 2, 6, 24, 15, 2, 60, 15, 6] Or, really, any sequence of like-typed portions of data. What I want to do is ensure that there is only one of each identical element. For example, the above array would become: [1, 4, 2, 6, 24, 15, 60] Notice that the duplicates of 2, 6, and 15 were removed to ensure that there was only one of each identical element. Does Swift provide a way to do this easily, or will I have to do it myself?
You can convert to a Set and back to an Array again quite easily: let unique = Array(Set(originals)) This is not guaranteed to maintain the original order of the array.
Swift
25,738,817
366
Is there a way to print the runtime type of a variable in swift? For example: var now = NSDate() var soon = now.dateByAddingTimeInterval(5.0) println("\(now.dynamicType)") // Prints "(Metatype)" println("\(now.dynamicType.description()") // Prints "__NSDate" since objective-c Class objects have a "description" selector println("\(soon.dynamicType.description()") // Compile-time error since ImplicitlyUnwrappedOptional<NSDate> has no "description" method In the example above, I'm looking for a way to show that the variable "soon" is of type ImplicitlyUnwrappedOptional<NSDate>, or at least NSDate!.
Update September 2016 Swift 3.0: Use type(of:), e.g. type(of: someThing) (since the dynamicType keyword has been removed) Update October 2015: I updated the examples below to the new Swift 2.0 syntax (e.g. println was replaced with print, toString() is now String()). From the Xcode 6.3 release notes: @nschum points out in the comments that the Xcode 6.3 release notes show another way: Type values now print as the full demangled type name when used with println or string interpolation. import Foundation class PureSwiftClass { } var myvar0 = NSString() // Objective-C class var myvar1 = PureSwiftClass() var myvar2 = 42 var myvar3 = "Hans" print( "String(myvar0.dynamicType) -> \(myvar0.dynamicType)") print( "String(myvar1.dynamicType) -> \(myvar1.dynamicType)") print( "String(myvar2.dynamicType) -> \(myvar2.dynamicType)") print( "String(myvar3.dynamicType) -> \(myvar3.dynamicType)") print( "String(Int.self) -> \(Int.self)") print( "String((Int?).self -> \((Int?).self)") print( "String(NSString.self) -> \(NSString.self)") print( "String(Array<String>.self) -> \(Array<String>.self)") Which outputs: String(myvar0.dynamicType) -> __NSCFConstantString String(myvar1.dynamicType) -> PureSwiftClass String(myvar2.dynamicType) -> Int String(myvar3.dynamicType) -> String String(Int.self) -> Int String((Int?).self -> Optional<Int> String(NSString.self) -> NSString String(Array<String>.self) -> Array<String> Update for Xcode 6.3: You can use the _stdlib_getDemangledTypeName(): print( "TypeName0 = \(_stdlib_getDemangledTypeName(myvar0))") print( "TypeName1 = \(_stdlib_getDemangledTypeName(myvar1))") print( "TypeName2 = \(_stdlib_getDemangledTypeName(myvar2))") print( "TypeName3 = \(_stdlib_getDemangledTypeName(myvar3))") and get this as output: TypeName0 = NSString TypeName1 = __lldb_expr_26.PureSwiftClass TypeName2 = Swift.Int TypeName3 = Swift.String Original answer: Prior to Xcode 6.3 _stdlib_getTypeName got the mangled type name of a variable. Ewan Swick's blog entry helps to decipher these strings: e.g. _TtSi stands for Swift's internal Int type. Mike Ash has a great blog entry covering the same topic.
Swift
24,006,165
365
I'm using Core Data with Cloud Kit, and have therefore to check the iCloud user status during application startup. In case of problems I want to issue a dialog to the user, and I do it using UIApplication.shared.keyWindow?.rootViewController?.present(...) up to now. In Xcode 11 beta 4, there is now a new deprecation message, telling me: 'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes How shall I present the dialog instead?
Edit The suggestion I make here is deprecated in iOS 15. So now what? Well, if an app doesn't have multiple windows of its own, I presume the accepted modern way would be to get the first of the app's connectedScenes, coerce to a UIWindowScene, and take its first window. But that is almost exactly what the accepted answer does! So my workaround feels rather feeble at this point. However, I'll let it stand for historical reasons. The accepted answer, while ingenious, might be overly elaborate. You can get exactly the same result much more simply: UIApplication.shared.windows.filter {$0.isKeyWindow}.first I would also caution that the deprecation of keyWindow should not be taken overly seriously. The full warning message reads: 'keyWindow' was deprecated in iOS 13.0: Should not be used for applications that support multiple scenes as it returns a key window across all connected scenes So if you are not supporting multiple windows on iPad there is no objection to going ahead and continuing to use keyWindow.
Swift
57,134,259
365
If I have an array in Swift, and try to access an index that is out of bounds, there is an unsurprising runtime error: var str = ["Apple", "Banana", "Coconut"] str[0] // "Apple" str[3] // EXC_BAD_INSTRUCTION However, I would have thought with all the optional chaining and safety that Swift brings, it would be trivial to do something like: let theIndex = 3 if let nonexistent = str[theIndex] { // Bounds check + Lookup print(nonexistent) ...do other things with nonexistent... } Instead of: let theIndex = 3 if (theIndex < str.count) { // Bounds check let nonexistent = str[theIndex] // Lookup print(nonexistent) ...do other things with nonexistent... } But this is not the case - I have to use the ol' if statement to check and ensure the index is less than str.count. I tried adding my own subscript() implementation, but I'm not sure how to pass the call to the original implementation, or to access the items (index-based) without using subscript notation: extension Array { subscript(var index: Int) -> AnyObject? { if index >= self.count { NSLog("Womp!") return nil } return ... // What? } }
Alex's answer has good advice and solution for the question, however, I've happened to stumble on a nicer way of implementing this functionality: extension Collection { /// Returns the element at the specified index if it is within bounds, otherwise nil. subscript (safe index: Index) -> Element? { return indices.contains(index) ? self[index] : nil } } Example let array = [1, 2, 3] for index in -20...20 { if let item = array[safe: index] { print(item) } }
Swift
25,329,186
360
Note, extremely old historic QA. (Is now just #if targetEnvironment(simulator).) In Objective-C we can know if an app is being built for device or simulator using macros: #if TARGET_IPHONE_SIMULATOR // Simulator #else // Device #endif These are compile time macros and not available at runtime. How can I achieve the same in Swift?
Update 30/01/19 While this answer may work, the recommended solution for a static check (as clarified by several Apple engineers) is to define a custom compiler flag targeting iOS Simulators. For detailed instructions on how to do to it, see @mbelsky's answer. Original answer If you need a static check (e.g. not a runtime if/else) you can't detect the simulator directly, but you can detect iOS on a desktop architecture like follows #if (arch(i386) || arch(x86_64)) && os(iOS) ... #endif After Swift 4.1 version Latest use, now directly for all in one condition for all types of simulators need to apply only one condition - #if targetEnvironment(simulator) // your simulator code #else // your real device code #endif For more clarification, you can check Swift proposal SE-0190 For older version - Clearly, this is false on a device, but it returns true for the iOS Simulator, as specified in the documentation: The arch(i386) build configuration returns true when the code is compiled for the 32–bit iOS simulator. If you are developing for a simulator other than iOS, you can simply vary the os parameter: e.g. Detect the watchOS simulator #if (arch(i386) || arch(x86_64)) && os(watchOS) ... #endif Detect the tvOS simulator #if (arch(i386) || arch(x86_64)) && os(tvOS) ... #endif Or, even, detect any simulator #if (arch(i386) || arch(x86_64)) && (os(iOS) || os(watchOS) || os(tvOS)) ... #endif If you instead are ok with a runtime check, you can inspect the TARGET_OS_SIMULATOR variable (or TARGET_IPHONE_SIMULATOR in iOS 8 and below), which is truthy on a simulator. Please notice that this is different and slightly more limited than using a preprocessor flag. For instance you won't be able to use it in place where a if/else is syntactically invalid (e.g. outside of functions scopes). Say, for example, that you want to have different imports on the device and on the simulator. This is impossible with a dynamic check, whereas it's trivial with a static check. #if (arch(i386) || arch(x86_64)) && os(iOS) import Foo #else import Bar #endif Also, since the flag is replaced with a 0 or a 1 by the swift preprocessor, if you directly use it in a if/else expression the compiler will raise a warning about unreachable code. In order to work around this warning, see one of the other answers.
Swift
24,869,481
358
After upgrading to Xcode 11.2 from Xcode 11.1 my app crashes: *** Terminating app due to uncaught exception 'NSInvalidUnarchiveOperationException', reason: 'Could not instantiate class named _UITextLayoutView because no class named _UITextLayoutView was found; the class needs to be defined in source code or linked in from a library (ensure the class is part of the correct target)' Why is this happening? How can I prevent this crash?
Update: Fixed! 🎉🎊 The ONLY Solution is to update This bug is fixed in Xcode 11.2.1. So you can download and use it from here. Storyboards containing a UITextView will no longer cause the app to crash on operating system versions earlier than iOS 13.2, tvOS 13.2, or macOS 10.15.2. (56808566, 56873523) Xcode 11.2 is deprecated by Apple on November 5, 2019 if you ever try to submit your app that build with Xcode 11.2 to the AppStore, you will be rejected: App Store Connect Operation Warning WARNING ITMS-90703: "Deprecated Xcode Build. Due to resolved app archives issues, we have deprecated Xcode 11.2 on November 5, 2019. Download Xcode 11.2.1 or newer, rebuild your app and resubmit." So all workarounds done with the Xcode 11.2 is useless It's a bug for Xcode 11.2, and fixed in Xcode 11.2.1. Solution(s) Roll back to previous Xcode release version from: Rollback is not an option anymore and AppStore will reject any build with Xcode below 11.2.1 take a look at this https://developer.apple.com/services-account/download?path=/Developer_Tools/Xcode_11.1/Xcode_11.1.xip Note that you should use Safari to download it and you must first login to Apple developer portal. You can find all other Xcode versions and other resources link (including release and beta versions) here at https://developer.apple.com/download/more The workaround This is very hard but working workaround. Replace all UITextViews in storyboards and Xibs with the pure code version. Note that this bug is found and fixed by Apple Also earlier, the bug was confirmed by Apple Staff edford For those with iOS 13.2 and can not use Xcode 11.1 anymore: Update macOS to 10.15.1 or later Install Xcode 11.2.1 or later It should be work now on the updated device. For those with storyboard: Subclass UITextView Assign it to all UITextView objects Don't forget to update any property changes that may lose in the subclassing. For those comfortable with method swizzling (Objc and dynamic behavior) Head to the @aftab muhammed khan answer for Objective-C and @MikRo answer for Swift adapted version Just don't do it anymore: Even if these last two swizzling workarounds are not using Apple private API, they will be rejected in AppStore because Apple will not accept builds with Xcode versions under 11.2.1! And once again: Xcode 11.2 is deprecated by Apple on November 5, 2019
Swift
58,657,087
355
Among the many properties of the Text view, I couldn't find any related to text alignment. I've seen in a demo that it automatically handles RTL, and when placing stuff using View's body, it always centers it automatically. Is there some concept that I'm missing about layout system in SwiftUI and if not, how can I set the text alignment properties to the Text?
You can do this via the modifier .multilineTextAlignment(.center). Text("CENTER") .multilineTextAlignment(.center) Apple Documentation
Swift
56,443,535
354
Issue I started taking a look on the Swift Programming Language, and somehow I am not able to correctly type the initialization of a UIViewController from a specific UIStoryboard. In Objective-C I simply write: UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"StoryboardName" bundle:nil]; UIViewController *viewController = [storyboard instantiateViewControllerWithIdentifier:@"ViewControllerID"]; [self presentViewController:viewController animated:YES completion:nil]; Can anyone help me on how to achieve this on Swift?
This answer was last revised for Swift 5.4 and iOS 14.5 SDK. It's all a matter of new syntax and slightly revised APIs. The underlying functionality of UIKit hasn't changed. This is true for a vast majority of iOS SDK frameworks. let storyboard = UIStoryboard(name: "myStoryboardName", bundle: nil) let vc = storyboard.instantiateViewController(withIdentifier: "myVCID") self.present(vc, animated: true) Make sure to set myVCID inside the storyboard, under "Storyboard ID."
Swift
24,035,984
352
I am currently using the following (clumsy) pieces of code for determining if a (non-empty) Swift dictionary contains a given key and for obtaining one (any) value from the same dictionary. How can one put this more elegantly in Swift? // excerpt from method that determines if dict contains key if let _ = dict[key] { return true } else { return false } // excerpt from method that obtains first value from dict for (_, value) in dict { return value }
You don't need any special code to do this, because it is what a dictionary already does. When you fetch dict[key] you know whether the dictionary contains the key, because the Optional that you get back is not nil (and it contains the value). So, if you just want to answer the question whether the dictionary contains the key, ask: let keyExists = dict[key] != nil If you want the value and you know the dictionary contains the key, say: let val = dict[key]! But if, as usually happens, you don't know it contains the key - you want to fetch it and use it, but only if it exists - then use something like if let: if let val = dict[key] { // now val is not nil and the Optional has been unwrapped, so use it }
Swift
28,129,401
352
I have an app that has a text field on the lower half of the view. This means that when I go to type in the text field the keyboard covers the textfield. How would I go about moving the view upwards while typing so I can see what i'm typing and then moving it back down to its original place when the keyboard disappears? I've looked everywhere but all the solutions appear to be in Obj-C which I can't quite convert just yet. Any help would be greatly appreciated.
Here is a solution, without handling the switch from one textField to another: override func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name: UIKeyboardWillShowNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name: UIKeyboardWillHideNotification, object: nil) } func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { self.view.frame.origin.y -= keyboardSize.height } } func keyboardWillHide(notification: NSNotification) { self.view.frame.origin.y = 0 } To solve this, replace the two functions keyboardWillShow/Hide with these: func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.CGRectValue() { if view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } func keyboardWillHide(notification: NSNotification) { if view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } Swift 3.0: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } Swift 4.0: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIKeyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } } Swift 4.2: override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) } @objc func keyboardWillShow(notification: NSNotification) { if let keyboardSize = (notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)?.cgRectValue { if self.view.frame.origin.y == 0 { self.view.frame.origin.y -= keyboardSize.height } } } @objc func keyboardWillHide(notification: NSNotification) { if self.view.frame.origin.y != 0 { self.view.frame.origin.y = 0 } }
Swift
26,070,242
350
I have an app where the user can choose an image either from the built-in app images or from the iphone photo library. I use an object Occasion that has an NSString property to save the imagePath. Now in the case of the built-in app images I do get the file name as an NSString an save in the [occasion imagePath]. But in the 2nd case where the user picks an image form the photo library I get an NSURL which I want to convert to an NSString to be able to save it in [occasion imagePath]. Is it possible to convert the NSURL to an NSString?
In Objective-C: NSString *myString = myURL.absoluteString; In Swift: var myString = myURL.absoluteString More info in the docs:
Swift
8,082,719
348
In my iOS Swift app I want to generate random UUID (GUID) strings for use as a table key, and this snippet appears to work: let uuid = CFUUIDCreateString(nil, CFUUIDCreate(nil)) Is this safe? Or is there perhaps a better (recommended) approach?
Try this one: let uuid = NSUUID().uuidString print(uuid) Swift 3/4/5 let uuid = UUID().uuidString print(uuid)
Swift
24,428,250
338
Just started with the playground. I'm trying to create a simple app. I've created a date object like this: var date = NSDate() How can I get the current hour? In other languages I can do something like this: var hour = date.hour But I can't find any properties/methods like that. I've found a method, dateWithCalendarFormat. Should I use that? If so, HOW?
Update for Swift 3: let date = Date() let calendar = Calendar.current let hour = calendar.component(.hour, from: date) let minutes = calendar.component(.minute, from: date) I do this: let date = NSDate() let calendar = NSCalendar.currentCalendar() let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date) let hour = components.hour let minutes = components.minute See the same question in objective-c How do I get hour and minutes from NSDate? Compared to Nate’s answer, you’ll get numbers with this one, not strings… pick your choice!
Swift
24,070,450
337
In swift there seem to be two equality operators: the double equals (==) and the triple equals (===), what is the difference between the two?
!== and === are identity operators and are used to determine if two objects have the same reference. Swift also provides two identity operators (=== and !==), which you use to test whether two object references both refer to the same object instance. Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l
Swift
24,002,819
336
I have written a library in Swift and I wasn't able to import it to my current project, written in Objective-C. Are there any ways to import it? #import "SCLAlertView.swift" - 'SCLAlertView.swift' file not found
You need to import ProductName-Swift.h. Note that it's the product name - the other answers make the mistake of using the class name. This single file is an autogenerated header that defines Objective-C interfaces for all Swift classes in your project that are either annotated with @objc or inherit from NSObject. Considerations: If your product name contains spaces, replace them with underscores (e.g. My Project becomes My_Project-Swift.h) If your target is a framework, you need to import <ProductName/ProductName-Swift.h> Make sure your Swift file is a member of the target
Swift
24,102,104
334
How can I hide a navigation bar from first ViewController or a particular ViewController in swift? I used the following code in viewDidLoad(): override func viewDidLoad() { super.viewDidLoad() self.navigationController?.isNavigationBarHidden = true } and also on viewWillAppear: override func viewWillAppear(animated: Bool) { self.navigationController?.isNavigationBarHidden = true } Both methods hide the navigation controller from all ViewControllers.
If you know that all other views should have the bar visible, you could use viewWillDisappear to set it to visible again. In Swift: override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) navigationController?.setNavigationBarHidden(false, animated: animated) }
Swift
29,209,453
332
.shuffle() and .shuffled() are part of Swift Original historic question: How do I randomize or shuffle the elements within an array in Swift? For example, if my array consists of 52 playing cards, I want to shuffle the array in order to shuffle the deck.
This answer details how to shuffle with a fast and uniform algorithm (Fisher-Yates) in Swift 4.2+ and how to add the same feature in the various previous versions of Swift. The naming and behavior for each Swift version matches the mutating and nonmutating sorting methods for that version. Swift 4.2+ shuffle and shuffled are native starting Swift 4.2. Example usage: let x = [1, 2, 3].shuffled() // x == [2, 3, 1] let fiveStrings = stride(from: 0, through: 100, by: 5).map(String.init).shuffled() // fiveStrings == ["20", "45", "70", "30", ...] var numbers = [1, 2, 3, 4] numbers.shuffle() // numbers == [3, 2, 1, 4] Swift 4.0 and 4.1 These extensions add a shuffle() method to any mutable collection (arrays and unsafe mutable buffers) and a shuffled() method to any sequence: extension MutableCollection { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled, unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { // Change `Int` in the next line to `IndexDistance` in < Swift 4.1 let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount))) let i = index(firstUnshuffled, offsetBy: d) swapAt(firstUnshuffled, i) } } } extension Sequence { /// Returns an array with the contents of this sequence, shuffled. func shuffled() -> [Element] { var result = Array(self) result.shuffle() return result } } Same usage as in Swift 4.2 examples above. Swift 3 These extensions add a shuffle() method to any mutable collection and a shuffled() method to any sequence: extension MutableCollection where Indices.Iterator.Element == Index { /// Shuffles the contents of this collection. mutating func shuffle() { let c = count guard c > 1 else { return } for (firstUnshuffled , unshuffledCount) in zip(indices, stride(from: c, to: 1, by: -1)) { // Change `Int` in the next line to `IndexDistance` in < Swift 3.2 let d: Int = numericCast(arc4random_uniform(numericCast(unshuffledCount))) guard d != 0 else { continue } let i = index(firstUnshuffled, offsetBy: d) self.swapAt(firstUnshuffled, i) } } } extension Sequence { /// Returns an array with the contents of this sequence, shuffled. func shuffled() -> [Iterator.Element] { var result = Array(self) result.shuffle() return result } } Same usage as in Swift 4.2 examples above. Swift 2 (obsolete language: you can't use Swift 2.x to publish on iTunes Connect starting July 2018) extension MutableCollectionType where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffleInPlace() { // empty and single-element collections don't shuffle if count < 2 { return } for i in startIndex ..< endIndex - 1 { let j = Int(arc4random_uniform(UInt32(count - i))) + i guard i != j else { continue } swap(&self[i], &self[j]) } } } extension CollectionType { /// Return a copy of `self` with its elements shuffled. func shuffle() -> [Generator.Element] { var list = Array(self) list.shuffleInPlace() return list } } Usage: [1, 2, 3].shuffle() // [2, 3, 1] let fiveStrings = 0.stride(through: 100, by: 5).map(String.init).shuffle() // ["20", "45", "70", "30", ...] var numbers = [1, 2, 3, 4] numbers.shuffleInPlace() // [3, 2, 1, 4] Swift 1.2 (obsolete language: you can't use Swift 1.x to publish on iTunes Connect starting July 2018) shuffle as a mutating array method This extension will let you shuffle a mutable Array instance in place: extension Array { mutating func shuffle() { if count < 2 { return } for i in 0..<(count - 1) { let j = Int(arc4random_uniform(UInt32(count - i))) + i swap(&self[i], &self[j]) } } } var numbers = [1, 2, 3, 4, 5, 6, 7, 8] numbers.shuffle() // e.g., numbers == [6, 1, 8, 3, 2, 4, 7, 5] shuffled as a non-mutating array method This extension will let you retrieve a shuffled copy of an Array instance: extension Array { func shuffled() -> [T] { if count < 2 { return self } var list = self for i in 0..<(list.count - 1) { let j = Int(arc4random_uniform(UInt32(list.count - i))) + i swap(&list[i], &list[j]) } return list } } let numbers = [1, 2, 3, 4, 5, 6, 7, 8] let mixedup = numbers.shuffled() // e.g., mixedup == [6, 1, 8, 3, 2, 4, 7, 5]
Swift
24,026,510
329
What is the equivalent of UI_USER_INTERFACE_IDIOM() in Swift to detect between iPhone and iPad? I get an Use of unresolved identifier error when compiling in Swift.
When working with Swift, you can use the enum UIUserInterfaceIdiom, defined as: enum UIUserInterfaceIdiom : Int { case unspecified case phone // iPhone and iPod touch style UI case pad // iPad style UI (also includes macOS Catalyst) } So you can use it as: UIDevice.current.userInterfaceIdiom == .pad UIDevice.current.userInterfaceIdiom == .phone UIDevice.current.userInterfaceIdiom == .unspecified Or with a Switch statement: switch UIDevice.current.userInterfaceIdiom { case .phone: // It's an iPhone case .pad: // It's an iPad (or macOS Catalyst) @unknown default: // Uh, oh! What could it be? } UI_USER_INTERFACE_IDIOM() is an Objective-C macro, which is defined as: #define UI_USER_INTERFACE_IDIOM() \ ([[UIDevice currentDevice] respondsToSelector:@selector(userInterfaceIdiom)] ? \ [[UIDevice currentDevice] userInterfaceIdiom] : \ UIUserInterfaceIdiomPhone) Also, note that even when working with Objective-C, the UI_USER_INTERFACE_IDIOM() macro is only required when targeting iOS 3.2 and below. When deploying to iOS 3.2 and up, you can use [UIDevice userInterfaceIdiom] directly.
Swift
24,059,327
327
I am defining a custom error type with Swift 3 syntax and I want to provide a user-friendly description of the error which is returned by the localizedDescription property of the Error object. How can I do it? public enum MyError: Error { case customError var localizedDescription: String { switch self { case .customError: return NSLocalizedString("A user-friendly description of the error.", comment: "My error") } } } let error: Error = MyError.customError error.localizedDescription // "The operation couldn’t be completed. (MyError error 0.)" Is there a way for the localizedDescription to return my custom error description ("A user-friendly description of the error.")? Note that the error object here is of type Error and not MyError. I can, of course, cast the object to MyError (error as? MyError)?.localizedDescription but is there a way to make it work without casting to my error type?
As described in the Xcode 8 beta 6 release notes, Swift-defined error types can provide localized error descriptions by adopting the new LocalizedError protocol. In your case: public enum MyError: Error { case customError } extension MyError: LocalizedError { public var errorDescription: String? { switch self { case .customError: return NSLocalizedString("A user-friendly description of the error.", comment: "My error") } } } let error: Error = MyError.customError print(error.localizedDescription) // A user-friendly description of the error. You can provide even more information if the error is converted to NSError (which is always possible): extension MyError : LocalizedError { public var errorDescription: String? { switch self { case .customError: return NSLocalizedString("I failed.", comment: "") } } public var failureReason: String? { switch self { case .customError: return NSLocalizedString("I don't know why.", comment: "") } } public var recoverySuggestion: String? { switch self { case .customError: return NSLocalizedString("Switch it off and on again.", comment: "") } } } let error = MyError.customError as NSError print(error.localizedDescription) // I failed. print(error.localizedFailureReason) // Optional("I don\'t know why.") print(error.localizedRecoverySuggestion) // Optional("Switch it off and on again.") By adopting the CustomNSError protocol the error can provide a userInfo dictionary (and also a domain and code). Example: extension MyError: CustomNSError { public static var errorDomain: String { return "myDomain" } public var errorCode: Int { switch self { case .customError: return 999 } } public var errorUserInfo: [String : Any] { switch self { case .customError: return [ "line": 13] } } } let error = MyError.customError as NSError if let line = error.userInfo["line"] as? Int { print("Error in line", line) // Error in line 13 } print(error.code) // 999 print(error.domain) // myDomain
Swift
39,176,196
327
I have an array that is made up of AnyObject. I want to iterate over it, and find all elements that are array instances. How can I check if an object is of a given type in Swift?
If you want to check against a specific type you can do the following: if let stringArray = obj as? [String] { // obj is a string array. Do something with stringArray } else { // obj is not a string array } You can use "as!" and that will throw a runtime error if obj is not of type [String] let stringArray = obj as! [String] You can also check one element at a time: let items : [Any] = ["Hello", "World"] for obj in items { if let str = obj as? String { // obj is a String. Do something with str } else { // obj is not a String } }
Swift
24,091,882
326
How can I unset/remove an element from an array in Apple's new language Swift? Here's some code: let animals = ["cats", "dogs", "chimps", "moose"] How could the element animals[2] be removed from the array?
The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g: var animals = ["cats", "dogs", "chimps", "moose"] animals.remove(at: 2) //["cats", "dogs", "moose"] A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g: let pets = animals.filter { $0 != "chimps" }
Swift
24,051,633
324
I am building an RSS reader using Swift and need to implement pull-to-reload functionality. Here is how I am trying to do it. class FirstViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { @IBOutlet var refresh: UIScreenEdgePanGestureRecognizer @IBOutlet var newsCollect: UITableView var activityIndicator:UIActivityIndicatorView? = nil override func viewDidLoad() { super.viewDidLoad() self.newsCollect.scrollEnabled = true // Do any additional setup after loading the view, typically from a nib. if nCollect.news.count <= 2{ self.collectNews() } else{ self.removeActivityIndicator() } view.addGestureRecognizer(refresh) } @IBAction func reload(sender: UIScreenEdgePanGestureRecognizer) { nCollect.news = News[]() return newsCollect.reloadData() } I am getting : Property 'self.refresh' not initialized at super.init call Please help me to understand the behavior of Gesture recognizers. A working sample code will be a great help. Thanks.
Pull to refresh is built in iOS. You could do this in swift like let refreshControl = UIRefreshControl() override func viewDidLoad() { super.viewDidLoad() refreshControl.attributedTitle = NSAttributedString(string: "Pull to refresh") refreshControl.addTarget(self, action: #selector(self.refresh(_:)), for: .valueChanged) tableView.addSubview(refreshControl) // not required when using UITableViewController } @objc func refresh(_ sender: AnyObject) { // Code to refresh table view } At some point you could end refreshing. refreshControl.endRefreshing()
Swift
24,475,792
321
Been encountering this error a lot in my OS X using swift: "This application is modifying the autolayout engine from a background thread, which can lead to engine corruption and weird crashes. This will cause an exception in a future release." I have a my NSWindow and I'm swapping in views to the contentView of the window. I get the error when I try and do a NSApp.beginSheet on the window, or when I add a subview to the window. Tried disabling autoresize stuff, and I don't have anything using auto layout. Any thoughts? Sometimes it's fine and nothing happens, other times it totally breaks my UI and nothing loads
It needs to be placed inside a different thread that allows the UI to update as soon as execution of thread function completes: Modern Swift: DispatchQueue.main.async { // Update UI } Older versions of Swift, pre Swift 3. dispatch_async(dispatch_get_main_queue(){ // code here }) Objective-C: dispatch_async(dispatch_get_main_queue(), ^{ // code here });
Swift
28,302,019
319
Trying to fill an array with strings from the keys in a dictionary in swift. var componentArray: [String] let dict = NSDictionary(contentsOfFile: NSBundle.mainBundle().pathForResource("Components", ofType: "plist")!) componentArray = dict.allKeys This returns an error of: 'AnyObject' not identical to string Also tried componentArray = dict.allKeys as String but get: 'String' is not convertible to [String]
Swift 3 & Swift 4 componentArray = Array(dict.keys) // for Dictionary componentArray = dict.allKeys // for NSDictionary
Swift
26,386,093
318
Is it possible to reduce the gap between text, when put in multiple lines in a UILabel? We can set the frame, font size and number of lines. I want to reduce the gap between the two lines in that label.
In Xcode 6 you can do this in the storyboard:
Swift
5,494,498
316
Swift has a property declaration syntax very similar to C#'s: var foo: Int { get { return getFoo() } set { setFoo(newValue) } } However, it also has willSet and didSet actions. These are called before and after the setter is called, respectively. What is their purpose, considering that you could just have the same code inside the setter?
The point seems to be that sometimes, you need a property that has automatic storage and some behavior, for instance to notify other objects that the property just changed. When all you have is get/set, you need another field to hold the value. With willSet and didSet, you can take action when the value is modified without needing another field. For instance, in that example: class Foo { var myProperty: Int = 0 { didSet { print("The value of myProperty changed from \(oldValue) to \(myProperty)") } } } myProperty prints its old and new value every time it is modified. With just getters and setters, I would need this instead: class Foo { var myPropertyValue: Int = 0 var myProperty: Int { get { return myPropertyValue } set { print("The value of myProperty changed from \(myPropertyValue) to \(newValue)") myPropertyValue = newValue } } } So willSet and didSet represent an economy of a couple of lines, and less noise in the field list.
Swift
24,006,234
316
When I try to check for an internet connection on my iPhone I get a bunch of errors. Can anyone help me to fix this? The code: import Foundation import SystemConfiguration public class Reachability { class func isConnectedToNetwork() -> Bool { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress)) zeroAddress.sin_family = sa_family_t(AF_INET) let defaultRouteReachability = withUnsafePointer(&zeroAddress) { SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0)) } var flags: SCNetworkReachabilityFlags = 0 if SCNetworkReachabilityGetFlags(defaultRouteReachability, &flags) == 0 { return false } let isReachable = (flags & UInt32(kSCNetworkFlagsReachable)) != 0 let needsConnection = (flags & UInt32(kSCNetworkFlagsConnectionRequired)) != 0 return (isReachable && !needsConnection) ? true : false } } The errors with the code: If it is unreadable, error 1 says: 'Int' is not convertible to 'SCNetworkReachabilityFlags' Error 2 & 3: Could not find an overload for 'init' that accepts the supplied arguments
To solve the 4G issue mentioned in the comments I have used @AshleyMills reachability implementation as a reference and rewritten Reachability for Swift 3.1: updated: Xcode 10.1 • Swift 4 or later Reachability.swift file import Foundation import SystemConfiguration class Reachability { var hostname: String? var isRunning = false var isReachableOnWWAN: Bool var reachability: SCNetworkReachability? var reachabilityFlags = SCNetworkReachabilityFlags() let reachabilitySerialQueue = DispatchQueue(label: "ReachabilityQueue") init(hostname: String) throws { guard let reachability = SCNetworkReachabilityCreateWithName(nil, hostname) else { throw Network.Error.failedToCreateWith(hostname) } self.reachability = reachability self.hostname = hostname isReachableOnWWAN = true try start() } init() throws { var zeroAddress = sockaddr_in() zeroAddress.sin_len = UInt8(MemoryLayout<sockaddr_in>.size) zeroAddress.sin_family = sa_family_t(AF_INET) guard let reachability = withUnsafePointer(to: &zeroAddress, { $0.withMemoryRebound(to: sockaddr.self, capacity: 1) { SCNetworkReachabilityCreateWithAddress(nil, $0) } }) else { throw Network.Error.failedToInitializeWith(zeroAddress) } self.reachability = reachability isReachableOnWWAN = true try start() } var status: Network.Status { return !isConnectedToNetwork ? .unreachable : isReachableViaWiFi ? .wifi : isRunningOnDevice ? .wwan : .unreachable } var isRunningOnDevice: Bool = { #if targetEnvironment(simulator) return false #else return true #endif }() deinit { stop() } } extension Reachability { func start() throws { guard let reachability = reachability, !isRunning else { return } var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil) context.info = Unmanaged<Reachability>.passUnretained(self).toOpaque() guard SCNetworkReachabilitySetCallback(reachability, callout, &context) else { stop() throw Network.Error.failedToSetCallout } guard SCNetworkReachabilitySetDispatchQueue(reachability, reachabilitySerialQueue) else { stop() throw Network.Error.failedToSetDispatchQueue } reachabilitySerialQueue.async { self.flagsChanged() } isRunning = true } func stop() { defer { isRunning = false } guard let reachability = reachability else { return } SCNetworkReachabilitySetCallback(reachability, nil, nil) SCNetworkReachabilitySetDispatchQueue(reachability, nil) self.reachability = nil } var isConnectedToNetwork: Bool { return isReachable && !isConnectionRequiredAndTransientConnection && !(isRunningOnDevice && isWWAN && !isReachableOnWWAN) } var isReachableViaWiFi: Bool { return isReachable && isRunningOnDevice && !isWWAN } /// Flags that indicate the reachability of a network node name or address, including whether a connection is required, and whether some user intervention might be required when establishing a connection. var flags: SCNetworkReachabilityFlags? { guard let reachability = reachability else { return nil } var flags = SCNetworkReachabilityFlags() return withUnsafeMutablePointer(to: &flags) { SCNetworkReachabilityGetFlags(reachability, UnsafeMutablePointer($0)) } ? flags : nil } /// compares the current flags with the previous flags and if changed posts a flagsChanged notification func flagsChanged() { guard let flags = flags, flags != reachabilityFlags else { return } reachabilityFlags = flags NotificationCenter.default.post(name: .flagsChanged, object: self) } /// The specified node name or address can be reached via a transient connection, such as PPP. var transientConnection: Bool { return flags?.contains(.transientConnection) == true } /// The specified node name or address can be reached using the current network configuration. var isReachable: Bool { return flags?.contains(.reachable) == true } /// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set, the kSCNetworkReachabilityFlagsConnectionOnTraffic flag, kSCNetworkReachabilityFlagsConnectionOnDemand flag, or kSCNetworkReachabilityFlagsIsWWAN flag is also typically set to indicate the type of connection required. If the user must manually make the connection, the kSCNetworkReachabilityFlagsInterventionRequired flag is also set. var connectionRequired: Bool { return flags?.contains(.connectionRequired) == true } /// The specified node name or address can be reached using the current network configuration, but a connection must first be established. Any traffic directed to the specified name or address will initiate the connection. var connectionOnTraffic: Bool { return flags?.contains(.connectionOnTraffic) == true } /// The specified node name or address can be reached using the current network configuration, but a connection must first be established. var interventionRequired: Bool { return flags?.contains(.interventionRequired) == true } /// The specified node name or address can be reached using the current network configuration, but a connection must first be established. The connection will be established "On Demand" by the CFSocketStream programming interface (see CFStream Socket Additions for information on this). Other functions will not establish the connection. var connectionOnDemand: Bool { return flags?.contains(.connectionOnDemand) == true } /// The specified node name or address is one that is associated with a network interface on the current system. var isLocalAddress: Bool { return flags?.contains(.isLocalAddress) == true } /// Network traffic to the specified node name or address will not go through a gateway, but is routed directly to one of the interfaces in the system. var isDirect: Bool { return flags?.contains(.isDirect) == true } /// The specified node name or address can be reached via a cellular connection, such as EDGE or GPRS. var isWWAN: Bool { return flags?.contains(.isWWAN) == true } /// The specified node name or address can be reached using the current network configuration, but a connection must first be established. If this flag is set /// The specified node name or address can be reached via a transient connection, such as PPP. var isConnectionRequiredAndTransientConnection: Bool { return (flags?.intersection([.connectionRequired, .transientConnection]) == [.connectionRequired, .transientConnection]) == true } } func callout(reachability: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) { guard let info = info else { return } DispatchQueue.main.async { Unmanaged<Reachability> .fromOpaque(info) .takeUnretainedValue() .flagsChanged() } } extension Notification.Name { static let flagsChanged = Notification.Name("FlagsChanged") } struct Network { static var reachability: Reachability! enum Status: String { case unreachable, wifi, wwan } enum Error: Swift.Error { case failedToSetCallout case failedToSetDispatchQueue case failedToCreateWith(String) case failedToInitializeWith(sockaddr_in) } } Usage Initialize it in your AppDelegate.swift didFinishLaunchingWithOptions method and handle any errors that might occur: import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { do { try Network.reachability = Reachability(hostname: "www.google.com") } catch { switch error as? Network.Error { case let .failedToCreateWith(hostname)?: print("Network error:\nFailed to create reachability object With host named:", hostname) case let .failedToInitializeWith(address)?: print("Network error:\nFailed to initialize reachability object With address:", address) case .failedToSetCallout?: print("Network error:\nFailed to set callout") case .failedToSetDispatchQueue?: print("Network error:\nFailed to set DispatchQueue") case .none: print(error) } } return true } } And a view controller sample: import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() NotificationCenter.default .addObserver(self, selector: #selector(statusManager), name: .flagsChanged, object: nil) updateUserInterface() } func updateUserInterface() { switch Network.reachability.status { case .unreachable: view.backgroundColor = .red case .wwan: view.backgroundColor = .yellow case .wifi: view.backgroundColor = .green } print("Reachability Summary") print("Status:", Network.reachability.status) print("HostName:", Network.reachability.hostname ?? "nil") print("Reachable:", Network.reachability.isReachable) print("Wifi:", Network.reachability.isReachableViaWiFi) } @objc func statusManager(_ notification: Notification) { updateUserInterface() } } Sample Project
Swift
30,743,408
316
I am using a Picker View to allow the user to choose the colour theme for the entire app. I am planning on changing the colour of the navigation bar, background and possibly the tab bar (if that is possible). I've been researching how to do this but can't find any Swift examples. Could anyone please give me an example of the code I would need to use to change the navigation bar colour and navigation bar text colour? The Picker View is set up, I'm just looking for the code to change the UI colours.
Navigation Bar: navigationController?.navigationBar.barTintColor = UIColor.green Replace greenColor with whatever UIColor you want, you can use an RGB too if you prefer. Navigation Bar Text: navigationController?.navigationBar.titleTextAttributes = [.foregroundColor: UIColor.orange] Replace orangeColor with whatever color you like. Tab Bar: tabBarController?.tabBar.barTintColor = UIColor.brown Tab Bar Text: tabBarController?.tabBar.tintColor = UIColor.yellow On the last two, replace brownColor and yellowColor with the color of your choice.
Swift
24,687,238
315
I have several Docker images that I want to use with Minikube. I don't want to first have to upload and then download the same image instead of just using the local image directly. How do I do this? Stuff I tried: 1. I tried running these commands (separately, deleting the instances of Minikube both times and starting fresh) kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 kubectl run hdfs --image=fluxcapacitor/hdfs:latest --port=8989 imagePullPolicy=Never Output: NAME READY STATUS RESTARTS AGE hdfs-2425930030-q0sdl 0/1 ContainerCreating 0 10m It just gets stuck on some status but never reaches the ready state. 2. I tried creating a registry and then putting images into it, but that didn't work either. I might've done that incorrectly but I can't find proper instructions to do this task. Please provide instructions to use local Docker images in a local Kubernetes instance. OS: Ubuntu 16.04 (Xenial Xerus) Docker: Docker version 1.13.1, build 092cba3 Kubernetes: Client Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.3", GitCommit:"029c3a408176b55c30846f0faedf56aae5992e9b", GitTreeState:"clean", BuildDate:"2017-02-15T06:40:50Z", GoVersion:"go1.7.4", Compiler:"gc", Platform:"linux/amd64"} Server Version: version.Info{Major:"1", Minor:"5", GitVersion:"v1.5.2", GitCommit:"08e099554f3c31f6e6f07b448ab3ed78d0520507", GitTreeState:"clean", BuildDate:"1970-01-01T00:00:00Z", GoVersion:"go1.7.1", Compiler:"gc", Platform:"linux/amd64"} What is a solution that uses docker-compose to do this? Images loaded in eval $(minikube docker-env): REPOSITORY TAG IMAGE ID CREATED SIZE fluxcapacitor/jupyterhub latest e5175fb26522 4 weeks ago 9.59 GB fluxcapacitor/zeppelin latest fe4bc823e57d 4 weeks ago 4.12 GB fluxcapacitor/prediction-pmml latest cae5b2d9835b 4 weeks ago 973 MB fluxcapacitor/scheduler-airflow latest 95adfd56f656 4 weeks ago 8.89 GB fluxcapacitor/loadtest latest 6a777ab6167c 5 weeks ago 899 MB fluxcapacitor/hdfs latest 00fa0ed0064b 6 weeks ago 1.16 GB fluxcapacitor/sql-mysql latest 804137671a8c 7 weeks ago 679 MB fluxcapacitor/metastore-1.2.1 latest ea7ce8c5048f 7 weeks ago 1.35 GB fluxcapacitor/cassandra latest 3cb5ff117283 7 weeks ago 953 MB fluxcapacitor/apachespark-worker-2.0.1 latest 14ee3e4e337c 7 weeks ago 3.74 GB fluxcapacitor/apachespark-master-2.0.1 latest fe60b42d54e5 7 weeks ago 3.72 GB fluxcapacitor/package-java-openjdk-1.8 latest 1db08965289d 7 weeks ago 841 MB gcr.io/google_containers/kubernetes-dashboard-amd64 v1.5.1 1180413103fd 7 weeks ago 104 MB fluxcapacitor/stream-kafka-0.10 latest f67750239f4d 2 months ago 1.14 GB fluxcapacitor/pipeline latest f6afd6c5745b 2 months ago 11.2 GB gcr.io/google-containers/kube-addon-manager v6.1 59e1315aa5ff 3 months ago 59.4 MB gcr.io/google_containers/kubedns-amd64 1.9 26cf1ed9b144 3 months ago 47 MB gcr.io/google_containers/kube-dnsmasq-amd64 1.4 3ec65756a89b 5 months ago 5.13 MB gcr.io/google_containers/exechealthz-amd64 1.2 93a43bfb39bf 5 months ago 8.37 MB gcr.io/google_containers/pause-amd64
As the handbook describes, you can reuse the Docker daemon from Minikube with eval $(minikube docker-env). So to use an image without uploading it, you can follow these steps: Set the environment variables with eval $(minikube docker-env) Build the image with the Docker daemon of Minikube (e.g., docker build -t my-image .) Set the image in the pod specification like the build tag (e.g., my-image) Set the imagePullPolicy to Never, otherwise Kubernetes will try to download the image. Important note: You have to run eval $(minikube docker-env) on each terminal you want to use, since it only sets the environment variables for the current shell session.
Kubernetes
42,564,058
657
I tried to delete a ReplicationController with 12 pods and I could see that some of the pods are stuck in Terminating status. My Kubernetes cluster consists of one control plane node and three worker nodes installed on Ubuntu virtual machines. What could be the reason for this issue? NAME READY STATUS RESTARTS AGE pod-186o2 1/1 Terminating 0 2h pod-4b6qc 1/1 Terminating 0 2h pod-8xl86 1/1 Terminating 0 1h pod-d6htc 1/1 Terminating 0 1h pod-vlzov 1/1 Terminating 0 1h
You can use following command to delete the POD forcefully. kubectl delete pod <PODNAME> --grace-period=0 --force --namespace <NAMESPACE>
Kubernetes
35,453,792
549
Question 1 - I'm reading the documentation and I'm slightly confused with the wording. It says: ClusterIP: Exposes the service on a cluster-internal IP. Choosing this value makes the service only reachable from within the cluster. This is the default ServiceType NodePort: Exposes the service on each Node’s IP at a static port (the NodePort). A ClusterIP service, to which the NodePort service will route, is automatically created. You’ll be able to contact the NodePort service, from outside the cluster, by requesting <NodeIP>:<NodePort>. LoadBalancer: Exposes the service externally using a cloud provider’s load balancer. NodePort and ClusterIP services, to which the external load balancer will route, are automatically created. Does the NodePort service type still use the ClusterIP but just at a different port, which is open to external clients? So in this case is <NodeIP>:<NodePort> the same as <ClusterIP>:<NodePort>? Or is the NodeIP actually the IP found when you run kubectl get nodes and not the virtual IP used for the ClusterIP service type? Question 2 - Also in the diagram from the link below: Is there any particular reason why the Client is inside the Node? I assumed it would need to be inside a Clusterin the case of a ClusterIP service type? If the same diagram was drawn for NodePort, would it be valid to draw the client completely outside both the Node andCluster or am I completely missing the point?
A ClusterIP exposes the following: spec.clusterIp:spec.ports[*].port You can only access this service while inside the cluster. It is accessible from its spec.clusterIp port. If a spec.ports[*].targetPort is set it will route from the port to the targetPort. The CLUSTER-IP you get when calling kubectl get services is the IP assigned to this service within the cluster internally. A NodePort exposes the following: <NodeIP>:spec.ports[*].nodePort spec.clusterIp:spec.ports[*].port If you access this service on a nodePort from the node's external IP, it will route the request to spec.clusterIp:spec.ports[*].port, which will in turn route it to your spec.ports[*].targetPort, if set. This service can also be accessed in the same way as ClusterIP. Your NodeIPs are the external IP addresses of the nodes. You cannot access your service from spec.clusterIp:spec.ports[*].nodePort. A LoadBalancer exposes the following: spec.loadBalancerIp:spec.ports[*].port <NodeIP>:spec.ports[*].nodePort spec.clusterIp:spec.ports[*].port You can access this service from your load balancer's IP address, which routes your request to a nodePort, which in turn routes the request to the clusterIP port. You can access this service as you would a NodePort or a ClusterIP service as well.
Kubernetes
41,509,439
536
What I understood by the documentation is that: kubectl create Creates a new k8s resource in the cluster kubectl replace Updates a resource in the live cluster kubectl apply If I want to do create + replace (Reference) My questions are Why are there three operations for doing the same task in a cluster? What are the use cases for these operations? How do they differ from each other under the hood?
Those are two different approaches: Imperative Management kubectl create is what we call Imperative Management. On this approach you tell the Kubernetes API what you want to create, replace or delete, not how you want your K8s cluster world to look like. Declarative Management kubectl apply is part of the Declarative Management approach, where changes that you may have applied to a live object (i.e. through scale) are "maintained" even if you apply other changes to the object. You can read more about imperative and declarative management in the Kubernetes Object Management documentation. In laymans They do different things. If the resource exists, kubectl create will error out and kubectl apply will not error out.
Kubernetes
47,369,351
475
I am quite confused about the roles of Ingress and Load Balancer in Kubernetes. As far as I understand Ingress is used to map incoming traffic from the internet to the services running in the cluster. The role of load balancer is to forward traffic to a host. In that regard how does ingress differ from load balancer? Also what is the concept of load balancer inside kubernetes as compared to Amazon ELB and ALB?
Load Balancer: A kubernetes LoadBalancer service is a service that points to external load balancers that are NOT in your kubernetes cluster, but exist elsewhere. They can work with your pods, assuming that your pods are externally routable. Google and AWS provide this capability natively. In terms of Amazon, this maps directly with ELB and kubernetes when running in AWS can automatically provision and configure an ELB instance for each LoadBalancer service deployed. Ingress: An ingress is really just a set of rules to pass to a controller that is listening for them. You can deploy a bunch of ingress rules, but nothing will happen unless you have a controller that can process them. A LoadBalancer service could listen for ingress rules, if it is configured to do so. You can also create a NodePort service, which has an externally routable IP outside the cluster, but points to a pod that exists within your cluster. This could be an Ingress Controller. An Ingress Controller is simply a pod that is configured to interpret ingress rules. One of the most popular ingress controllers supported by kubernetes is nginx. In terms of Amazon, ALB can be used as an ingress controller. For an example, this nginx controller is able to ingest ingress rules you have defined and translate them to an nginx.conf file that it loads and starts in its pod. Let's for instance say you defined an ingress as follows: apiVersion: extensions/v1beta1 kind: Ingress metadata: annotations: ingress.kubernetes.io/rewrite-target: / name: web-ingress spec: rules: - host: kubernetes.foo.bar http: paths: - backend: serviceName: appsvc servicePort: 80 path: /app If you then inspect your nginx controller pod you'll see the following rule defined in /etc/nginx.conf: server { server_name kubernetes.foo.bar; listen 80; listen [::]:80; set $proxy_upstream_name "-"; location ~* ^/web2\/?(?<baseuri>.*) { set $proxy_upstream_name "apps-web2svc-8080"; port_in_redirect off; client_max_body_size "1m"; proxy_set_header Host $best_http_host; # Pass the extracted client certificate to the backend # Allow websocket connections proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection $connection_upgrade; proxy_set_header X-Real-IP $the_real_ip; proxy_set_header X-Forwarded-For $the_x_forwarded_for; proxy_set_header X-Forwarded-Host $best_http_host; proxy_set_header X-Forwarded-Port $pass_port; proxy_set_header X-Forwarded-Proto $pass_access_scheme; proxy_set_header X-Original-URI $request_uri; proxy_set_header X-Scheme $pass_access_scheme; # mitigate HTTPoxy Vulnerability # https://www.nginx.com/blog/mitigating-the-httpoxy-vulnerability-with-nginx/ proxy_set_header Proxy ""; # Custom headers proxy_connect_timeout 5s; proxy_send_timeout 60s; proxy_read_timeout 60s; proxy_redirect off; proxy_buffering off; proxy_buffer_size "4k"; proxy_buffers 4 "4k"; proxy_http_version 1.1; proxy_cookie_domain off; proxy_cookie_path off; rewrite /app/(.*) /$1 break; rewrite /app / break; proxy_pass http://apps-appsvc-8080; } Nginx has just created a rule to route http://kubernetes.foo.bar/app to point to the service appsvc in your cluster. Here is an example of how to implement a kubernetes cluster with an nginx ingress controller.
Kubernetes
45,079,988
458
While diving into Docker, Google Cloud and Kubernetes, and without clearly understanding all three of them yet, it seems to me these products are overlapping, yet they're not compatible. For example, a docker-compose.yml file needs to be re-written so an app can be deployed to Kubernetes. Could someone provide a high-level, rough description of where Docker, Docker Compose, Docker Cloud, and Kubernetes overlap and where one is dependent on the other?
Containers: Containers are at the core of the other technologies listed here Docker: Docker is a popular implementation of the technology that allows applications to be bundled into a container. docker is a command-line tool to manage images, containers, volumes, and networks Docker Compose Docker Compose is the declarative version of the docker cli It can start one or more containers It can create one or more networks and attach containers to them It can create one or more volumes and configure containers to mount them All of this is for use on a single host Docker Classic Swarm Docker swarm has been abandoned by Docker Inc. and is not being actively maintained or supported. Docker Swarm is for running and connecting containers on multiple hosts. Docker Swarm is a container cluster management and orchestration tool. It manages containers running on multiple hosts and does things like scaling, starting a new container when one crashes, networking containers ... The Docker Swarm file named stack file is very similar to a Docker Compose file The only comparison between Kubernetes and Compose is at the most trivial and unimportant level: they both run containers, but this says nothing to help one understand what the two tools are and where they are useful. They are both useful for different things Kubernetes Kubernetes (K8S) is a distributed container orchestration tool initially created by Google It was open-sourced in 2014 and handed over to the Cloud Native Computing Foundation (CNCF) the following year The CNCF is an industry body with hundreds of members drawn from the majority of large cloud, software and hardware companies At the time of writing (late 2021) there are nearly a thousand K8S related projects split into around twenty classes with a total of over $21 billion dollars in funding Kubernetes (2021) is the most popular distributed system orchestrator in the world with 88% adoption Because of its near ubiquity, K8S has become the most popular contemporary platform for innovative system development in 2021 Kubernetes is a competitor (more or less) to Docker swarm but does more stuff than docker swarm i.e a popular choice.
Kubernetes
47,536,536
448
What exactly is the difference between Apache's Mesos and Google's Kubernetes? I understand both are server cluster management software. Can anyone elaborate where the main differences are - when would which framework be preferred? Why would you want to use Kubernetes on top of Mesosphere?
Kubernetes is an open source project that brings 'Google style' cluster management capabilities to the world of virtual machines, or 'on the metal' scenarios. It works very well with modern operating system environments (like CoreOS or Red Hat Atomic) that offer up lightweight computing 'nodes' that are managed for you. It is written in Golang and is lightweight, modular, portable and extensible. We (the Kubernetes team) are working with a number of different technology companies (including Mesosphere who curate the Mesos open source project) to establish Kubernetes as the standard way to interact with computing clusters. The idea is to reproduce the patterns that we see people needing to build cluster applications based on our experience at Google. Some of these concepts include: pods — a way to group containers together replication controllers — a way to handle the lifecycle of containers labels — a way to find and query containers, and services — a set of containers performing a common function. So with Kubernetes alone you will have something that is simple, easy to get up-and-running, portable and extensible that adds 'cluster' as a noun to the things that you manage in the lightest weight manner possible. Run an application on a cluster, and stop worrying about an individual machine. In this case, cluster is a flexible resource just like a VM. It is a logical computing unit. Turn it up, use it, resize it, turn it down quickly and easily. With Mesos, there is a fair amount of overlap in terms of the basic vision, but the products are at quite different points in their lifecycle and have different sweet spots. Mesos is a distributed systems kernel that stitches together a lot of different machines into a logical computer. It was born for a world where you own a lot of physical resources to create a big static computing cluster. The great thing about it is that lots of modern scalable data processing application run well on Mesos (Hadoop, Kafka, Spark) and it is nice because you can run them all on the same basic resource pool, along with your new age container packaged apps. It is somewhat more heavy weight than the Kubernetes project, but is getting easier and easier to manage thanks to the work of folks like Mesosphere. Now what gets really interesting is that Mesos is currently being adapted to add a lot of the Kubernetes concepts and to support the Kubernetes API. So it will be a gateway to getting more capabilities for your Kubernetes app (high availability master, more advanced scheduling semantics, ability to scale to a very large number of nodes) if you need them, and is well suited to run production workloads (Kubernetes is still in an alpha state). When asked, I tend to say: Kubernetes is a great place to start if you are new to the clustering world; it is the quickest, easiest and lightest way to kick the tires and start experimenting with cluster oriented development. It offers a very high level of portability since it is being supported by a lot of different providers (Microsoft, IBM, Red Hat, CoreOs, MesoSphere, VMWare, etc). If you have existing workloads (Hadoop, Spark, Kafka, etc), Mesos gives you a framework that let's you interleave those workloads with each other, and mix in a some of the new stuff including Kubernetes apps. Mesos gives you an escape valve if you need capabilities that are not yet implemented by the community in the Kubernetes framework.
Kubernetes
26,705,201
426
I have been creating pods with type:deployment but I see that some documentation uses type:pod, more specifically the documentation for multi-container pods: apiVersion: v1 kind: Pod metadata: name: "" labels: name: "" namespace: "" annotations: [] generateName: "" spec: ? "// See 'The spec schema' for details." : ~ But to create pods I can just use a deployment type: apiVersion: extensions/v1beta1 kind: Deployment metadata: name: "" spec: replicas: 3 template: metadata: labels: app: "" spec: containers: etc I noticed the pod documentation says: The create command can be used to create a pod directly, or it can create a pod or pods through a Deployment. It is highly recommended that you use a Deployment to create your pods. It watches for failed pods and will start up new pods as required to maintain the specified number. If you don’t want a Deployment to monitor your pod (e.g. your pod is writing non-persistent data which won’t survive a restart, or your pod is intended to be very short-lived), you can create a pod directly with the create command. Note: We recommend using a Deployment to create pods. You should use the instructions below only if you don’t want to create a Deployment. But this raises the question of what kind:pod is good for? Can you somehow reference pods in a deployment? I didn't see a way. It looks like what you get with pods is some extra metadata but none of the deployment options such as replica or a restart policy. What good is a pod that doesn't persist data, survives a restart? I think I'd be able to create a multi-container pod with a deployment as well.
Radek's answer is very good, but I would like to pitch in from my experience, you will almost never use an object with the kind pod, because that doesn't make any sense in practice. Because you need a deployment object - or other Kubernetes API objects like a replication controller or replicaset - that needs to keep the replicas (pods) alive (that's kind of the point of using kubernetes). What you will use in practice for a typical application are: Deployment object (where you will specify your apps container/containers) that will host your app's container with some other specifications. Service object (that is like a grouping object and gives it a so-called virtual IP (cluster IP) for the pods that have a certain label - and those pods are basically the app containers that you deployed with the former deployment object). You need to have the service object because the pods from the deployment object can be killed, scaled up and down, and you can't rely on their IP addresses because they will not be persistent. So you need an object like a service, that gives those pods a stable IP. Just wanted to give you some context around pods, so you know how things work together. Hope that clears a few things for you, not long ago I was in your shoes :)
Kubernetes
41,325,087
403
Upon looking at the docs, there is an API call to delete a single pod, but is there a way to delete all pods in all namespaces?
There is no command to do exactly what you asked. Here are some close matches. Be careful before running any of these commands. Make sure you are connected to the right cluster, if you use multiple clusters. Consider running. kubectl config view first. You can delete all the pods in a single namespace with this command: kubectl delete --all pods --namespace=foo You can also delete all deployments in namespace which will delete all pods attached with the deployments corresponding to the namespace kubectl delete --all deployments --namespace=foo You can delete all namespaces and every object in every namespace (but not un-namespaced objects, like nodes and some events) with this command: kubectl delete --all namespaces However, the latter command is probably not something you want to do, since it will delete things in the kube-system namespace, which will make your cluster not usable. This command will delete all the namespaces except kube-system, which might be useful: for each in $(kubectl get ns -o jsonpath="{.items[*].metadata.name}" | grep -v kube-system); do kubectl delete ns $each done
Kubernetes
33,509,194
374
I have the following replication controller in Kubernetes on GKE: apiVersion: v1 kind: ReplicationController metadata: name: myapp labels: app: myapp spec: replicas: 2 selector: app: myapp deployment: initial template: metadata: labels: app: myapp deployment: initial spec: containers: - name: myapp image: myregistry.com/myapp:5c3dda6b ports: - containerPort: 80 imagePullPolicy: Always imagePullSecrets: - name: myregistry.com-registry-key Now, if I say kubectl rolling-update myapp --image=us.gcr.io/project-107012/myapp:5c3dda6b the rolling update is performed, but no re-pull. Why?
Kubernetes will pull upon Pod creation if either (see updating-images doc): Using images tagged :latest imagePullPolicy: Always is specified This is great if you want to always pull. But what if you want to do it on demand: For example, if you want to use some-public-image:latest but only want to pull a newer version manually when you ask for it. You can currently: Set imagePullPolicy to IfNotPresent or Never and pre-pull: Pull manually images on each cluster node so the latest is cached, then do a kubectl rolling-update or similar to restart Pods (ugly easily broken hack!) Temporarily change imagePullPolicy, do a kubectl apply, restart the pod (e.g. kubectl rolling-update), revert imagePullPolicy, redo a kubectl apply (ugly!) Pull and push some-public-image:latest to your private repository and do a kubectl rolling-update (heavy!) No good solution for on-demand pull. If that changes, please comment; I'll update this answer.
Kubernetes
33,112,789
344
In the Kubernetes/Docker ecosystem there is a convention of using /healthz as a health-check endpoint for applications. Where does the name 'healthz' come from, and are there any particular semantics associated with that name?
It historically comes from Google’s internal practices. They're called "z-pages". The reason it ends with z is to reduce collisions with actual application endpoints with the same name (like /status). See this talk for more: https://vimeo.com/173610242 Similar endpoints (at least inside Google) are /varz, /statusz, /rpcz. Services developed at Google automatically get these endpoints to export their health and metrics and there are tools that collect the exposed metrics/statuses from all the deployed services. Open source tools like Prometheus implement this pattern (since original authors of Prometheus are also ex-Googlers) by coming to a well-known endpoint to collect metrics from your application. Similarly OpenCensus allows you to expose z-pages from your app (ideally on a different port) to diagnose problems.
Kubernetes
43,380,939
337
I am trying to deploy nginx on kubernetes, kubernetes version is v1.5.2, I have deployed nginx with 3 replica, YAML file is below, apiVersion: extensions/v1beta1 kind: Deployment metadata: name: deployment-example spec: replicas: 3 revisionHistoryLimit: 2 template: metadata: labels: app: nginx spec: containers: - name: nginx image: nginx:1.10 ports: - containerPort: 80 and now I want to expose its port 80 on port 30062 of node, for that I created a service below, kind: Service apiVersion: v1 metadata: name: nginx-ils-service spec: ports: - name: http port: 80 nodePort: 30062 selector: app: nginx type: LoadBalancer this service is working good as it should be, but it is showing as pending not only on kubernetes dashboard also on terminal.
It looks like you are using a custom Kubernetes Cluster (using minikube, kubeadm or the like). In this case, there is no LoadBalancer integrated (unlike AWS or Google Cloud). With this default setup, you can only use NodePort or an Ingress Controller. With the Ingress Controller you can setup a domain name which maps to your pod; you don't need to give your Service the LoadBalancer type if you use an Ingress Controller.
Kubernetes
44,110,876
323
Running kubectl logs shows me the stderr/stdout of one Kubernetes container. How can I get the aggregated stderr/stdout of a set of pods, preferably those created by a certain replication controller?
You can use labels kubectl logs -l app=elasticsearch And you'd probably want to specify --all-containers --ignore-errors in order to: Include logs from pods with multiple containers Continue to next pod on fatal error (e.g. logs could not be retrieved)
Kubernetes
33,069,736
320
A Kubernetes Service can have a targetPort and port in the service definition: kind: Service apiVersion: v1 metadata: name: my-service spec: selector: app: MyApp ports: - protocol: TCP port: 80 targetPort: 9376 What is the difference between the port and targetPort?
Service: This directs the traffic to a pod. TargetPort: This is the actual port on which your application is running inside the container. Port: Some times your application inside container serves different services on a different port. Example: The actual application can run 8080 and health checks for this application can run on 8089 port of the container. So if you hit the service without port it doesn't know to which port of the container it should redirect the request. Service needs to have a mapping so that it can hit the specific port of the container. kind: Service apiVersion: v1 metadata: name: my-service spec: selector: app: MyApp ports: - name: http nodePort: 30475 port: 8089 protocol: TCP targetPort: 8080 - name: metrics nodePort: 31261 port: 5555 protocol: TCP targetPort: 5555 - name: health nodePort: 30013 port: 8443 protocol: TCP targetPort: 8085 if you hit the my-service:8089 the traffic is routed to 8080 of the container(targetPort). Similarly, if you hit my-service:8443 then it is redirected to 8085 of the container(targetPort). But this myservice:8089 is internal to the kubernetes cluster and can be used when one application wants to communicate with another application. So to hit the service from outside the cluster someone needs to expose the port on the host machine on which kubernetes is running so that the traffic is redirected to a port of the container. This is node port(port exposed on the host machine). From the above example, you can hit the service from outside the cluster(Postman or any rest-client) by host_ip:nodePort Say your host machine ip is 10.10.20.20 you can hit the http, metrics, health services by 10.10.20.20:30475, 10.10.20.20:31261, 10.10.20.20:30013. Edits: Edited as per Raedwald comment.
Kubernetes
49,981,601
319
I've created a Kubernetes Scheduled Job, which runs twice a day according to its schedule. However, I would like to trigger it manually for testing purposes. How can I do this?
The issue #47538 that @jdf mentioned is now closed and this is now possible. The original implementation can be found here but the syntax has changed. With kubectl v1.10.1+ the command is: kubectl create job --from=cronjob/<cronjob-name> <job-name> -n <namespace-name> It seems to be backwardly compatible with older clusters as it worked for me on v0.8.x.
Kubernetes
40,401,795
314
Say, I have two namespaces k8s-app1 and k8s-app2 I can list all pods from specific namespace using the below command kubectl get pods -n <namespace> We need to append namespace to all commands to list objects from the respective namespaces. Is there a way to set specific namespace and list objects without including the namespace explicitly?
I like my answers short, to the point and with references to official documentation: Answer: kubectl config set-context --current --namespace=my-namespace From: https://kubernetes.io/docs/reference/kubectl/cheatsheet/ # permanently save the namespace for all subsequent kubectl commands in that context. kubectl config set-context --current --namespace=ggckad-s2
Kubernetes
55,373,686
300
I'm now trying to run a simple container with shell (/bin/bash) on a Kubernetes cluster. I thought that there was a way to keep a container running on a Docker container by using pseudo-tty and detach option (-td option on docker run command). For example, $ sudo docker run -td ubuntu:latest Is there an option like this in Kubernetes? I've tried running a container by using a kubectl run-container command like: kubectl run-container test_container ubuntu:latest --replicas=1 But the container exits for a few seconds (just like launching with the docker run command without options I mentioned above). And ReplicationController launches it again repeatedly. Is there a way to keep a container running on Kubernetes like the -td options in the docker run command?
Containers are meant to run to completion. You need to provide your container with a task that will never finish. Something like this should work: apiVersion: v1 kind: Pod metadata: name: ubuntu spec: containers: - name: ubuntu image: ubuntu:latest # Just spin & wait forever command: [ "/bin/bash", "-c", "--" ] args: [ "while true; do sleep 30; done;" ]
Kubernetes
31,870,222
298
I have started pods with command $ kubectl run busybox \ --image=busybox \ --restart=Never \ --tty \ -i \ --generator=run-pod/v1 Something went wrong, and now I can't delete this Pod. I tried using the methods described below but the Pod keeps being recreated. $ kubectl delete pods busybox-na3tm pod "busybox-na3tm" deleted $ kubectl get pods NAME READY STATUS RESTARTS AGE busybox-vlzh3 0/1 ContainerCreating 0 14s $ kubectl delete pod busybox-vlzh3 --grace-period=0 $ kubectl delete pods --all pod "busybox-131cq" deleted pod "busybox-136x9" deleted pod "busybox-13f8a" deleted pod "busybox-13svg" deleted pod "busybox-1465m" deleted pod "busybox-14uz1" deleted pod "busybox-15raj" deleted pod "busybox-160to" deleted pod "busybox-16191" deleted $ kubectl get pods --all-namespaces NAMESPACE NAME READY STATUS RESTARTS AGE default busybox-c9rnx 0/1 RunContainerError 0 23s
You need to delete the deployment, which should in turn delete the pods and the replica sets https://github.com/kubernetes/kubernetes/issues/24137 To list all deployments: kubectl get deployments --all-namespaces Then to delete the deployment: kubectl delete -n NAMESPACE deployment DEPLOYMENT Where NAMESPACE is the namespace it's in, and DEPLOYMENT is the name of the deployment. If NAMESPACE is default, leave off the -n option altogether. In some cases it could also be running due to a job or daemonset. Check the following and run their appropriate delete command. kubectl get jobs kubectl get daemonsets.app --all-namespaces kubectl get daemonsets.extensions --all-namespaces
Kubernetes
40,686,151
292
I have been trying to find a way to define a service in one namespace that links to a Pod running in another namespace. I know that containers in a Pod running in namespaceA can access serviceX defined in namespaceB by referencing it in the cluster DNS as serviceX.namespaceB.svc.cluster.local, but I would rather not have the code inside the container need to know about the location of serviceX. That is, I want the code to just lookup serviceX and then be able to access it. The Kubernetes documentation suggests that this is possible. It says that one of the reasons that you would define a service without a selector is that You want to point your service to a service in another Namespace or on another cluster. That suggests to me that I should: Define a serviceX service in namespaceA, without a selector (since the POD I want to select isn't in namespaceA). Define a service (which I also called serviceX) in namespaceB, and then Define an Endpoints object in namespaceA to point to serviceX in namespaceB. It is this third step that I have not been able to accomplish. First, I tried defining the Endpoints object this way: kind: Endpoints apiVersion: v1 metadata: name: serviceX namespace: namespaceA subsets: - addresses: - targetRef: kind: Service namespace: namespaceB name: serviceX apiVersion: v1 ports: - name: http port: 3000 That seemed the logical approach, and obviously what the targetRef was for. But, this led to an error saying that the ip field in the addresses array was mandatory. So, my next try was to assign a fixed ClusterIP address to serviceX in namespaceB, and put that in the IP field (note that the service_cluster_ip_range is configured as 192.168.0.0/16, and 192.168.1.1 was assigned as the ClusterIP for serviceX in namespaceB; serviceX in namespaceA was auto assigned a different ClusterIP on the 192.168.0.0/16 subnet): kind: Endpoints apiVersion: v1 metadata: name: serviceX namespace: namespaceA subsets: - addresses: - ip: 192.168.1.1 targetRef: kind: Service namespace: namespaceB name: serviceX apiVersion: v1 ports: - name: http port: 3000 That was accepted, but accesses to serviceX in namespaceA did not get forwarded to the Pod in namespaceB - they timed out. Looking at the iptables setup, it looks like it would have had to do NAT pre-routing twice to accomplish that. The only thing I did find that worked - but is not a satisfactory solution - is to lookup the actual IP address of the Pod providing serviceX in namespaceB and put that address in the Endpoints object in namespaceA. That isn't satisfactory, of course, because the Pod IP address may change over time. That's the problem service IPs are there to solve. So, is there a way to meet what seems to be the promise of the documentation that I can point a service in one namespace to a service running in a different namespace? A commenter questioned why you would want to do this - here is a use case that makes sense to me, at least: Say you have a multi-tenant system, which also includes a common data-access function that can be shared between tenants. Now imagine that there are different flavors of this data-access function with common APIs, but different performance characteristics. Some tenants get access to one of them, other tenants have access to another one. Each tenant's pods run in their own namespaces, but each one needs to access one of these common data-access services, which will necessarily be in another namespace (since it is accessed by multiple tenants). But, you wouldn't want the tenant to have to change their code if their subscription changes to access the higher-performing service. A potential solution (the cleanest one I can think of, if only it worked) is to include a service definition in each tenant's namespace for the data-access service, with each one configured for the appropriate endpoint. This service definition would be configured to point to the proper data-access service each tenant is entitled to use.
I stumbled over the same issue and found a nice solution which does not need any static ip configuration: You can access a service via it's DNS name (as mentioned by you): servicename.namespace.svc.cluster.local You can use that DNS name to reference it in another namespace via a local service: kind: Service apiVersion: v1 metadata: name: service-y namespace: namespace-a spec: type: ExternalName externalName: service-y.namespace-b.svc.cluster.local ports: - port: 80
Kubernetes
37,221,483
282
I have Kubernetes operating well in two different environments, namely in my local environment (MacBook running minikube) and as well as on Google's Container Engine (GCE, Kubernetes on Google Cloud). I use the MacBook/local environment to develop and test my YAML files and then, upon completion, try them on GCE. Currently I need to work with each environment separately: I need to edit the YAML files in my local environment and, when ready, (git) clone them to a GCE environment and then use/deploy them. This is a somewhat cumbersome process. Ideally, I would like to use kubectl from my Macbook to easily change between the local minikube or GCE Kubernetes environments and to easily determine where the YAML files are used. Is there a simple way to switch contexts to do this?
You can switch from local (minikube) to gcloud and back with: kubectl config use-context CONTEXT_NAME to list all contexts: kubectl config get-contexts You can create different enviroments for local and gcloud and put it in separate yaml files.
Kubernetes
43,643,463
277
I do have deployment with single pod, with my custom docker image like: containers: - name: mycontainer image: myimage:latest During development I want to push new latest version and make Deployment updated. Can't find how to do that, without explicitly defining tag/version and increment it for each build, and do kubectl set image deployment/my-deployment mycontainer=myimage:1.9.1
You can configure your pod with a grace period (for example 30 seconds or more, depending on container startup time and image size) and set "imagePullPolicy: "Always". And use kubectl delete pod pod_name. A new container will be created and the latest image automatically downloaded, then the old container terminated. Example: spec: terminationGracePeriodSeconds: 30 containers: - name: my_container image: my_image:latest imagePullPolicy: "Always" I'm currently using Jenkins for automated builds and image tagging and it looks something like this: kubectl --user="kube-user" --server="https://kubemaster.example.com" --token=$ACCESS_TOKEN set image deployment/my-deployment mycontainer=myimage:"$BUILD_NUMBER-$SHORT_GIT_COMMIT" Another trick is to intially run: kubectl set image deployment/my-deployment mycontainer=myimage:latest and then: kubectl set image deployment/my-deployment mycontainer=myimage It will actually be triggering the rolling-update but be sure you have also imagePullPolicy: "Always" set. Update: another trick I found, where you don't have to change the image name, is to change the value of a field that will trigger a rolling update, like terminationGracePeriodSeconds. You can do this using kubectl edit deployment your_deployment or kubectl apply -f your_deployment.yaml or using a patch like this: kubectl patch deployment your_deployment -p \ '{"spec":{"template":{"spec":{"terminationGracePeriodSeconds":31}}}}' Just make sure you always change the number value.
Kubernetes
40,366,192
265
kubectl logs <pod-id> gets latest logs from my deployment - I am working on a bug and interested to know the logs at runtime - How can I get continuous stream of logs ? edit: corrected question at the end.
kubectl logs -f <pod-id> You can use the -f flag: -f, --follow=false: Specify if the logs should be streamed. https://kubernetes.io/docs/reference/generated/kubectl/kubectl-commands#logs
Kubernetes
39,454,962
259
How do I automatically restart Kubernetes pods and pods associated with deployments when their configmap is changed/updated? I know there's been talk about the ability to automatically restart pods when a config maps changes but to my knowledge this is not yet available in Kubernetes 1.2. So what (I think) I'd like to do is a "rolling restart" of the deployment resource associated with the pods consuming the config map. Is it possible, and if so how, to force a rolling restart of a deployment in Kubernetes without changing anything in the actual template? Is this currently the best way to do it or is there a better option?
The current best solution to this problem (referenced deep in https://github.com/kubernetes/kubernetes/issues/22368 linked in the sibling answer) is to use Deployments, and consider your ConfigMaps to be immutable. When you want to change your config, create a new ConfigMap with the changes you want to make, and point your deployment at the new ConfigMap. If the new config is broken, the Deployment will refuse to scale down your working ReplicaSet. If the new config works, then your old ReplicaSet will be scaled to 0 replicas and deleted, and new pods will be started with the new config. Not quite as quick as just editing the ConfigMap in place, but much safer.
Kubernetes
37,317,003
256
Reading the Kubernets documentation it looks to be possible to select a certain range of pods based on labels. I want to select all the pods on one node but I don't want to label each pod on their corresponding node. Am I missing something from the documentation or is it just not possible to select by node? If I do: kubectl get pods \ --output=wide --namespace=$NS \ --server=$SERVER | head #=> NAME READY STATUS RESTARTS AGE NODE Can any of these headers be used as selector? If yes, how to do it with kubectl? How to do it with the API?
As mentioned in the accepted answer the PR is now merged and you can get pods by node as follows: kubectl get pods --all-namespaces -o wide --field-selector spec.nodeName=<node>
Kubernetes
39,231,880
255
kubectl config view shows contexts and clusters corresponding to clusters that I have deleted. How can I remove those entries? The command kubectl config unset clusters appears to delete all clusters. Is there a way to selectively delete cluster entries? What about contexts?
kubectl config unset takes a dot-delimited path. You can delete cluster/context/user entries by name. E.g. kubectl config unset users.gke_project_zone_name kubectl config unset contexts.aws_cluster1-kubernetes kubectl config unset clusters.foobar-baz Side note, if you teardown your cluster using cluster/kube-down.sh (or gcloud if you use Container Engine), it will delete the associated kubeconfig entries. There is also a planned kubectl config rework for a future release to make the commands more intuitive/usable/consistent.
Kubernetes
37,016,546
251
Is there a way to share secrets across namespaces in Kubernetes? My use case is: I have the same private registry for all my namespaces and I want to avoid creating the same secret for each.
Secret API objects reside in a namespace. They can only be referenced by pods in that same namespace. Basically, you will have to create the secret for every namespace. For more details, see this: Kubernetes Documentation / Concepts / Configuration / Secrets
Kubernetes
46,297,949
241
kubectl exposes commands that can be used to create a Service for an application and assigns an IP address to access it from internet. As far as I understand, to access any application within Kubernetes cluster there should be a Service resource created and that should have an IP address which is accessible from an external network. But in case of port-forward how does kubectl create a connection to the application without an IP address which is accessible externally?
To start, it's useful to note and remember that in Kubernetes, every pod gets its own ip address from 10.*, that is usable only within the cluster. Now, the port-forward feature of kubectl simply tunnels the traffic from a specified port at your local host machine to the specified port on the specified pod. API server then becomes, in a sense, a temporary gateway between your local port and the Kubernetes cluster. kubectl port-forward forwards connections to a local port to a port on a pod. Compared to kubectl proxy, kubectl port-forward is more generic as it can forward TCP traffic while kubectl proxy can only forward HTTP traffic. kubectl port-forward is useful for testing/debugging purposes so you can access your service locally without exposing it. Below is the name of the pod and it will forward it's port 6379 to localhost:6379. kubectl port-forward redis-master-765d459796-258hz 6379:6379 which is the same as kubectl port-forward pods/redis-master-765d459796-258hz 6379:6379 or kubectl port-forward deployment/redis-master 6379:6379 or kubectl port-forward rs/redis-master 6379:6379 or kubectl port-forward svc/redis-master 6379:6379
Kubernetes
51,468,491
239
Include: Daemon Sets Deployments Jobs Pods Replica Sets Replication Controllers Stateful Sets Services ... If has replicationcontroller, when delete some deployments they will regenerate. Is there a way to make kubenetes back to initialize status?
Method 1: To delete everything from the current namespace (which is normally the default namespace) using kubectl delete: kubectl delete all --all all refers to all resource types such as pods, deployments, services, etc. --all is used to delete every object of that resource type instead of specifying it using its name or label. To delete everything from a certain namespace you use the -n flag: kubectl delete all --all -n {namespace} Method 2: You can also delete a namespace and re-create it. This will delete everything that belongs to it: kubectl delete namespace {namespace} kubectl create namespace {namespace} Note (thanks @Marcus): all in kubernetes does not refers to every kubernetes object, such as admin level resources (limits, quota, policy, authorization rules). If you really want to make sure to delete eveything, it's better to delete the namespace and re-create it. Another way to do that is to use kubectl api-resources to get all resource types, as seen here: kubectl delete "$(kubectl api-resources --namespaced=true --verbs=delete -o name | tr "\n" "," | sed -e 's/,$//')" --all
Kubernetes
47,128,586
230
All of a sudden, I cannot deploy some images which could be deployed before. I got the following pod status: [root@webdev2 origin]# oc get pods NAME READY STATUS RESTARTS AGE arix-3-yjq9w 0/1 ImagePullBackOff 0 10m docker-registry-2-vqstm 1/1 Running 0 2d router-1-kvjxq 1/1 Running 0 2d The application just won't start. The pod is not trying to run the container. From the Event page, I have got Back-off pulling image "172.30.84.25:5000/default/arix@sha256:d326. I have verified that I can pull the image with the tag with docker pull. I have also checked the log of the last container. It was closed for some reason. I think the pod should at least try to restart it. I have run out of ideas to debug the issues. What can I check more?
You can use the 'describe pod' syntax For OpenShift use: oc describe pod <pod-id> For vanilla Kubernetes: kubectl describe pod <pod-id> Examine the events of the output. In my case it shows Back-off pulling image unreachableserver/nginx:1.14.22222 In this case the image unreachableserver/nginx:1.14.22222 can not be pulled from the Internet because there is no Docker registry unreachableserver and the image nginx:1.14.22222 does not exist. NB: If you do not see any events of interest and the pod has been in the 'ImagePullBackOff' status for a while (seems like more than 60 minutes), you need to delete the pod and look at the events from the new pod. For OpenShift use: oc delete pod <pod-id> oc get pods oc get pod <new-pod-id> For vanilla Kubernetes: kubectl delete pod <pod-id> kubectl get pods kubectl get pod <new-pod-id> Sample output: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Scheduled 32s default-scheduler Successfully assigned rk/nginx-deployment-6c879b5f64-2xrmt to aks-agentpool-x Normal Pulling 17s (x2 over 30s) kubelet Pulling image "unreachableserver/nginx:1.14.22222" Warning Failed 16s (x2 over 29s) kubelet Failed to pull image "unreachableserver/nginx:1.14.22222": rpc error: code = Unknown desc = Error response from daemon: pull access denied for unreachableserver/nginx, repository does not exist or may require 'docker login': denied: requested access to the resource is denied Warning Failed 16s (x2 over 29s) kubelet Error: ErrImagePull Normal BackOff 5s (x2 over 28s) kubelet Back-off pulling image "unreachableserver/nginx:1.14.22222" Warning Failed 5s (x2 over 28s) kubelet Error: ImagePullBackOff Additional debugging steps try to pull the docker image and tag manually on your computer Identify the node by doing a 'kubectl/oc get pods -o wide' ssh into the node (if you can) that can not pull the docker image check that the node can resolve the DNS of the docker registry by performing a ping. try to pull the docker image manually on the node If you are using a private registry, check that your secret exists and the secret is correct. Your secret should also be in the same namespace. Thanks swenzel Some registries have firewalls that limit ip address access. The firewall may block the pull Some CIs create deployments with temporary docker secrets. So the secret expires after a few days (You are asking for production failures...)
Kubernetes
34,848,422
227