├── CoreData.jpg
├── Lifecycle.png
├── PushNotifications.png
├── README.md
├── designpatterns1.jpg
├── designpatterns2.jpg
├── dispatch.png
├── interview.png
└── other
└── 1
/CoreData.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/CoreData.jpg
--------------------------------------------------------------------------------
/Lifecycle.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/Lifecycle.png
--------------------------------------------------------------------------------
/PushNotifications.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/PushNotifications.png
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # iOS-interview
2 |
3 | ## Table of Contents
4 | * [Preparation](#preparation)
5 | * [Phone Screen](#phone-screen)
6 | * [ON SITE](#on-site)
7 | -----------
8 | * [iOS](#iOS)
9 | * [Patterns](#Patterns)
10 | * [Extra](#Extra)
11 | -----------
12 |
13 | # Preparation
14 | [[⬆]](#contents)
15 | -----------
16 |
17 | ## Before Inteview
18 | | [ALg+Repl](https://leetcode.com/) | [DP](https://www.geeksforgeeks.org/dynamic-programming/) | [SDp](https://github.com/donnemartin/system-design-primer) | [SDy](https://www.youtube.com/watch?v=iJLL-KPqBpM) | [SDg](https://www.educative.io/courses/grokking-the-system-design-interview) | [OOD](https://www.educative.io/courses/grokking-the-object-oriented-design-interview) |
19 |
20 | ## Portfolio
21 | Portfolio
22 | 1. http://www.inheritx.com/
23 | 2. http://100grams.nl/
24 | 3. http://ios-developer.fr/
25 | 4. scalsys.com
26 | 5. http://www.aichtechnologies.com/portfolio.php
27 | 6. https://ekatsuta.github.io/index.html
28 | 7. [CV](https://www.careercup.com/resume)
29 |
30 |
31 | ## iOS(swift):
32 | ### Theory - [swift-book](https://docs.swift.org/swift-book/) [quiz](https://www.hackingwithswift.com/test)
33 | ### Practical(swift knowledge) - [swift](https://repl.it/@dmyma/Swift-knowledge)
34 | ### Practical(iOS knowledge) - [raywenderlich.com/](https://www.raywenderlich.com/10625296-navigating-the-ios-interview)
35 |
36 | ## Data Structures and Algorythms - [leetcode](leetcode.com)
37 | ### Alg:
38 | - [Leetcode](https://leetcode.com/)
39 | - [G4G](https://www.geeksforgeeks.org)
40 | - [CTCI](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850)
41 | - [EPI](https://www.amazon.com/Elements-Programming-Interviews-Python-Insiders/dp/1537713949)
42 | - MIT [6.046](https://www.youtube.com/watch?v=2P-yW7LQr08&list=PLUl4u3cNGP6317WaSNfmCvGym2ucw3oGp) [6.006](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb) [6.584](https://www.youtube.com/watch?v=hM547xRIdzc&list=PL6ogFv-ieghdoGKGg2Bik3Gl1glBTEu8c) [6.851](https://www.youtube.com/watch?v=T0yzrZL1py0&list=PLUl4u3cNGP61hsJNdULdudlRL493b-XZf)
43 | - [CF](http://codeforces.com)
44 | - [CC](codechef.com)
45 |
46 | ### DS:
47 | - [Alg 4th](https://www.amazon.com/gp/product/032157351X)
48 | - [Alg Design](https://www.amazon.com/gp/product/1849967202)
49 | - [Intro](https://www.amazon.com/Introduction-Algorithms-3rd-MIT-Press/dp)
50 | - [class SU](https://www.coursera.org/specializations/algorithms)
51 | - [Google](https://www.udacity.com/course/data-structures-and-algorithms-in-python--ud513)
52 | - [mycodeschool](https://www.youtube.com/watch?v=92S4zgXN17o&list=PL2_aWCzGMAwI3W_JlcBbtYTwiQSsOTa6P)
53 | - [MIT](https://www.youtube.com/watch?v=HtSuA80QTyo&list=PLUl4u3cNGP61Oq3tWYp6V_F-5jb5L2iHb)
54 |
55 | ## System Design / Object Oriented Design - [premier](https://github.com/donnemartin/system-design-primer)
56 | ### System Design
57 | - [Premier](https://github.com/donnemartin/system-design-primer)
58 | - [CC](https://www.careercup.com/)
59 | - [101](https://engineering.videoblocks.com/web-architecture-101-a3224e126947)
60 | - [pramp](https://github.com/donnemartin/system-design-primer)
61 | - [GSDI](https://www.educative.io/collection/5668639101419520/5649050225344512)
62 | - [youtube](https://www.youtube.com/watch?v=UzLMhqg3_Wc)
63 | - [youtube2](https://www.youtube.com/watch?v=jItLuOTsCX4)
64 | - [youtube3](https://www.youtube.com/watch?v=iJLL-KPqBpM)
65 | - [HT](https://www.hiredintech.com/courses/system-design)
66 | - [HS](http://highscalability.com/)
67 | - [FB](https://www.usenix.org/system/files/conference/atc13/atc13-bronson.pdf)
68 | - [Goo](https://static.googleusercontent.com/media/research.google.com/en//archive/gfs-sosp2003.pdf)
69 | - [Web Scalability for Startup Engineers](https://www.amazon.com/Scalability-Startup-Engineers-Artur-Ejsmont/dp/0071843655)
70 |
71 | | # | # | # |
72 | | ------------- | ------------- | ------------- |
73 | | [AWS]() | [Cassandra/MongoDB](https://db-engines.com/en/system/Cassandra%3BMongoDB%3BRedis) | [Memcached/Redis](https://www.alibabacloud.com/blog/redis-vs-memcached-in-memory-data-storage-systems_592091?gclid=EAIaIQobChMIkpK-qO-u6AIVFsJkCh03qA36EAAYASAAEgL5j_D_BwE) |
74 | | [Dynamo](https://www.allthingsdistributed.com/files/amazon-dynamo-sosp2007.pdf) | [MapReduce](https://static.googleusercontent.com/media/research.google.com/en//archive/mapreduce-osdi04.pdf) | [Consistent Hashing](https://www.akamai.com/es/es/multimedia/documents/technical-publication/consistent-hashing-and-random-trees-distributed-caching-protocols-for-relieving-hot-spots-on-the-world-wide-web-technical-publication.pdf) |
75 | | [Kafka](http://notes.stephenholiday.com/Kafka.pdf) | [RabbitMQ/Redis](https://otonomo.io/redis-kafka-or-rabbitmq-which-microservices-message-broker-to-choose/) | [Connection](https://www.smashingmagazine.com/2018/02/sse-websockets-data-flow-http2/) |
76 | |[Gluster](https://en.wikipedia.org/wiki/Gluster#GlusterFS)|[Hadoop](https://storageconference.us/2010/Papers/MSST/Shvachko.pdf) |Snowflake|
77 | | [Gossip protocol](http://highscalability.com/blog/2011/11/14/using-gossip-protocols-for-failure-detection-monitoring-mess.html) | [ZooKeper](https://www.usenix.org/legacy/event/usenix10/tech/full_papers/Hunt.pdf) | [Sync](http://engineering.nyu.edu/~suel/papers/recon.pdf) [Sync](https://pdos.csail.mit.edu/papers/lbfs:sosp01/lbfs.pdf) |
78 | | ElasticSearch | GraphQL | Docker |
79 | |nginx haproxy | | [DBs](https://www.youtube.com/watch?v=W2Z7fbCLSTw&ab_channel=Fireship)|
80 |
81 |
82 | ### Object Oriented Design:
83 | - [GOOPI](https://www.educative.io/courses/grokking-the-object-oriented-design-interview)
84 | - [PDG4](https://www.educative.io/courses/software-design-patterns-best-practices/xVovQB3Rknq)
85 | - [Patterns of Design](https://github.com/ochococo/Design-Patterns-In-Swift)
86 | - [Patterns](https://sourcemaking.com/design_patterns)
87 |
88 | ## Behavioral [Amazon 14 principals](https://www.youtube.com/watch?v=RzlUQCy84rQ)
89 | ### Answer
90 | - STAR about the project and people
91 | ### ASK [Ask](https://angel.co/blog/30-questions-to-ask-before-joining-a-startup)
92 | - What is normal day look like?
93 | - How do you decide if someone is doing a good job or vice-verca?
94 | - Why did you choose this company?
95 |
96 | # Phone Screen
97 | [[⬆]](#contents)
98 | -----------
99 |
100 | ## Theory
101 | 1. class vs struct
102 | 2. frame vs bounds + scroll view
103 | 3. GCD vs NSOperationQueue(async, sync, gcd, queues, operations, threades)[top](https://theswiftdev.com/ultimate-grand-central-dispatch-tutorial-in-swift/) [link](https://stackoverflow.com/questions/21122842/whats-the-difference-between-synchronous-and-asynchronous-calls-in-objective-c#:~:text=swift%203%2C%204%2C%204%2C,task%20to%20finish%20before%20continuing.&text=Asynchronous%20means%20that%20Completes%20a,means%20it%20will%20not%20wait.) [link](https://stackoverflow.com/questions/40764140/operationqueue-main-vs-dispatchqueue-main/40764666#:~:text=DispatchQueue%20manages%20the%20execution%20of,threads%20managed%20by%20the%20system.&text=The%20NSOperationQueue%20class%20regulates%20the%20execution%20of%20a%20set%20of%20Operation%20objects.&text=An%20application%20may%20create%20multiple,operations%20to%20any%20of%20them.) [link](https://stackoverflow.com/questions/49286984/accessing-main-queue-via-dispatchgroup-vs-dispatchqueue) [link](https://swiftwithsadiq.wordpress.com/2020/03/03/gcd-sync-vs-async/) [link](https://gist.github.com/FWEugene/3861f0460c3e23f684e113f0f8d6947f) [link](https://www.uraimo.com/2017/05/07/all-about-concurrency-in-swift-1-the-present)
104 | 4. MVVM vs MVC vs MVP vs Viper
105 | 5. ARC + ObjC
106 | 6. App LifeCycle, View LifeCycle
107 | 7. delegate vs notification center vs callback
108 | 8. Gesture recogniser
109 | 9. URL session request
110 | 10. init
111 | 11. How protocols interact with generics
112 | 12. Generics
113 | 12. Protocols: Hashable, HashFunctions, Codable
114 | 14. objC NULL, inter
115 | 15. Networking
116 | 16. Testing
117 | 17. filter, map, reduce, flatMAP, modulo
118 | 18. 3D party libraries
119 | 19. debugging
120 | 20. autolayout/sizeclasses
121 | 21. Optional biding
122 | 22. Initializers
123 |
124 | ### Quiz
125 |
126 | Which of the following types can be declared as a weak property?
127 | - internal class Bull
128 | - protocol Machine
129 | - private struct Shovel
130 | - enum Tool
131 | - public protocol BUilder: class
132 | - NSInteger
133 | - none
134 |
135 | Which of the following variables declarations or code snippets poses a memory access safety risk?
136 | - weak var name: NSString!
137 | - var person: Person?
138 | - weak var person: Person?
139 | - URLSEssion.shared.dataTask(with: url) {[unowned self] (data, response, err) in self.handleResponse(data, response, error)}
140 | - none
141 |
142 | ## Practical
143 | 1. Create a button and drag it around in code
144 | 2. Parse json
145 | 3. Networking get request and then post
146 | 4. Authentication
147 | 5. Navigation
148 | 6. Pass objects around
149 | 7. If you had a home project you can add some features or discuss your solution
150 |
151 | ## Algorithms
152 | Usually there are two questions and each can have a follow up.
153 | 1. [esay](https://leetcode.com/problems/valid-parentheses/)
154 | 2. [medium](https://leetcode.com/problems/evaluate-reverse-polish-notation/)
155 |
156 |
157 | # On site
158 | [[⬆]](#contents)
159 | -----------
160 |
161 | ## iOS
162 | 1. Write Generic Stack implementation
163 | 2. Write json parser
164 | 3. Create a quez app
165 | 4. If you had a home project you can add some features or discuss your solution
166 |
167 | ## System Design
168 | 1. Design a Callendar application
169 | 2. Design a Chat application
170 | 3. Design Twitter
171 | 4. Scalability
172 | 5. Multithreading
173 |
174 | ## DSA
175 | 1. HashMap
176 | 2. Binary Search
177 | 3. Merge Sort
178 | 4. KMP and Rabin-Karp
179 | 5. BFS and DFS
180 | 6. DP
181 | 7. Strings
182 | 8. Graphs: Trees, BT, BST, RB Tree, AB Tree, Segmented Tree, AVL
183 | 9. Sliding Window
184 | 10. 2 Pointers or Iterators
185 | 11. Fast and Slow Pointers or Iterators: Floyd's Tortoise and Hare
186 | 12. Merge Intervals
187 | 13. In-place reversal of linked list
188 | 14. Heaps
189 | 15. Topological sort: Kahn's Algorithm
190 | 16. MST: Prim(min), Kruskal(connected)
191 | 17. Union Find
192 | 18. Shortest Path: Dijkstra, Bellman Ford(n-1), Floyd Warshall(all), Johnson, A* star
193 | 19. Kaddan
194 | 20. Huffman coding
195 | 21. Korasaju's
196 | 22. De Bruijn sequence
197 | 23. Gale–Shapley
198 | 24. Fisher-Yates shuffle
199 | 25. Manacher's Algorithm
200 | 26. Moore’s Voting Algorithm)
201 | 27. Fenwick tree
202 | 28. Booth's
203 | 29. Hungarian Algorithm
204 | 30. Line sweep
205 | 31. Prefix sum
206 |
207 | ## Behavioral
208 | 1. Tell me a project you have worked that you found out it could be much bigger after you started working on this
209 | 2. Tell me a project where you had to work with tight deadlines.
210 | 3. Tell me a project where you had to analyze the initial solution and then found a differnet solution for the problem.
211 | 4. Sometimes there questions to find out if you are a leader or a manager.
212 |
213 | ## More:
214 | - [blind](teamblind.com)
215 | - [lvls](levels.fyi)
216 | - [refer](https://repher.me/)
217 | - [questions](https://www.glassdoor.com)
218 | - [without algs](https://github.com/poteto/hiring-without-whiteboards)
219 |
220 | ## iOS
221 | [[⬆]](#contents)
222 | -----------
223 | What is the diference between struct and class?
224 | An enum is an object type whose instances represent distinct predefined alternative values. Think of it as a list of known possibilities. An enum is the Swift way to express a set of constants that are alternatives to one another. An enum declaration includes case statements. Each case is the name of one of the alternatives. An instance of an enum will represent exactly one alternative — one case.
225 |
226 | Methods A method is a function — one that happens to be declared at the top level of an object type declaration. This means that everything said about functions in Chapter 2 applies. By default, a metho
227 |
228 | Properties A property is a variable — one that happens to be declared at the top level of an object type declaration. This means that everything said about variables in Chapter 3 applies. A property has a fixed type; it can be declared with var or let; it can be stored or computed; it can have setter observers. An instance property can also be declared lazy.
229 |
230 | Structs A struct is the Swift object type par excellence. An enum, with its fixed set of cases, is a reduced, specialized kind of object. A class, at the other extreme, will often turn out to be overkill; it has some features that a struct lacks, but if you don’t need those features, a struct may be preferable.
231 |
232 | Classes A class is similar to a struct, with the following key differences: Reference type Classes are reference types. This means, among other things, that a class instance has two remarkable features that are not true of struct instances or enum instances: Mutability A class instance is mutable in place. Even if your reference to an instance of a class is a constant (let), you can change the value of an instance property through that reference. An instance method of a class never has to be marked mutating (and cannot be). Multiple references When a given instance of a class is assigned to multiple variables or passed as argument to a function, you get multiple references to one and the same object. Inheritance A class can have a superclass. A class that has a superclass is a subclass of that superclass. Class types can thus form a hierarchical tree. In Objective-C, classes are the only object type. Some built-in Swift struct types are magically bridged to Objective-C class types, but your custom struct types don’t have that magic. Thus, when programming iOS with Swift, a primary reason for declaring a class, rather than a struct, is as a form of interchange with Objective-C and Cocoa.
233 |
234 | Value Types and Reference Types A major difference between enums and structs, on the one hand, and classes, on the other, is that enums and structs are value types, whereas classes are reference types. A value type is not mutable in place, even though it seems to be. For example, consider a struct. A struct is a value type:
235 |
236 |
237 |
238 | Memory Management
239 | - Core Data
240 | - SQL
241 | - Realm
242 |
243 |
244 | 1. Semaphore — allows up to N threads to access a given region of code at a time.
245 | 2. Mutex — ensures that only one thread is active in a given region of code at a time. You can think of it as a semaphore with a maximum count of 1.
246 | 3. Spinlock — causes a thread trying to acquire a lock to wait in a loop while checking if the lock is available. It is efficient if waiting is rare, but wasteful if waiting is common.
247 | 4. Read-write lock — provides concurrent access for read-only operations, but exclusive access for write operations. Efficient when reading is common and writing is rare.
248 | 5. Recursive lock — a mutex that can be acquired by the same thread many times.
249 |
250 |
251 | setNeedsLayout vs layoutIfNeeded vs layoutSubviews()
[link](http://tech.gc.com/demystifying-ios-layout/)
252 |
253 | Advanced Threading
254 | [mutex](http://www.lukeparham.com/blog/2018/6/3/comparing-synchronization-strategies)
255 | [fairness](https://www.mikeash.com/pyblog/friday-qa-2017-10-27-locks-thread-safety-and-swift-2017-edition.html)
256 | - thread vs queue[link](https://stackoverflow.com/questions/23166246/what-is-the-difference-between-thread-and-queue-in-ios-development)
257 | - load vs initialize[link](https://www.mikeash.com/pyblog/friday-qa-2009-05-22-objective-c-class-loading-and-initialization.html)
258 |
259 | NSThread vs NSOperation
260 | NSThread:
261 |
262 | 1. iOS developers have to write code for the work/process he want to perform along with for the creation and management of the threads themselves.
263 | 2. iOS developers have to be careful about a plan of action for using threads.
264 | 3. iOS developer have to manage posiable problems like reuseability of thread, lockings etc. by them self.
265 | 4. Thread will consume more memory too.
266 |
267 | NSOperation:
268 |
269 | 1. The NSOperation class is an abstract class which encapsulates the code and data associated with a single task.
270 | 2. Developer needs to use subclass or one of the system-defined subclasses of NSOperation to perform the task.
271 | 3. Add operations into NSOperationQueue to execute them.
272 | 4. The NSOperationQueue creates a new thread for each operation and runs them in the order they are added.
273 | 5. Operation queues handle all of the thread management, ensuring that operations are executed as quickly and efficiently as possible.
274 | 6. An operation queue executes operations either directly by running them on secondary threads or indirectly using GCD (Grand Central Dispatch).
275 | 7. It takes care of all of the memory management and greatly simplifies the process.
276 | 8. If you don’t want to use an operation queue, you can also execute an operation by calling its start method. It may make your code too complex.
277 |
278 |
279 |
280 | Explain NSURLSession?
281 | The NSURLSession class and related classes provide an API for downloading content via HTTP. This API provides a rich set of delegate methods for supporting authentication and gives your app the ability to perform background downloads when your app is not running or, in iOS, while your app is suspended.
282 |
283 | To use the NSURLSession API, your app creates a series of sessions, each of which coordinates a group of related data transfer tasks. For example, if you are writing a web browser, your app might create one session per tab or window. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (and for any follow-on URLs if the original URL returned an HTTP redirect).
284 |
285 | Like most networking APIs, the NSURLSession API is highly asynchronous. If you use the default, system-provided delegate, you must provide a completion handler block that returns data to your app when a transfer finishes successfully or with an error. Alternatively, if you provide your own custom delegate objects, the task objects call those delegates' methods with data as it is received from the server (or, for file downloads, when the transfer is complete).
286 |
287 | Note: Completion callbacks are primarily intended as an alternative to using a custom delegate. If you create a task using a method that takes a completion callback, the delegate methods for response and data delivery are not called.
288 | The NSURLSession API provides status and progress properties, in addition to delivering this information to delegates. It supports canceling, restarting (resuming), and suspending tasks, and it provides the ability to resume suspended, canceled, or failed downloads where they left off.
289 |
290 | Explain types of NSURLSession?
291 | The NSURLSession API supports three types of sessions, as determined by the type of configuration object used to create the session:
292 |
293 | - Default sessions : behave similarly to other Foundation methods for downloading URLs. They use a persistent disk-based cache and store credentials in the user's keychain.
294 |
295 | - Ephemeral sessions : do not store any data to disk; all caches, credential stores, and so on are kept in RAM and tied to the session. Thus, when your app invalidates the session, they are purged automatically.
296 |
297 | - Background sessions : are similar to default sessions, except that a separate process handles all data transfers. Background sessions have some additional limitations.
298 |
299 |
300 |
301 | Explain life cycle of URL Session?
302 | You can use the NSURLSession API in two ways: with a system-provided delegate or with your own delegate. In general, you must use your own delegate if your app does any of the following:
303 |
304 | - Uses background sessions to download or upload content while your app is not running.
305 | - Performs custom authentication.
306 | - Performs custom SSL certificate verification.
307 | - Decides whether a transfer should be downloaded to disk or displayed based on the MIME type returned by the server or other similar criteria.
308 | - Uploads data from a body stream (as opposed to an NSData object).
309 | - Limits caching programmatically.
310 | - Limits HTTP redirects programmatically.
311 |
312 | If your app does not need to do any of these things, your app can use the system-provided delegates. Depending on which technique you choose, you should read one of the following sections:
313 |
314 | - Life Cycle of a URL Session with System-Provided Delegates : provides a lightweight view of how your code creates and uses a URL session. You should read this section even if you intend to write your own delegate, because it gives you a complete picture of what your code must do to configure the object and use it.
315 |
316 | - Life Cycle of a URL Session with Custom Delegates : provides a complete view of every step in the operation of a URL session. You should refer to this section to help you understand how the session interacts with its delegate. In particular, this explains when each of the delegate methods is called.
317 |
318 |
319 |
320 |
321 |
322 | async vs sync
323 | [GCD vs Q](http://www.knowstack.com/swift-3-1-concurrency-operation-queue-grand-central-dispatch/)
324 |
325 |
326 |
327 | core data and different threads
328 |
329 | Basic rules are:
330 |
331 | Use one NSPersistentStoreCoordinator per program not per thread.
332 | Create one NSManagedObjectContext per thread.
333 | Never pass an NSManagedObject on a thread to the other thread.
334 | Instead, get the object IDs via -objectID and pass it to the other thread.
335 | More rules:
336 |
337 | Make sure you save the object into the store before getting the object ID. Until saved, they're temporary, and you can't access them from another thread.
338 | And beware of the merge policies if you make changes to the managed objects from more than one thread.
339 | NSManagedObjectContext's -mergeChangesFromContextDidSaveNotification: is helpful.
340 | Documentation
341 | https://cocoacasts.com/core-data-and-concurrency/
342 | https://www.raywenderlich.com/145877/core-data-tutorial-multiple-managed-object-contexts-2
343 |
344 |
345 | What steps should be accomplish in order to save/fetch an object?
346 | Step 1 — Describes which entity we are working with. LEts say Person.
347 | Step 2 — Create the our Class(PErson) NSManagedObject. The NSManagedObject will be inserted into our managed object context later when saving.
348 | Step 3 — Now that we have specified our entity and created a new class(person), we need to save the person’s name. In this case, we use key value coding to set the value for our key, which is specified as “name”.
349 | Step 4 — At this point, it’s time to save our managedObjectContext, which persists the data to the store. If an error should occur, we catch it at this point.
350 | - Fetch
351 | Step 1 — Create a fetch request. A fetch request is what we use to fetch data from our Core Data store. A fetch request can be customizable to include only the results or attributes that you need. In our case, we want to fetch all objects from the Person entity.
352 | Step 2 — We now try to fetch data from our Core Data store and store it in our managed object context, whose job it is to create a scratchpad of sorts when dealing with managed objects.
353 | Step 3 — We have a simple for loop that loops through each result in our fetched items array. At this point, we print out the name of each saved object into the console.
354 |
355 | https://www.codementor.io/codementorteam/core-data-tutorial-saving-and-fetching-pdphdmh50
356 | https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/CoreData/CreatingObjects.html
357 |
358 |
359 | Application-(Managed Object Contex(Manage Object))- Persistance storage Coordinator(PS Model) - PS
360 |
361 | point(inside:with:) vs hitTest(_:with:)
362 | NSAttributedString
363 |
364 | Swift futures
365 | Fast and concise iteration over a range or collection
366 | Structs that support methods, extensions, and protocols
367 | Functional programming patterns, e.g., map and filter
368 | Powerful error handling built-in
369 | Advanced control flow with do, guard, defer, and repeat keywords
370 |
371 | nil in Swift vs nil in Objective-C? Difference?
372 | In defintion terms:
373 |
374 | Swift optional variable is an enum, which can have nil as a value, where as objective variable is a pointer, where nil represents, it is pointing no where.
375 |
376 | In Usage terms:
377 |
378 | Both are somewhat similar in the sense,
379 |
380 | that both variables having nil value on messaging any method returns nil
381 |
382 | Optional chaining in Swift is similar to messaging nil in Objective-C, but in a way that works for any type, and that can be checked for success or failure.
383 | But in Safety Checking, Swift optional is the winner
384 |
385 | As compiler does many type checking for you already, Ex. non optional parameter can't accept optional, thus you will need to unwrap it by first checking it for nil Or when you you cast any variable, it always returns an optional, thus again a safety feature at compiler level
386 |
387 |
388 | What’s the difference between the frame and the bounds?
389 | The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).
390 | The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
391 |
392 |
393 |
394 |
395 | What is the use of controller object UIApplication?
396 | Controller object UIApplication is used without subclassing to manage the application event loop.
397 | It coordinates other high-level app behaviors.
398 | It works along with the app delegate object which contains app-level logic.
399 |
400 |
401 |
402 | Which object is create by UIApplicationMain function at app launch time?
403 | The app delegate object is created by UIApplicationMain function at app launch time. The app delegate object's main job is to handle state transitions within the app.
404 |
405 |
406 |
407 | How is the app delegate is declared by Xcode project templates?
408 | App delegate is declared as a subclass of UIResponder by Xcode project templates.
409 |
410 |
411 |
412 | What happens if IApplication object does not handle an event?
413 | In such case the event will be dispatched to your app delegate for processing.
414 |
415 |
416 |
417 | Which app specific objects store the app's content?
418 | Data model objects are app specific objects and store app’s content. Apps can also use document objects to manage some or all of their data model objects.
419 |
420 |
421 |
422 | Are document objects required for an application? What does they offer?
423 | Document objects are not required but are very useful in grouping data that belongs in a single file or file package.
424 |
425 |
426 |
427 | Which object manage the presentation of app's content on the screen?
428 | View controller objects takes care of the presentation of app's content on the screen. A view controller is used to manage a single view along with the collection of subviews. It makes its views visible by installing them in the app’s window.
429 |
430 |
431 |
432 | Which is the super class of all view controller objects?
433 | UIViewController class. The functionality for loading views, presenting them, rotating them in response to device rotations, and several other standard system behaviors are provided by UIViewController class.
434 |
435 |
436 |
437 | What is the purpose of UIWindow object?
438 | The presentation of one or more views on a screen is coordinated by UIWindow object.
439 |
440 |
441 |
442 |
443 | When an app is said to be in not running state?
444 | An app is said to be in 'not running' state when:
445 | - it is not launched.
446 | - it gets terminated by the system during running.
447 |
448 |
449 |
450 | Assume that your app is running in the foreground but is currently not receiving events. In which sate it would be in?
451 | An app will be in InActive state if it is running in the foreground but is currently not receiving events. An app stays in InActive state only briefly as it transitions to a different state.
452 |
453 |
454 | initialisers?
Memberwise, failable, Default, designated, Convenience, Required, Override, optional
455 |
456 | Nonatomic,Copy,Assign, Retain,Strong,Weak
457 | Nonatomic
458 |
459 | nonatomic is used for multi threading purposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.
460 |
461 | Copy
462 |
463 | copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
464 |
465 | Assign
466 |
467 | Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
468 |
469 | Retain
470 |
471 | retain is required when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count to) the object. You will need to release the object when you are finished with it. By using retain it will increase the retain count and occupy memory in autorelease pool.
472 |
473 | Strong
474 |
475 | strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
476 |
477 | This is a good website to learn about strong and weak for iOS 5. http://www.raywenderlich.com/5677/beginning-arc-in-ios-5-part-1
478 |
479 | Weak
480 |
481 | weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
482 |
483 |
484 |
485 | What is NSURLConnection class? Define its types and use case.
486 | There are two ways of using NSURLConnection class. One is asynchronous and the other is synchronous.
487 | An asynchronous connection will create a new thread and performs its download process on the new thread. A synchronous connection will block the calling thread while downloading content and doing its communication.
488 | Many developers think that a synchronous connection blocks the main thread, which is not true. A synchronous connection will always block the thread from which it is fired. If you fire a synchronous connection from the main thread, the main thread will be blocked. But, if you fire a synchronous connection from a thread other than the main thread, it will be like an asynchronous connection and won’t block your main thread.
489 | In fact, the only difference between a synchronous and an asynchronous connection is that at runtime, a thread will be created for the asynchronous connection while it won’t do the same for a synchronous connection.
490 | In order to create an asynchronous connection, we need to do the following:
491 | 1. Have our URL in an instance of NSString
492 | 2. Convert our string to an instance of NSURL
493 | 3. Place our URL in a URL Request of type NSURLRequest, or in the case of mutable URLs, in an instance of NSMutableURLRequest.
494 | 4. Create an instance of NSURLConnection and pass the URL request to it.
495 |
496 | What is the relation between iVar and @property?
497 | iVar is an instance variables. It cannot be accessed unless we create accessors, which are generated by @property. iVar and its counterpart @property can be of different names.
498 | @interface Box : NSObject{
499 | NSString *boxName;
500 | }
501 | @property (strong) NSString *boxDescription;//this will become another ivar
502 | -(void)aMethod;
503 | @end
504 | @implementation Box
505 | @synthesize boxDescription=boxName;//now boxDescription is accessor for name
506 | -(void)aMethod {
507 | NSLog(@"name=%@", boxName);
508 | NSLog(@"boxDescription=%@",self.boxDescription);
509 | NSLog(@"boxDescription=%@",boxDescription); //throw an error
510 | }
511 | @end
512 |
513 |
514 | What is the difference between retain & assign?
515 | Assign creates a reference from one object to another without increasing the source’s retain count.
516 | if (_variable != object)
517 | {
518 | [_variable release];
519 | _variable = nil;
520 | _variable = object;
521 | }
522 | Retain creates a reference from one object to another and increases the retain count of the source object.
523 | if (_variable != object)
524 | {
525 | [_variable release];
526 | _variable = nil;
527 | _variable = [object retain];
528 | }
529 |
530 |
531 | Give example scenarios when an application goes into InActive state?
532 | An app can get into InActive state when the user locks the screen or the system prompts the user to respond to some event e.g. SMS message, incoming call etc.
533 |
534 |
535 |
536 | When an app is said to be in active state?
537 | An app is said to be in active state when it is running in foreground and is receiving events.
538 |
539 |
540 |
541 | Name the app sate which it reaches briefly on its way to being suspended.
542 | An app enters background state briefly on its way to being suspended.
543 |
544 |
545 |
546 | Assume that an app is not in foreground but is still executing code. In which state will it be in?
547 | Background state.
548 |
549 |
550 |
551 | An app is loaded into memory but is not executing any code. In which state will it be in?
552 | An app is said to be in suspended state when it is still in memory but is not executing any code.
553 |
554 |
555 |
556 | Assume that system is running low on memory. What can system do for suspended apps?
557 | In case system is running low on memory, the system may purge suspended apps without notice.
558 |
559 |
560 |
561 | How can you respond to state transitions on your app?
562 | On state transitions can be responded to state changes in an appropriate way by calling corresponding methods on app's delegate object.
563 |
564 | applicationDidBecomeActive method can be used to prepare to run as the foreground app.
565 | applicationDidEnterBackground method can be used to execute some code when app is running in the background and may be suspended at any time.
566 | applicationWillEnterForeground method can be used to execute some code when your app is moving out of the background
567 | applicationWillTerminate method is called when your app is being terminated.
568 |
569 |
570 |
571 | List down app's state transitions when it gets launched.
572 | Before the launch of an app, it is said to be in not running state.
573 | When an app is launched, it moves to the active or background state, after transitioning briefly through the inactive state.
574 |
575 |
576 |
577 | Who calls the main function of you app during the app launch cycle?
578 | During app launching, the system creates a main thread for the app and calls the app’s main function on that main thread. The Xcode project's default main function hands over control to the UIKit framework, which takes care of initializing the app before it is run.
579 |
580 |
581 |
582 |
583 |
584 | Define view object.
585 | Views along with controls are used to provide visual representation of the app content. View is an object that draws content in a designated rectangular area and it responds to events within that area.
586 |
587 |
588 |
589 |
590 | Apart from incorporating views and controls, what else an app can incorporate?
591 | Apart from incorporating views and controls, an app can also incorporate Core Animation layers into its view and control hierarchies.
592 |
593 |
594 |
595 | What are layer objects and what do they represent?
596 | Layer objects are data objects which represent visual content. Layer objects are used by views to render their content. Custom layer objects can also be added to the interface to implement complex animations and other types of sophisticated visual effects.
597 |
598 |
599 |
600 | What are the levels of privacy in swift 3?
601 |
602 |
603 |
604 | Swift 3 has five levels of privacy: internal The default rule is that declarations are internal, meaning that they are globally visible to all code in all files within the containing module. That is why Swift files within the same module can see one another’s top-level contents automatically, with no effort on your part. (That’s different from C and Objective-C, where files can’t see each other at all unless you explicitly show them to one another through include or import statements.) fileprivate (narrower than internal) A thing declared fileprivate is visible only within its containing file. For example, two object types declared in the same file can see one another’s members declared fileprivate, but code in other files cannot see those members. private (even narrower than fileprivate) A thing declared private is visible only within its containing curly braces. In effect, the visibility of an object type’s member declared private is limited to code within this class declaration. (A private declaration at the top level of a file is equivalent to fileprivate.) public (wider than internal) A thing declared public is visible even outside its containing module. Another module must first import this module before it can see anything at all. But once another module has imported this module, it still won’t be able to see anything in this module that hasn’t been explicitly declared public. If you don’t write any modules, you might never need to declare anything public. If you do write a module, you must declare something public, or your module is useless. open (even wider than public) If a class is declared open, code in another module can subclass it; it can’t do that if the class is declared merely public. If an open class member is declared open, code in another module that subclasses this class can override
605 |
606 |
607 | When init method needed?
608 | init method are not so common because properties can have their defaults set using =
609 | or properties can be optionals
610 | you can use lazy
611 | So you only need init when a value can’t be set in any of these ways
612 |
613 | App Delegate Methods
614 | -UIApplicationDidFinishLaunching
615 | -UIApplicationWillResignActive
616 | -UIApplicationDidBecomeActive
617 | -UIApplicationWillEnterForeground
618 | -UIApplicationDidEnterBackground
619 | -UIApplicationwillterminate
620 |
621 | App States
622 | ### States
623 |
624 | Apps developed for early iOS versions (before iOS 4.0) supported three states: non-running, inactive, and active. An application delegate for pre-iOS 4.0 apps received two important method calls: applicationDidFinishLaunching and applicationWillTerminate. When an app received an applicationDidFinishLaunching message, it was an opportunity for information to be retrieved from the previous launch to restore the app to its last used state. The status, applicationWillTerminate, was used to notify the app when the app was preparing to shut down. This gave the developer an opportunity to save any unsaved data or specific state information.
625 |
626 | Currently, there are five possible application states that would be cause for the app to prepare for a transition - such as a shutdown or moving to the background. In certain cases, an app might need to continue processing in the background. However, there is certainly no reason for the app to process any graphics, animations, or display-specific routines. The five states of an iOS app - as listed in the iOS App Programming Guide - include the following:
627 |
628 | - Non-running - The app is not running.
629 | - Inactive - The app is running in the foreground, but not receiving events. An iOS app can be placed into an inactive state, for example, when a call or SMS message is received.
630 | - Active - The app is running in the foreground, and receiving events.
631 | - Background - The app is running in the background, and executing code.
632 | - Suspended - The app is in the background, but no code is being executed.
633 | - The seven most important application delegate methods
634 |
635 | The operating system calls specific methods within the application delegate to facilitate transitioning to and from various states. The seven most important application delegate methods a developer should handle are:
636 |
637 | ### application:willFinishLaunchingWithOptions
638 | Method called when the launch process is initiated. This is the first opportunity to execute any code within the app.
639 |
640 | ### application:didFinishLaunchingWithOptions
641 | Method called when the launch process is nearly complete. Since this method is called is before any of the app's windows are displayed, it is the last opportunity to prepare the interface and make any final adjustments.
642 |
643 | ### applicationDidBecomeActive
644 | Once the application has become active, the application delegate will receive a callback notification message via the method applicationDidBecomeActive.
645 |
646 | This method is also called each time the app returns to an active state from a previous switch to inactive from a resulting phone call or SMS.
647 |
648 | ### applicationWillResignActive
649 | There are several conditions that will spawn the applicationWillResignActive method. Each time a temporary event, such as a phone call, happens this method gets called. It is also important to note that "quitting" an iOS app does not terminate the processes, but rather moves the app to the background.
650 |
651 | ### applicationDidEnterBackground
652 | This method is called when an iOS app is running, but no longer in the foreground. In other words, the user interface is not currently being displayed. According to Apple's UIApplicationDelegate Protocol Reference, the app has approximately five seconds to perform tasks and return. If the method does not return within five seconds, the application is terminated.
653 |
654 | ### applicationWillEnterForeground
655 | This method is called as an app is preparing to move from the background to the foreground. The app, however, is not moved into an active state without the applicationDidBecomeActive method being called. This method gives a developer the opportunity to re-establish the settings of the previous running state before the app becomes active.
656 |
657 | ### applicationWillTerminate
658 | This method notifies your application delegate when a termination event has been triggered. Hitting the home button no longer quits the application. Force quitting the iOS app, or shutting down the device triggers the applicationWillTerminate method. This is the opportunity to save the application configuration, settings, and user preferences.
659 |
660 | ### Application state changes
661 |
662 | Every iOS app is always in one of the five app states. The operating system manages the app state, but the app itself is responsible for managing important tasks to ensure smooth transitions between the states. Developers are required to respond appropriately to app state transitions.
663 |
664 | With multitasking capability, the latest iOS version manages the resources available to every app. It is important to note, however, that the operating system limits what an app can do in the background. If an app needs to continue running in the background (with limited functionality), you must request permission.
665 |
666 | ### Launching the app
667 |
668 | The moment a user taps the app icon, the app begins to change state. The app delegate receives an application:willFinishLaunchingWithOptions method call, and the app state changes from non-running to inactive. Once in the inactive state, the app delegate will receive an application:didFinishLaunchingWithOptions method call, giving the app an opportunity to make final adjustments before the interface is displayed. If the app has not been designed to launch in the background, the operating system will activate the app, set the app state to active, and send the applicationDidBecomeActive method call to the app delegate.
669 |
670 | ### Interruptions
671 |
672 | On occasion, the iOS app will need to respond to interruptions. An alert-based interruption - such as a phone call - causes the app to move into an inactive state. The app delegate will receive an applicationWillResignActive method call, allowing the app an opportunity to prepare for a temporary inactive state. If the user chooses to ignore the interruption, or the interrupting process has terminated, the app will move back into the active state. While making the transition from inactive to active, the app delegate will receive an applicationDidBecomeActive method call.
673 |
674 | ### Switching to the background
675 |
676 | The iOS devices make it simple to quickly switch from app to app; when a user switches to a different app, the current app moves to the background. The app can be in one of two states: background or suspended. In either case, and before switching to the background, the app delegate receives an applicationWillResignActive method call, followed by an applicationDidEnterBackground message. If in a suspended state, the app sleeps. A background state - meaning that the app is allowed to continue executing code - requires the app to monitor and handle events. Developers need to be aware that the operating system may terminate the app at any time.#
677 |
678 | UIViewController lifecycle
679 | viewDidLoad - update UI, outlets are set, bounds not set yet(no geometry)
680 | viewWillApear - changing over display, geometry set, optimise performance,
681 | viewWillLAyoutSubviews - called when frames changed
682 | viewDidlayoutSubviews
683 | viewDidApear -
684 | viewWillDisapear - remember whats going on and clean up, no time consuming
685 | viewDidDisapear
686 |
687 |
688 |
689 |
690 |
691 |
692 | FPR
+MAth
693 |
694 | ```swift
695 | func incr(_ x: Int) -> Int {
696 | return x + 1
697 | }
698 |
699 | incr(2)
700 |
701 | func square(_ x: Int) -> Int {
702 | return x * x
703 | }
704 |
705 | square(incr(2))
706 |
707 | extension Int {
708 | func incr() -> Int {
709 | return self + 1
710 | }
711 |
712 | func square() -> Int {
713 | return self * self
714 | }
715 | }
716 |
717 | 2.incr()
718 | 2.incr().square()
719 |
720 | precedencegroup ForwardApplication {
721 | associativity: left
722 | }
723 |
724 | infix operator |>: ForwardApplication
725 |
726 | func |> (x: A, f: (A) -> B) -> B {
727 | return f(x)
728 | }
729 |
730 | 2 |> incr |> square
731 |
732 | extension Int {
733 | func incrAndSquare() -> Int {
734 | return self.incr().square()
735 | }
736 | }
737 |
738 | precedencegroup ForwardComposition {
739 | higherThan: ForwardApplication
740 | associativity: right
741 | }
742 | infix operator >>>: ForwardComposition
743 |
744 | func >>> (_ f: @escaping (A) -> B, _ g: @escaping (B) -> C) -> ((A) -> C) {
745 | return { a in g(f(a)) }
746 | }
747 |
748 | 2 |> incr >>> square
749 |
750 | [1, 2, 3]
751 | .map(square)
752 | .map(incr)
753 |
754 | [1, 2, 3]
755 | .map(square >>> incr)
756 | ```
757 |
758 |
759 |
760 |
761 | POP
762 | Abstraction, encapsulation, iheritance(composition), polymorphism
763 | A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task or piece of functionality.
764 | Protocol dynamicly dispatch methods
765 | Protocol Extension staticly dispatch methods
766 | Protoxcol Composition
767 |
768 |
769 | An enumeration defines a common type for a group of related values and enables you to work with those values in a type-safe way within your code.
770 | reversedrandomacesscollection
771 |
772 |
773 |
774 | Conditional Conformance in protocols
775 | - Protocols: https://useyourloaf.com/blog/swift-equatable-and-comparable/
776 |
777 |
778 | Class vs Struct
779 |
780 | - Class: CALayer, CGImage, UIView
781 | - Struck: CGRect, CGPoint,
782 | Since struct instances are allocated on stack, and class instances are allocated on heap, structs can sometimes be drastically faster.
783 |
784 |
785 | use struct unless need to use class only features or class semantics
786 | ref vs value
787 | reference cycle
788 | initialisers
789 | inheritance
790 | Classes and structures in Swift have many things in common. Both can:
791 |
792 | Define properties to store values
793 |
794 | Define methods to provide functionality
795 |
796 | Define subscripts to provide access to their values using subscript syntax
797 |
798 | Define initializers to set up their initial state
799 |
800 | Be extended to expand their functionality beyond a default implementation
801 |
802 | Conform to protocols to provide standard functionality of a certain kind
803 |
804 | For more information, see Properties, Methods, Subscripts, Initialization, Extensions, and Protocols.
805 |
806 | Classes have additional capabilities that structures do not:
807 |
808 | Inheritance enables one class to inherit the characteristics of another.
809 |
810 | Type casting enables you to check and interpret the type of a class instance at runtime.
811 |
812 | Deinitializers enable an instance of a class to free up any resources it has assigned.
813 |
814 | Reference counting allows more than one reference to a class instance.
815 |
816 | For more information, see Inheritance, Type Casting, Deinitialization, and Automatic Reference Counting.
817 |
818 | As a general guideline, consider creating a structure when one or more of these conditions apply:
819 |
820 | The structure’s primary purpose is to encapsulate a few relatively simple data values.
821 |
822 | It is reasonable to expect that the encapsulated values will be copied rather than referenced when you assign or pass around an instance of that structure.
823 |
824 | Any properties stored by the structure are themselves value types, which would also be expected to be copied rather than referenced.
825 |
826 | The structure does not need to inherit properties or behavior from another existing type.
827 |
828 | Examples of good candidates for structures include:
829 |
830 | The size of a geometric shape, perhaps encapsulating a width property and a height property, both of type Double.
831 |
832 | A way to refer to ranges within a series, perhaps encapsulating a start property and a length property, both of type Int.
833 |
834 | A point in a 3D coordinate system, perhaps encapsulating x, y and z properties, each of type Double.
835 |
836 | Extensions can add a new continuance initializer but can not add a new designated Initializer or deinit.
837 |
838 |
839 |
840 | frame vs bounds
841 |
842 | The frame of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to the superview it is contained within.
843 | The bounds of an UIView is the rectangle, expressed as a location (x,y) and size (width,height) relative to its own coordinate system (0,0).
844 |
845 | scroll view
846 | Gesture recogniser + underhood
847 |
848 |
849 | ARC
850 | BonusObj
851 |
852 | - Nonatomic
853 |
854 | nonatomic is used for multi threading purposes. If we have set the nonatomic attribute at the time of declaration, then any other thread wanting access to that object can access it and give results in respect to multi-threading.
855 |
856 | - Copy
857 |
858 | copy is required when the object is mutable. Use this if you need the value of the object as it is at this moment, and you don't want that value to reflect any changes made by other owners of the object. You will need to release the object when you are finished with it because you are retaining the copy.
859 |
860 | - Assign
861 |
862 | Assign is somewhat the opposite to copy. When calling the getter of an assign property, it returns a reference to the actual data. Typically you use this attribute when you have a property of primitive type (float, int, BOOL...)
863 |
864 | - Retain
865 |
866 | retain is required when the attribute is a pointer to an object. The setter generated by @synthesize will retain (aka add a retain count to) the object. You will need to release the object when you are finished with it. By using retain it will increase the retain count and occupy memory in autorelease pool.
867 |
868 | - Strong
869 |
870 | strong is a replacement for the retain attribute, as part of Objective-C Automated Reference Counting (ARC). In non-ARC code it's just a synonym for retain.
871 |
872 | - what is Auto release pool?
873 | The @autoreleasepool statement is doing the same job as before, instead of using the NSAutoreleasePool class. The way the NSAutoreleasePool worked was a bit weird, as creating it caused an effect throughout the whole application; @autoreleasepool creates a scoped area and makes it clearer what's within the pool and when it drains (when it goes out of scope). It's also more efficient according to Apple.
874 |
875 | - Weak
876 |
877 | weak is similar to strong except that it won't increase the reference count by 1. It does not become an owner of that object but just holds a reference to it. If the object's reference count drops to 0, even though you may still be pointing to it here, it will be deallocated from memory.
878 |
879 | - release
880 | - autorelease
881 |
882 |
883 |
884 | Keeps track of the strong references and when this number gets to 0 release the memory
885 | A weak reference is a reference that does not keep a strong hold on the instance it refers to, and so does not stop ARC from disposing of the referenced instance. This behavior prevents the reference from becoming part of a strong reference cycle. You indicate a weak reference by placing the weak keyword before a property or variable declaration.
886 |
887 | Like a weak reference, an unowned reference does not keep a strong hold on the instance it refers to. Unlike a weak reference, however, an unowned reference is used when the other instance has the same lifetime or a longer lifetime. You indicate an unowned reference by placing the unowned keyword before a property or variable declaration.
888 |
889 | ```swift
890 | lazy var someClosure: () -> String = {
891 | [unowned self, weak delegate = self.delegate!] in
892 | // closure body goes here
893 | }
894 | ```
895 |
896 |
897 |
898 |
899 |
900 |
901 |
902 | UIResponderChain?
903 | For discrete gestures
904 | G is recognized-> consumes the gesture or failed-> forwards back touch event to responder chain
905 | -For continues gestures
906 | G is began->consume(calls the delegate method specified) and changed until Ended/if not match Canceled or failed->Responder chain
907 |
908 |
909 |
910 | GCD vs NSOperationQueue
911 |
912 |
913 | What is convcurency?
914 | Main thread
915 | api on top of GCD
916 | queue of task to give GCD
917 | queue
918 | 1 main and 4 concurent
919 |
920 |
921 |
922 | FIFO
923 | - Serial queue
924 | predicted order
925 | prevent race conditions
926 |
927 | - Concurent queue
928 | Faster
929 | Unpredicted order
930 |
931 | Dependencies
932 | The NSOperation API provides support for dependencies. This is a powerful concept that enables developers to execute tasks in a specific order. An operation is ready when every dependency has finished executing.
933 |
934 | Observable
935 | The NSOperation and NSOperationQueue classes have a number of properties that can be observed, using KVO (Key Value Observing). This is another important benefit if you want to monitor the state of an operation or operation queue.
936 |
937 | Pause, Cancel, Resume
938 | Operations can be paused, resumed, and cancelled. Once you dispatch a task using Grand Central Dispatch, you no longer have control or insight into the execution of that task. The NSOperation API is more flexible in that respect, giving the developer control over the operation's life cycle.
939 |
940 | Control
941 | The NSOperationQueue also adds a number of benefits to the mix. For example, you can specify the maximum number of queued operations that can run simultaneously. This makes it easy to control how many operations run at the same time or to create a serial operation queue.
942 |
943 | Grand Central Dispatch is ideal if you just need to dispatch a block of code to a serial or concurrent queue. If you don't want to go through the hassle of creating an NSOperation subclass for a trivial task, then Grand Central Dispatch is a great alternative. Another benefit of Grand Central Dispatch is that you can keep related code together. Take a look at the following example.
944 |
945 | secure lock
946 | threads
947 | async
948 |
949 |
950 |
951 | delegate vs notification center
952 |
953 |
954 | Collections
955 | ContiguousArray
956 | ArraySlice
957 |
958 | ```swift
959 | someArray.withUnsafeBufferPointer{ p in
960 | retyrn p
961 | }
962 | ```
963 | copy-on-write
964 |
965 | ```swift
966 | array.map { $0 * 2 }.filter { $0 > 100 }.reduce(0, +)
967 | ```
968 |
969 | ```swift
970 | bigs.flatMap { big in
971 | smals.map{ smal in (big, smal)
972 |
973 | }
974 | }
975 | ```
976 |
977 | merge dictionaries
978 |
979 | Set
980 | $0.substracting($1)
981 | .intersection
982 | .union
983 |
984 | flatMap vs map -> optional
985 | only !nil optionals
986 | https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/CollectionTypes.html#//apple_ref/doc/uid/TP40014097-CH8-ID105
987 | Iterator: IteratorProtocol signle pass constructor next() - mutating (value semantic, but)
988 | sequence - serious of values that allows to iterate over
989 | collection - stable sequence allows iterate over times non destructively
990 | ```swift
991 | var iterator = string.makeIterator()
992 |
993 | while let char = iterator.next() {
994 | print(char)
995 | }
996 | ```
997 |
998 | forEach
999 | enumarate
1000 | AnyIterator - hides the itertor concreate type
1001 | AnySequence
1002 | UnfoldSequence
1003 | SubSequence - AnySequence
1004 |
1005 |
1006 | ```swift
1007 | associatedtype SubSequence: Sequence
1008 | where Iterator.Element == SubSequence.Iterator.Element,
1009 | SubSequence.SubSequence == SubSequence
1010 | ```
1011 |
1012 | ```swift
1013 | let standardIn = AnySequence {
1014 | return AnyIterator {
1015 | readLine()
1016 | }
1017 | }
1018 | ```
1019 |
1020 | "closing over", free function, dynamic/staticly dispatch
1021 | Ranges
1022 | Slicing
1023 |
1024 | Equatable
1025 | Comparable
1026 | Hashable - https://useyourloaf.com/blog/swift-hashable/
1027 |
1028 | IteratorProtocol
1029 | Sequence
1030 | Collection
1031 |
1032 | BidirectionCollection
1033 | RandomAccesCollection
1034 | MutableCollection
1035 | RangeReplcaceableCollection
1036 | Has functions
1037 | closure expression
1038 | Array functions
1039 |
1040 | Queue book p.63,65
1041 | Stack documentation
1042 | Indexable, Subscript
1043 |
1044 | JavaScript Object Notation
1045 | Representational state transfer
1046 | Alg
1047 | Hasmap
1048 |
1049 |
1050 | ```swift
1051 | extension List: IteratorProtocol, Sequnce
1052 | where Self: Iterator.Element: COmparable{
1053 | mutating function func next() -> Element? {
1054 | return pop()
1055 | }
1056 | }
1057 | ```
1058 |
1059 |
1060 |
1061 | Optionals
1062 |
1063 | ```swift
1064 | enum Optional{
1065 | case none
1066 | case some(T)
1067 | }
1068 | ```
1069 |
1070 | ```swift
1071 | let urlString = "https://img.img.jpg"
1072 | if let url = URL(string: urlString), url.pathExtension == "jpg",
1073 | let data = try? Data(contentsOf: url),
1074 | let image = UIImage(data: data) {
1075 | let view = UIImageView(image: image)
1076 | PlaygroundPage.current.liveView = view
1077 | }
1078 | ```
1079 | if let/var
1080 |
1081 | while let/var
1082 |
1083 | force unwrapping
1084 |
1085 | optional chaining
1086 |
1087 | nill-Coolescing ??
1088 | ```swift
1089 | guard let name = nameField.text where name.characters.count > 3 && name.characters.count <= 16, let range = name.rangeOfCharacterFromSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) where range.startIndex == range.endIndex else {
1090 | show("name failed validation")
1091 | return
1092 | }
1093 | ```
1094 |
1095 | submit(name)
1096 |
1097 |
1098 | ```swift
1099 | for i in 0...10 where i%2 == 0{
1100 |
1101 | }
1102 | ```
1103 |
1104 | ```swift
1105 | for case let i? in maybeInts {
1106 |
1107 | }
1108 | ```
1109 |
1110 |
1111 | Properties
1112 |
1113 | 1. Stored properties store constant and variable values as part of an instance(C, S)
1114 | - Instances of a struct with let will not allow change the properties eventhough there are var, which is not true for class
1115 | 2. Computed properties calculate (rather than store) a value(C, S, E). Instead, they provide a getter and an optional setter to retrieve and set other properties and values indirectly.
1116 | - A lazy stored property is a property whose initial value is not calculated until the first time it is used
1117 |
1118 | 3. Type properties - properties can also be associated with the type itsel.
1119 |
1120 | ```swift
1121 | var center: Point {
1122 | get {
1123 | let centerX = origin.x + (size.width / 2)
1124 | let centerY = origin.y + (size.height / 2)
1125 | return Point(x: centerX, y: centerY)
1126 | }
1127 | set(newCenter) {
1128 | set {
1129 | origin.x = newCenter.x - (size.width / 2)
1130 | origin.y = newCenter.y - (size.height / 2)
1131 | }
1132 | }
1133 | ```
1134 |
1135 | You must declare computed properties—including read-only computed properties—as variable properties with the var keyword, because their value is not fixed. The let keyword is only used for constant properties, to indicate that their values cannot be changed once they are set as part of instance initialization.
1136 |
1137 | 4. Property observers can be added to stored properties you define
1138 |
1139 | ```swift
1140 | class StepCounter {
1141 | var totalSteps: Int = 0 {
1142 | willSet(newTotalSteps) {
1143 | print("About to set totalSteps to \(newTotalSteps)")
1144 | }
1145 | didSet {
1146 | if totalSteps > oldValue {
1147 | print("Added \(totalSteps - oldValue) steps")
1148 | }
1149 | }
1150 | }
1151 | }
1152 | ```
1153 | If you pass a property that has observers to a function as an in-out parameter, the willSet and didSet observers are always called. This is because of the copy-in copy-out memory model for in-out parameters: The value is always written back to the property at the end of the function.
1154 |
1155 |
1156 | Initializers
1157 | Memberwise, Default, Convinience, Designated, Faileable, Required,
1158 |
1159 |
1160 | Classes and structures must set all of their stored properties to an appropriate initial value by the time an instance of that class or structure is created. Stored properties cannot be left in an indeterminate state.
1161 |
1162 | You can set an initial value for a stored property within an initializer, or by assigning a default property value as part of the property’s definition.
1163 | deinitializer
1164 | ```swift
1165 | struct Fahrenheit {
1166 | var temperature: Double
1167 | init() {
1168 | temperature = 32.0
1169 | }
1170 | }
1171 | var f = Fahrenheit()
1172 | print("The default temperature is \(f.temperature)° Fahrenheit")
1173 | ```
1174 | or
1175 | ```swift
1176 | struct Fahrenheit {
1177 | var temperature = 32.0
1178 | }
1179 | ```
1180 |
1181 | Initialization Parameters
1182 |
1183 | You can assign a value to a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes. Once a constant property is assigned a value, it can’t be further modified.
1184 |
1185 | Swift provides a default initializer for any structure or class that provides default values for all of its properties and does not provide at least one initializer itself. The default initializer simply creates a new instance with all of its properties set to their default values.
1186 |
1187 | Structure types automatically receive a memberwise initializer if they do not define any of their own custom initializers. Unlike a default initializer, the structure receives a memberwise initializer even if it has stored properties that do not have default values.
1188 |
1189 | Initializers can call other initializers to perform part of an instance’s initialization. This process, known as initializer delegation, avoids duplicating code across multiple initializers.
1190 |
1191 | Note that if you define a custom initializer for a value type, you will no longer have access to the default initializer (or the memberwise initializer, if it is a structure) for that type.
1192 |
1193 | --Classes vs Struct initializers
1194 |
1195 | You can initialize the Rect structure below in one of three ways—by using its default zero-initialized origin and size property values, by providing a specific origin point and size, or by providing a specific center point and size. These initialization options are represented by three custom initializers that are part of the Rect structure’s definition
1196 |
1197 | ```swift
1198 | struct Rect {
1199 | var origin = Point()
1200 | var size = Size()
1201 | init() {}
1202 | init(origin: Point, size: Size) {
1203 | self.origin = origin
1204 | self.size = size
1205 | }
1206 | init(center: Point, size: Size) {
1207 | let originX = center.x - (size.width / 2)
1208 | let originY = center.y - (size.height / 2)
1209 | self.init(origin: Point(x: originX, y: originY), size: size)
1210 | }
1211 | }
1212 | ```
1213 |
1214 | All of a class’s stored properties—including any properties the class inherits from its superclass—must be assigned an initial value during initialization.
1215 |
1216 | Swift defines two kinds of initializers for class types to help ensure all stored properties receive an initial value. These are known as designated initializers and convenience initializers.
1217 |
1218 |
1219 | Designated initializers are the primary initializers for a class. A designated initializer fully initializes all properties introduced by that class and calls an appropriate superclass initializer to continue the initialization process up the superclass chain.
1220 |
1221 | Classes tend to have very few designated initializers, and it is quite common for a class to have only one. Designated initializers are “funnel” points through which initialization takes place, and through which the initialization process continues up the superclass chain.
1222 |
1223 | Every class must have at least one designated initializer. In some cases, this requirement is satisfied by inheriting one or more designated initializers from a superclass, as described in Automatic Initializer Inheritance below.
1224 |
1225 | Convenience initializers are secondary, supporting initializers for a class. You can define a convenience initializer to call a designated initializer from the same class as the convenience initializer with some of the designated initializer’s parameters set to default values. You can also define a convenience initializer to create an instance of that class for a specific use case or input value type.
1226 |
1227 | You do not have to provide convenience initializers if your class does not require them. Create convenience initializers whenever a shortcut to a common initialization pattern will save time or make initialization of the class clearer in intent.
1228 | ```swift
1229 | init() {
1230 | }
1231 |
1232 | convenience init() {
1233 | }
1234 | ```
1235 |
1236 | To simplify the relationships between designated and convenience initializers, Swift applies the following three rules for delegation calls between initializers:
1237 |
1238 | Rule 1
1239 | A designated initializer must call a designated initializer from its immediate superclass.
1240 |
1241 | Rule 2
1242 | A convenience initializer must call another initializer from the same class.
1243 |
1244 | Rule 3
1245 | A convenience initializer must ultimately call a designated initializer.
1246 |
1247 | A simple way to remember this is:
1248 |
1249 | Designated initializers must always delegate up.
1250 |
1251 | Convenience initializers must always delegate across.
1252 |
1253 |
1254 |
1255 | Two-Phase Initialization
1256 | Class initialization in Swift is a two-phase process. In the first phase, each stored property is assigned an initial value by the class that introduced it. Once the initial state for every stored property has been determined, the second phase begins, and each class is given the opportunity to customize its stored properties further before the new instance is considered ready for use.
1257 |
1258 | The use of a two-phase initialization process makes initialization safe, while still giving complete flexibility to each class in a class hierarchy. Two-phase initialization prevents property values from being accessed before they are initialized, and prevents property values from being set to a different value by another initializer unexpectedly.
1259 |
1260 | Swift’s compiler performs four helpful safety-checks to make sure that two-phase initialization is completed without error:
1261 |
1262 | Safety check 1
1263 | A designated initializer must ensure that all of the properties introduced by its class are initialized before it delegates up to a superclass initializer.
1264 |
1265 | As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all of its own properties are initialized before it hands off up the chain.
1266 |
1267 | Safety check 2
1268 | A designated initializer must delegate up to a superclass initializer before assigning a value to an inherited property. If it doesn’t, the new value the designated initializer assigns will be overwritten by the superclass as part of its own initialization.
1269 |
1270 | Safety check 3
1271 | A convenience initializer must delegate to another initializer before assigning a value to any property (including properties defined by the same class). If it doesn’t, the new value the convenience initializer assigns will be overwritten by its own class’s designated initializer.
1272 |
1273 | Safety check 4
1274 | An initializer cannot call any instance methods, read the values of any instance properties, or refer to self as a value until after the first phase of initialization is complete.
1275 |
1276 | The class instance is not fully valid until the first phase ends. Properties can only be accessed, and methods can only be called, once the class instance is known to be valid at the end of the first phase.
1277 |
1278 | Here’s how two-phase initialization plays out, based on the four safety checks above:
1279 |
1280 | Phase 1
1281 |
1282 | A designated or convenience initializer is called on a class.
1283 |
1284 | Memory for a new instance of that class is allocated. The memory is not yet initialized.
1285 |
1286 | A designated initializer for that class confirms that all stored properties introduced by that class have a value. The memory for these stored properties is now initialized.
1287 |
1288 | The designated initializer hands off to a superclass initializer to perform the same task for its own stored properties.
1289 |
1290 | This continues up the class inheritance chain until the top of the chain is reached.
1291 |
1292 | Once the top of the chain is reached, and the final class in the chain has ensured that all of its stored properties have a value, the instance’s memory is considered to be fully initialized, and phase 1 is complete.
1293 |
1294 | Phase 2
1295 |
1296 | Working back down from the top of the chain, each designated initializer in the chain has the option to customize the instance further. Initializers are now able to access self and can modify its properties, call its instance methods, and so on.
1297 |
1298 | Finally, any convenience initializers in the chain have the option to customize the instance and to work with self.
1299 |
1300 |
1301 | Conversely, if you write a subclass initializer that matches a superclass convenience initializer, that superclass convenience initializer can never be called directly by your subclass, as per the rules
1302 |
1303 |
1304 | Automatic Initializer Inheritance
1305 | As mentioned above, subclasses do not inherit their superclass initializers by default. However, superclass initializers are automatically inherited if certain conditions are met. In practice, this means that you do not need to write initializer overrides in many common scenarios, and can inherit your superclass initializers with minimal effort whenever it is safe to do so.
1306 |
1307 | Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:
1308 |
1309 | Rule 1
1310 | If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.
1311 |
1312 | Rule 2
1313 | If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.
1314 |
1315 | Failable Initializers
1316 | It is sometimes useful to define a class, structure, or enumeration for which initialization can fail. This failure might be triggered by invalid initialization parameter values, the absence of a required external resource, or some other condition that prevents initialization from succeeding.
1317 |
1318 | To cope with initialization conditions that can fail, define one or more failable initializers as part of a class, structure, or enumeration definition. You write a failable initializer by placing a question mark after the init keyword (init?).
1319 |
1320 | - Required Initializers
1321 |
1322 | Generics
1323 | Compiler bases its decision of which overload to call on the static types and not on values dynamic types at runtime.
1324 | Compile-once-and-dispatch-dynamically
1325 |
1326 |
1327 | Can not be accros module boundaries
1328 |
1329 | Swift boxes the value in a container with fixed size to store the value, if too big swift allocates it on the heap with ref. Witness table, value witness table(vtable), protocol witness table DynamicD
1330 |
1331 | Genaric protocols - they serve a very important purpose in the swift world—defining type relationships.
1332 | 1. Generic Functions
1333 |
1334 | ```swift
1335 | func swapTwoValues(_ a: inout T, _ b: inout T)
1336 |
1337 | swapTwoValues(&someInt, &anotherInt)
1338 | ```
1339 |
1340 | 2. Type Parameters
1341 |
1342 | ```swift
1343 | struct Stack {
1344 | var items = [Element]()
1345 | mutating func push(_ item: Element) {
1346 | items.append(item)
1347 | }
1348 | mutating func pop() -> Element {
1349 | return items.removeLast()
1350 | }
1351 | }
1352 | var stackOfStrings = Stack()
1353 | ```
1354 |
1355 | Type Constraints
1356 |
1357 | ```swift
1358 | func findIndex(of valueToFind: T, in array:[T]) -> Int? {
1359 | for (index, value) in array.enumerated() {
1360 | if value == valueToFind {
1361 | return index
1362 | }
1363 | }
1364 | return nil
1365 |
1366 | ```
1367 |
1368 | 3. Protocols
1369 |
1370 | ```swift
1371 | protocol Container {
1372 | associatedtype Item
1373 | mutating func append(_ item: Item)
1374 | var count: Int { get }
1375 | subscript(i: Int) -> Item { get }
1376 | }
1377 |
1378 | struct IntStack: Container {
1379 | // original IntStack implementation
1380 | var items = [Int]()
1381 | mutating func push(_ item: Int) {
1382 | items.append(item)
1383 | }
1384 | mutating func pop() -> Int {
1385 | return items.removeLast()
1386 | }
1387 | // conformance to the Container protocol
1388 | typealias Item = Int
1389 | mutating func append(_ item: Int) {
1390 | self.push(item)
1391 | }
1392 | var count: Int {
1393 | return items.count
1394 | }
1395 | subscript(i: Int) -> Int {
1396 | return items[i]
1397 | }
1398 | }
1399 |
1400 | struct Stack: Container {
1401 | // original Stack implementation
1402 | var items = [Element]()
1403 | mutating func push(_ item: Element) {
1404 | items.append(item)
1405 | }
1406 | mutating func pop() -> Element {
1407 | return items.removeLast()
1408 | }
1409 | // conformance to the Container protocol
1410 | mutating func append(_ item: Element) {
1411 | self.push(item)
1412 | }
1413 | var count: Int {
1414 | return items.count
1415 | }
1416 | subscript(i: Int) -> Element {
1417 | return items[i]
1418 | }
1419 | }
1420 | ```
1421 | Constraints
1422 |
1423 | ```swift
1424 | protocol SuffixableContainer: Container {
1425 | associatedtype Suffix: SuffixableContainer where Suffix.Item == Item
1426 | func suffix(_ size: Int) -> Suffix
1427 | }
1428 |
1429 | protocol Container {
1430 | associatedtype Item
1431 | mutating func append(_ item: Item)
1432 | var count: Int { get }
1433 | subscript(i: Int) -> Item { get }
1434 |
1435 | associatedtype Iterator: IteratorProtocol where Iterator.Element == Item
1436 | func makeIterator() -> Iterator
1437 | }
1438 | ```
1439 |
1440 | Generic Subscripts?
1441 | How Generics Work - book - https://developer.apple.com/videos/play/wwdc2015/409/?time=992
1442 |
1443 |
1444 | Subscripts
1445 |
1446 | error hadling
1447 |
1448 | throw
1449 | throws
1450 | rethrows
1451 |
1452 | ```swift
1453 | func anyThrows() throws {
1454 | throw SomeError.error
1455 | }
1456 |
1457 | func any(callback: () throws -> Void) rethrows {
1458 | do {
1459 | try callback()
1460 | try anyThrows() // Invalid
1461 | } catch {
1462 | throw AnotherError.error
1463 | }
1464 | ```
1465 | ```swift
1466 | do {
1467 | y = try someThrowingFunction()
1468 | } catch {
1469 | y = nil
1470 | }
1471 | defer
1472 | ```
1473 |
1474 | protocols
1475 | functions
1476 |
1477 | Values vs References
1478 | Closures
1479 | Global and nested functions, as introduced in Functions, are actually special cases of closures. Closures take one of three forms:
1480 |
1481 | Global functions are closures that have a name and do not capture any values.
1482 |
1483 | Nested functions are closures that have a name and can capture values from their enclosing function.
1484 |
1485 | Closure expressions are unnamed closures written in a lightweight syntax that can capture values from their surrounding context.
1486 |
1487 | Swift’s closure expressions have a clean, clear style, with optimizations that encourage brief, clutter-free syntax in common scenarios. These optimizations include:
1488 |
1489 | Inferring parameter and return value types from context
1490 |
1491 | Implicit returns from single-expression closures
1492 |
1493 | Shorthand argument names
1494 |
1495 | Trailing closure syntax
1496 |
1497 | @escaping
1498 | A closure is said to escape a function when the closure is passed as an argument to the function, but is called after the function returns. When you declare a function that takes a closure as one of its parameters, you can write @escaping before the parameter’s type to indicate that the closure is allowed to escape.
1499 | Marking a closure with @escaping means you have to refer to self explicitly within the closure. For example, in the code below, the closure passed to someFunctionWithEscapingClosure(_:) is an escaping closure, which means it needs to refer to self explicitly. In contrast, the closure passed to someFunctionWithNonescapingClosure(_:) is a nonescaping closure, which means it can refer to self implicitly.
1500 |
1501 | @autoclosure
1502 | An autoclosure is a closure that is automatically created to wrap an expression that’s being passed as an argument to a function. It doesn’t take any arguments, and when it’s called, it returns the value of the expression that’s wrapped inside of it. This syntactic convenience lets you omit braces around a function’s parameter by writing a normal expression instead of an explicit closure.
1503 |
1504 | Global function is a closure that have a name and does not capture any values
1505 | Nested function is a closure that has a name and can capture the value from their enclosed function
1506 | Closure expressions are unnamed closures written in lightweight syntax that can capture values from their surrounding context
1507 |
1508 | Inferring parameter and return value types from context
1509 | Implicit returns from single-expression closures
1510 | Shorthand argument names
1511 | Trailing closure syntax
1512 |
1513 |
1514 | (Closure: ()-> void) {}
1515 | (Closure:{})
1516 | (){}
1517 |
1518 | Functions can be assigned to variables and passed in and out of other functions as argument, just as an int or a string can be
1519 | Functions can capture variables that exist outside of their local scope
1520 | There are two ways of creating functions - either with the func word , or with {} - closure expression.
1521 |
1522 |
1523 |
1524 |
1525 |
1526 | Methods
1527 | mutating
1528 | If you need runtime Polymorphism - that is, you want the function to be picked based on what a variable points to and not what the type of the variable is - you should be using methods not functions.
1529 |
1530 |
1531 | Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.
1532 | Assigning to self Within a Mutating Method
1533 | Instance Methods
1534 | Type Methods
1535 |
1536 |
1537 |
1538 | other
1539 | dynamic dispatch swift , polymorphism
1540 | Pattern matching
1541 | Array vs Sets
1542 | Lazy loading
1543 | Operator overloading
1544 | Tupels
1545 | Guard
1546 | Labeled statements
1547 | Nil coalescing
1548 | dynamic dyspatch - compiler doesn't know at compile time which function will run.
1549 | Subscripts enable you to query instances of a type by writing one or more values in square brackets after the instance name. Their syntax is similar to both instance method syntax and computed property syntax. You write subscript definitions with the subscript
1550 | assert
1551 | precondition
1552 | autolayout/size classes priorities - hugging/compression resistance
1553 | Hugging => content does not want to grow
1554 | Compression Resistance => content does not want to shrink
1555 | After solving for the required constraints, Auto Layout tries to solve all the optional constraints in priority order from highest to lowest. If it cannot solve for an optional constraint, it tries to come as close as possible to the desired result, and then moves on to the next constraint.
1556 |
1557 | This combination of inequalities, equalities, and priorities gives you a great amount of flexibility and power. By combining multiple constraints, you can define layouts that dynamically adapt as the size and location of the elements in your user interface change.
1558 |
1559 | >>>
1560 | throw vs optional
1561 | Operator overload
1562 | ```swift
1563 |
1564 | precedencegroup ExponentiationPrecedence {
1565 | associativity: left
1566 | higherThan: MultiplicationPrecedence
1567 | }
1568 |
1569 | infix operator **: ExponentiaionPrecedence
1570 |
1571 | func **(lhs: T, rhs: T) -> T {
1572 | return pow(lhs, rhs)
1573 | }
1574 |
1575 | ```
1576 |
1577 | Swift Style Guide
1578 | - Swift API Design Guidline
1579 | https://swift.org/documentation/api-design-guidelines/
1580 | - mark final class
1581 | - properties fileprivate
1582 | - class public but not open
1583 | - trailing closure syntax, except closure following immediately followed by another opening brace
1584 | - Leave self
1585 | - extensions instead of free functions
1586 |
1587 |
1588 | ```swift
1589 | extension Array {
1590 | func map(_ transform: (Element) -> T) -> [T] {
1591 | var result: [T] = []
1592 | for element in self {
1593 | result.append(transform(element))
1594 | }
1595 | return result
1596 | }
1597 | }
1598 | ```
1599 |
1600 |
1601 | ```swift
1602 | extension Array {
1603 | func filter(_ includeElement: (Element) -> Bool) -> [Element] {
1604 | var result: [Element] = []
1605 | for element in self where includeElement(element) {
1606 | result.append(element)
1607 | }
1608 | return result
1609 | }
1610 | }
1611 | ```
1612 |
1613 |
1614 | ```swift
1615 | extension Array {
1616 | func reduce(_ initialResult: T, combiner: (T, Element) -> T) -> T {
1617 | var result: T = initialResult
1618 | for element in self {
1619 | result = combiner(result, element)
1620 | }
1621 | return result
1622 | }
1623 | }
1624 | ```
1625 | let vs var
1626 | Collection in Swift
1627 | raw Value vs associated
1628 | If the app crashes what would you do?
1629 | Singleton
1630 | Ex. states of the app
1631 | Swift vs ObjC
1632 | Codable
1633 | typles
1634 | map, filter, reduce
1635 |
1636 | guard
1637 | class vs struct
1638 | error handling
do, try, catch
1639 | closure vs delegate vs notification
1640 | * closure only on method
1641 | * delegate foe an object
1642 | * notification many to many
1643 |
1644 |
1645 | Inheritance vs Composition
1646 | Bridge header and @objC
1647 | Documentation
1648 |
1649 |
1650 | More
1651 | 1. What is Optional in Swift and nil in Swift and Objective-C?
1652 | 2. What are properties and instance variables in Objective-C and Swift?
1653 | 3. What is a protocol (both Obj-C and Swift)? When and how is it used?
1654 | 4. What is a category/extension? When is it used?
1655 | 5. What are closures/blocks and how are they used?
1656 | 6. What is MVC?
1657 | 7. What are Singletons? What are they used for?
1658 | 8. What is Delegate pattern in iOS?
1659 | 9. What is KVO (Key-Value Observation)?
1660 | 10. What are CGRect Frames? When and where would you use them?
1661 | 11. What is AutoLayout? When and where would you use it?
1662 | 12. What are compression resistance and content hugging priorities for?
1663 | 13. How does AutoLayout work with multi-threading?
1664 | 14. What are the advantages and disadvantages of creating AutoLayouts in code versus using storyboards?
1665 | 15. How do you work with storyboards in a large team?
1666 | 16. How do you mix AutoLayout with Frames?
1667 | 17. What options do you have with animation on iOS?
1668 | 18. How do you do animation with Frames and AutoLayout?
1669 | 19. How do you work with UITableView?
1670 | 20. How do you optimize table views performance for smooth, fast scrolling?
1671 | 21. How do you work with UICollectionView?
1672 | 22. How do you work with UIScrollView?
1673 | 23. What is UIStackView? When would you use it and why?
1674 | 24. What design patterns are commonly used in iOS apps?
1675 | 25. What are SOLID principles? Can you give an example of each in iOS/Swift?
1676 | 26. How do you manage dependencies in iOS applications?
1677 | 27. What is Functional Programming and Functional Reactive Programming?
1678 | 28. MRC vs ARC? What is it? How does it work? What is the main principle?
1679 | 29. Autorelease pool, when? Next drain
1680 | 30. Objective-C properties(strong, weak, copy(which: nscopy protocol to support the , assign ) copy vs assigned
1681 | 31. Origin of bounds equals zero(rotate the view or move inside of the super view) like scroll view, frame the same bound change
1682 | 32. Problem: small button(put a view on top with Gesture recogniser, bigger button, on set of the button, responderchain(hitTest, property Animator) if the touch inside of the view or outside
1683 | 33. What are the ways to animate view(animate, core animation)property animate
1684 | 34. GCD vs NSOperationQueue, dispatch queue which is concurant(, dispatch after do?, where it can be useful , dispatchgroup, dispatch barrier async (only one at a time) , dispatch queue how to synchronize ? Locks
1685 | 35. what is deadlock? How to avoid deadlocks
1686 |
1687 |
1688 | ## Patterns
1689 | [[⬆]](#contents)
1690 | -----------
1691 |
1692 |
1693 |
1694 |
1695 | Singleton
- ensures a class has only one instance and provides global point of access to it
1696 | Factory Method
- define an interface for creating an object, but let the subclass decide which class to instantiate
1697 | ABS
- provides an interface for creating families of related or depended objects without specifying heir concrete classes
1698 | Builder
- separates the construction of a complex object from its representation so the same construction process can create different representations
1699 | Prototype
- specify the kinds of objects to create using a prototypical instance, and creating new object by copying this prototype
1700 |
1701 | Adapter
- provides a link between two otherwise incompatible types by wrapping the "adaptee" with a class that supports the interface required by the client.
1702 | Bridge
- separates the abstract elements of a class from the implementation details, providing the means to replace the implementation details without modifying the abstraction.
1703 | Facade
- define a simplified interface to a more complex system(API)
1704 | Flyweight
- minimizes memory usage or computational expenses by sharing as much as possible with other similar objects.
1705 | Proxy
- provide a surrogate or placeholder object, which reference an underlying object.( virtual - load objects on demand, protection - restricting access)
1706 | Template Method
- The Template Pattern is used when two or more implementations of an algorithm exist. The template is defined and then built upon with further variations. Use this method when most (or all) subclasses need to implement the same behavior. Traditionally, this would be accomplished with abstract classes and protected methods (as in Java). However in Swift, because abstract classes don't exist (yet - maybe someday), we need to accomplish the behavior using interface delegation.(N: Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure. )
1707 | Observer
- allows an object to publish changes to its state. Other objects subscribe to be immediately notified of any changes.
1708 | Decorator
- extends or alters the functionality of objects at run- time by wrapping them in an object of a decorator class. This provides a flexible alternative to using inheritance to modify behaviour.(coffee)
1709 |
1710 | Chain of Responsibility
- processes varied requests, each of which may be dealt with by a different handler.
1711 | Strategy
- creates an interchangeable family of algorithms from which the required process is chosen at run-time.
1712 | State
1713 | Memento
(Originator, caretaker) captures the current state of an object and store it in such a manner that it can be restored at a later time without breaking the rules of encapsulation.
1714 |
1715 |
1716 | Visitor
- separates a relatively complex set of structured data classes from the functionality that may be performed upon the data that they hold.
1717 |
1718 |
1719 | Command
- expresses a request, including the call to be made and all of its required parameters, in a command object. The command may then be executed immediately or held for later use.
1720 | Composite
- creates hierarchical, recursive tree structures of related objects where any element of the structure may be accessed and utilised in a standard manner.
1721 |
1722 | Mediator
reduces coupling between classes that communicate with each other. Instead of classes communicating directly, and thus requiring knowledge of their implementation, the classes send messages via a mediator object.
1723 | Interpreter
1724 | Iterator
1725 | What is OOP?
1726 | Inheritance - allowas a class to be definde as a modified or more specialized version of another class
1727 | Polymorphism - the capability to provide multiple implementations of an action and to select the correct implementation based on the surrounding context.override
1728 | What is POP?
1729 |
1730 | What are the pros and cons of inheritance?
1731 | What is polymorphism?
1732 | What is tight coupling?
1733 | What are design patterns and how they are good?
1734 | Tell me some important design patterns used in iOS?
1735 | What is singleton?
1736 | What challenges you have encounter implementing MVC?
1737 | What is MVVM and why you will use it?
1738 | What is dependency injection, how it is good?
1739 |
1740 | Decorator vs Inheritance
1741 | App Architecture
1742 | 1. MVC
1743 | 2. Viper
1744 | 3. MVP
1745 | 4. MVVC
1746 | 5. MVVM-C
1747 | 6. MVVM-A
1748 |
1749 | http://gexiaoguo.github.io/MVC,-MVP-and-MVVM/
1750 |
1751 |
1752 |
1753 |
1754 | ## Extra
1755 | [[⬆]](#contents)
1756 | -----------
1757 |
1758 |
1759 |
1760 |
1761 |
1762 |
1763 | Git
1764 |
1765 |
1766 |
1767 | ### Main
1768 | - git clone -b
1769 | - git checkout -b “” — specific feature
1770 | - git pull origin
1771 | - git checkout
1772 |
1773 | - git add -A .
1774 | - git commit -m "Upload"
1775 |
1776 | ### Push
1777 | - git push origin
1778 | - git push
1779 | - git push :
1780 |
1781 | ### Stash
1782 | - git stash ~ Git stash push -m “”
1783 | - git stash list
1784 | - git stash clean
1785 |
1786 | - git stash apply
1787 | - git stash pop 0 = Git stash apply 0 + Git stash drop 0
1788 |
1789 | ### More
1790 |
1791 | - git push --force
1792 |
1793 | - git tag v1.1.1
1794 | - git fetch
1795 | - git log -1
1796 | - git show
1797 | - git reset —hard “commit hash”
1798 | - git mergetool -t opendiff
1799 | - git rebase
1800 |
1801 |
1802 |
1803 | ## Libraries
1804 | [[⬆]](#contents)
1805 |
1806 | 1. Alamofire - Networking
1807 | 2. HUB - state
1808 | 3. RxSwift - FP
1809 | 4. SwiftyJSON - Parcing
1810 | 5. Nimble, Quick - Test
1811 | 6. REALM - DB
1812 | 7. Lottie - Animation
1813 |
1814 |
1815 | ### Open source
1816 |
1817 | Open Source commits(Fork, Clone, Branch, Change, Push) [link1](https://www.natashatherobot.com/beginners-contributing-to-open-source/) [link2](https://www.raywenderlich.com/179717/open-source-collaboration-using-git-and-github) [link3](https://github.com/topics/swift?l=swift) [link4](https://github.com/trending/swift)
1818 |
1819 |
1820 | | 1 | 2 | 3 |
1821 | | ------------- | ------------- | ------------- |
1822 | | youtube | [check](https://github.com/JohnSundell/ImagineEngine/issues) | [3](https://github.com/efremidze/Cluster/issues/61) |
1823 | | [IB](https://github.com/IBAnimatable/IBAnimatable/issues/434) | [check](https://github.com/Khan/SwiftTweaks) | [3](https://github.com/zvonicek/ImageSlideshow/issues/200) |
1824 | | [skeleton](https://github.com/Juanpe/SkeletonView/issues/13) |[check](https://github.com/richardtop/CalendarKit/issues) | [4](https://github.com/marmelroy/PhoneNumberKit/issues/192) |
1825 | | [LEEGO](https://github.com/wangshengjia/LeeGo/issues) | [6](https://github.com/CVCalendar/CVCalendar/issues) | [7](https://github.com/Orderella/PopupDialog/issues/204) |
1826 | | [Hero](https://github.com/lkzhao/Hero/issues) | [4](https://github.com/SwifterSwift/SwifterSwift/issues/186) | [3](https://github.com/CosmicMind/Material/issues) |
1827 | | [5](https://github.com/radex/SwiftyUserDefaults/issues) | test | |
1828 |
1829 |
1830 | ### Skills
1831 |
1832 | Stack
1833 | 1. Swift, node, python, React, Kotlin, AWS
1834 | 2. Java, Go, Rn, Vue, typescript, Flutter
1835 |
1836 | Mobile:
1837 | - iOS(Swift, Objective-C, C++) RxSwift, Alamofire | ShiftUI, Combine
1838 | - Android(Kotlin, Java) RxJava, Retrofite | Coroutines
1839 | - ReactNative
1840 | - Flutter
1841 | - Xamarin
1842 |
1843 | FE:
1844 | - React
1845 | - Vue
1846 | - Angular
1847 | - Elm
1848 |
1849 | BE:
1850 | - Node, Java, Python, Rails, Go, Elixir, Rust, Scala
1851 |
1852 | DB:
1853 | - postsql, mongoDB, AWS
1854 |
1855 | ### More
1856 | [[⬆]](#contents)
1857 | 1. http://www.geekinterview.com/Interview-Questions/iOS
1858 | 2. http://way2ios.com/development/ios-development-2/ios-interview-questions-with-answers/
1859 | 3. https://www.linkedin.com/groups/121874/121874-6146133293344579586
1860 | 4. https://medium.com/ios-os-x-development/50-ios-interview-questions-and-answers-part-2-45f952230b9f
1861 | 5. https://github.com/ochococo/Design-Patterns-In-Swift#creational
1862 | 6. https://github.com/soapyigu/LeetCode_Swift/blob/master/README.md
1863 | 7. https://github.com/9magnets/iOS-Developer-and-Designer-Interview-Questions#general
1864 | 8. https://github.com/durul/My-Medium-Articles
1865 | 9. https://github.com/5uper0/ios-science
1866 | 10. http://www.geekinterview.com/Interview-Questions/iOS
1867 | 11. https://www.glassdoor.com/Interview/san-francisco-ios-developer-interview-questions-SRCH_IL.0,13_IM759_KO14,27_SDRD.htm
1868 | 12. https://www.codementor.io/hajderrabiee/basic-swift-interview-questions-job-junior-developer-omuqax3ab
1869 | 13. http://martiancraft.com/blog/2016/10/interview-tips/
1870 | 14. https://www.thecrazyprogrammer.com/2015/11/ios-interview-questions-and-answers.html
1871 | 15. https://sourcemaking.com/
1872 | 16. https://medium.freecodecamp.org/how-i-learned-to-code-and-earned-a-job-in-silicon-valley-changing-my-life-along-the-way-a3af854855fa
1873 | 17. https://engineering.pandora.com/engineering-interviews-at-pandora-eb339d80afc0
1874 | 18. https://medium.com/@jamesrochabrun/parsing-json-response-and-save-it-in-coredata-step-by-step-fb58fc6ce16f
1875 | 19. https://docs.google.com/document/d/1tIyrbbTAzeiwMO0Fshfh2PQNPDZ7cuunCPiu1vnc8Ic/edit
1876 | 20. https://paulhanna1933.github.io/
1877 | 21. https://medium.com/better-programming/how-to-write-an-ios-developer-resume-that-will-land-you-an-interview-43cf66c6d4fa
1878 | 22. https://uxplanet.org/ux-design-portfolios-best-practices-8676e6a72ab
1879 | 23. https://www.raywenderlich.com/862-top-8-programmer-hobbies
1880 | 24. https://resume.creddle.io/resume/5n9dp9okfvo
1881 | 25. https://github.com/NirantK/awesome-project-ideas
1882 | 26. https://medium.freecodecamp.com/how-i-learned-to-code-and-earned-a-job-in-silicon-valley-changing-my-life-along-the-way-a3af854855fa
1883 | 27. https://medium.freecodecamp.com/how-i-left-my-consulting-career-behind-and-broke-into-tech-36ea0c1a0407
1884 | 28. https://blog.usejournal.com/a-complete-guide-to-getting-hired-as-an-ios-developer-in-2018-d7dcf50dc25
1885 | 29. [Company](https://github.com/algerrnon/noway)
1886 | 30. [Company2](https://people.neilon.software/?fbclid=IwAR0XnIe8AhIE4pmeyjyYf5AnKYrPdAXf5SGwHhslZhg0-Euktu6fdvfytXc)
1887 | 31. [lvl](https://github.com/bohdanorlov/ios-skills-matrix)
1888 | 32. [clear code](https://github.com/sergdort/CleanArchitectureRxSwift)
1889 | 33. [interview prep1](https://engineering.pandora.com/engineering-interviews-at-pandora-eb339d80afc0)
1890 | 34. [interview prep2](https://blog.usejournal.com/a-complete-guide-to-getting-hired-as-an-ios-developer-in-2018-d7dcf50dc25)
1891 | 35. [Staff Eng experience](https://leetcode.com/discuss/interview-experience/906579/Staff-Eng-or-FacebookAirbnbPinterestSquareStripeByteDance-or-San-Francisco-or-Sept-2020-or-Offers)
1892 | 36. [5 top companies](https://medium.com/@XiaohanZeng/i-interviewed-at-five-top-companies-in-silicon-valley-in-five-days-and-luckily-got-five-job-offers-25178cf74e0f)
1893 | 37. [7 onsites 7 offers](https://www.teamblind.com/post/7-onsites-7-offers-aAFTykAD)
1894 |
--------------------------------------------------------------------------------
/designpatterns1.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/designpatterns1.jpg
--------------------------------------------------------------------------------
/designpatterns2.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/designpatterns2.jpg
--------------------------------------------------------------------------------
/dispatch.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/dispatch.png
--------------------------------------------------------------------------------
/interview.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/dmyma/iOS-interview/78db551339c1c60d12e661680ba6eb58fb417c59/interview.png
--------------------------------------------------------------------------------
/other/1:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------