text
stringlengths
8
1.32M
// // Created by Efe Ejemudaro on 15/04/2021. // Copyright (c) 2021 TopTier labs. All rights reserved. // import Foundation struct OnboardUserRequest: Codable { let licenseNumber: String let nationality: String private enum CodingKeys: String, CodingKey { case licenseNumber case nationality } }
// // ResultsTableView.swift // testYourself // // Created by Marin on 10/02/2018. // Copyright © 2018 Arthur BRICQ. All rights reserved. // import UIKit class ResultsTableView: UITableView { }
// // ConversationTableViewCell.swift // Sunlit // // Created by Jonathan Hays on 5/20/20. // Copyright © 2020 Micro.blog, LLC. All rights reserved. // import UIKit import Snippets class ConversationTableViewCell : UITableViewCell, UICollectionViewDataSource, UICollectionViewDelegate { @IBOutlet var avatar : UIImageView! @IBOutlet var userName : UILabel! @IBOutlet var userHandle : UILabel! @IBOutlet var replyText : UITextView! @IBOutlet var photosCollectionView : UICollectionView? @IBOutlet var photosCollectionHeightConstraint : NSLayoutConstraint? @IBOutlet var dateLabel : UILabel! var post : SunlitPost? = nil override func awakeFromNib() { self.avatar.clipsToBounds = true self.avatar.layer.cornerRadius = (self.avatar.bounds.size.height - 1) / 2.0 self.userName.font = UIFont.preferredFont(forTextStyle: .headline) self.userHandle.font = UIFont.preferredFont(forTextStyle: .subheadline) self.addUserProfileTapGesture(self.userName) self.addUserProfileTapGesture(self.avatar) self.addUserProfileTapGesture(self.userHandle) } func setup(_ post : SunlitPost, _ indexPath : IndexPath) { self.post = post self.replyText.attributedText = post.attributedText self.replyText.textContainerInset = UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 0) self.userName.text = post.owner.fullName self.userHandle.text = "@" + post.owner.userName self.loadProfilePhoto(post.owner, indexPath) if let date = post.publishedDate { self.dateLabel.text = date.friendlyFormat() } else { self.dateLabel.text = "" } if let collection_height_constraint = self.photosCollectionHeightConstraint { if post.images.count == 0 { collection_height_constraint.constant = 0 } else { // 40x40 cells with 4pt padding + 4pt margins around collection view collection_height_constraint.constant = 48 } } } func addUserProfileTapGesture(_ view : UIView) { view.isUserInteractionEnabled = true for gesture in view.gestureRecognizers ?? [] { view.removeGestureRecognizer(gesture) } let gesture = UITapGestureRecognizer(target: self, action: #selector(handleUserTappedGesture)) view.addGestureRecognizer(gesture) } @objc func handleUserTappedGesture() { NotificationCenter.default.post(name: .viewUserProfileNotification, object: self.post?.owner) } func loadProfilePhoto(_ owner: SnippetsUser, _ indexPath: IndexPath) { let avatarSource = owner.avatarURL if let avatar = ImageCache.prefetch(avatarSource) { self.avatar.image = avatar } else { ImageCache.fetch(self, avatarSource) { (image) in if let _ = image { DispatchQueue.main.async { NotificationCenter.default.post(name: .refreshCellNotification, object: indexPath) } } } } } func loadPostPhotos(_ cell: ConversationPhotoCollectionViewCell, _ indexPath: IndexPath) { if let post = self.post { let url = post.images[indexPath.item] if let image = ImageCache.prefetch(url) { cell.imageView.image = image } else { ImageCache.fetch(self, url) { image in if let _ = image { DispatchQueue.main.async { self.photosCollectionView?.reloadItems(at: [ indexPath ]) } } } } } } func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { if let post = self.post { return post.images.count } else { return 0 } } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "ConversationPhotoCollectionViewCell", for: indexPath) as! ConversationPhotoCollectionViewCell return cell } func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { if let cell = cell as? ConversationPhotoCollectionViewCell { self.loadPostPhotos(cell, indexPath) } } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { if let post = self.post { let url = post.images[indexPath.item] var dictionary : [String : Any] = [:] dictionary["imagePath"] = url dictionary["post"] = post NotificationCenter.default.post(name: .viewPostNotification, object: dictionary) } } }
import Foundation protocol DetailViewModelDelegate: class { func updateUI() } final class MovieDetailViewModel { private var tubiClient: TubiClient var movie: Movie? var movieId: String weak var delegate: DetailViewModelDelegate? init(movieId: String, tubiClient: TubiClient = TubiClient()) { self.movieId = movieId self.tubiClient = tubiClient } func getMovieDetails() { tubiClient.getMovieDetails(movieId: movieId) { [weak self] (result: Result<Movie>) in guard let `self` = self else { return } switch result { case .result(let movie): self.movie = movie DispatchQueue.main.async { self.delegate?.updateUI() } cache.add(key: self.movieId, value: movie) case .error(let error): //Handle Error ie crashalytics, UIAlert, pop screen, etc using the delegate //Depending on how you handle the error you might want to stop the spinner........ print(error) } } } }
// RUN: %target-swift-frontend -parse-stdlib -emit-silgen %s | FileCheck %s // CHECK: [_semantics "123"] [_semantics "223"] @func1 @_semantics("223") @_semantics("123") @_silgen_name("func1") func func1() { }
// // Index+Indexing.swift // // // Created by Vladislav Fitc on 03/03/2020. // // swiftlint:disable file_length import Foundation public extension Index { // MARK: - Save object /** Add a new record to an index. - Note: This method allows you to create records on your index by sending one or more objects. Each object contains a set of attributes and values, which represents a full record on an index. There is no limit to the number of objects that can be passed, but a size limit of 1 GB on the total request. For performance reasons, it is recommended to push batches of ~10 MB of payload. Batching records allows you to reduce the number of network calls required for multiple operations. But note that each indexed object counts as a single indexing operation. When adding large numbers of objects, or large sizes, be aware of our rate limit. You’ll know you’ve reached the rate limit when you start receiving errors on your indexing operations. This can only be resolved if you wait before sending any further indexing operations. - Parameter object: The record of type T to save. - Parameter autoGeneratingObjectID: Add objectID if record type doesn't provide it in serialized form. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronousoperation */ @discardableResult func saveObject<T: Encodable>(_ object: T, autoGeneratingObjectID: Bool = false, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<ObjectCreation>) -> Operation & TransportTask { if !autoGeneratingObjectID { ObjectIDChecker.assertObjectID(object) } let command = Command.Indexing.SaveObject(indexName: name, record: object, requestOptions: requestOptions) return execute(command, completion: completion) } /** Add a new record to an index. - See: saveObject - Parameter object: The record of type T to save. - Parameter autoGeneratingObjectID: Add objectID if record type doesn't provide it in serialized form. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: ObjectCreation task */ @discardableResult func saveObject<T: Encodable>(_ object: T, autoGeneratingObjectID: Bool = false, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<ObjectCreation> { if !autoGeneratingObjectID { try ObjectIDChecker.checkObjectID(object) } let command = Command.Indexing.SaveObject(indexName: name, record: object, requestOptions: requestOptions) return try execute(command) } // MARK: - Save objects /** Add multiple schemaless objects to an index. - See: saveObject - Parameter objects The list of records to save. - Parameter autoGeneratingObjectID: Add objectID if record type doesn't provide it in serialized form. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronousoperation */ @discardableResult func saveObjects<T: Encodable>(_ objects: [T], autoGeneratingObjectID: Bool = false, requestOptions: RequestOptions? = nil, completion: @escaping ResultBatchesCallback) -> Operation { return batch(objects.map { .add($0, autoGeneratingObjectID: autoGeneratingObjectID) }, requestOptions: requestOptions, completion: completion) } /** Add multiple schemaless objects to an index. - See: saveObject - Parameter objects The list of records to save. - Parameter autoGeneratingObjectID: Add objectID if record type doesn't provide it in serialized form. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Batch task */ @discardableResult func saveObjects<T: Encodable>(_ objects: [T], autoGeneratingObjectID: Bool = false, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<BatchesResponse> { return try batch(objects.map { .add($0, autoGeneratingObjectID: autoGeneratingObjectID) }, requestOptions: requestOptions) } // MARK: - Get object /** Get one record using its ObjectID. - Parameter objectID: The ObjectID to identify the record. - Parameter attributesToRetrieve: Specify a list of Attribute to retrieve. This list will apply to all records. If you don’t specify any attributes, every attribute will be returned. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronousoperation */ @discardableResult func getObject<T: Decodable>(withID objectID: ObjectID, attributesToRetrieve: [Attribute] = [], requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<T>) -> Operation & TransportTask { let command = Command.Indexing.GetObject(indexName: name, objectID: objectID, attributesToRetrieve: attributesToRetrieve, requestOptions: requestOptions) return execute(command, completion: completion) } /** Get one record using its ObjectID. - Parameter objectID: The ObjectID to identify the record. - Parameter attributesToRetrieve: Specify a list of Attribute to retrieve. This list will apply to all records. If you don’t specify any attributes, every attribute will be returned. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Requested record */ @discardableResult func getObject<T: Decodable>(withID objectID: ObjectID, attributesToRetrieve: [Attribute] = [], requestOptions: RequestOptions? = nil) throws -> T { let command = Command.Indexing.GetObject(indexName: name, objectID: objectID, attributesToRetrieve: attributesToRetrieve, requestOptions: requestOptions) return try execute(command) } // MARK: - Get objects /** Get multiple records using their ObjectID. - Parameter objectIDs: The list of ObjectID to identify the srecord. - Parameter attributesToRetrieve: Specify a list of Attribute to retrieve. This list will apply to all records. If you don’t specify any attributes, every attribute will be returned. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronousoperation */ @discardableResult func getObjects<T: Decodable>(withIDs objectIDs: [ObjectID], attributesToRetrieve: [Attribute] = [], requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<ObjectsResponse<T>>) -> Operation & TransportTask { let command = Command.MultipleIndex.GetObjects(indexName: name, objectIDs: objectIDs, attributesToRetreive: attributesToRetrieve, requestOptions: requestOptions) return execute(command, completion: completion) } /** Get multiple records using their ObjectID. - Parameter objectIDs: The list ObjectID to identify the records. - Parameter attributesToRetrieve: Specify a list of Attribute to retrieve. This list will apply to all records. If you don’t specify any attributes, every attribute will be returned. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: ObjectResponse object containing requested records */ @discardableResult func getObjects<T: Decodable>(withIDs objectIDs: [ObjectID], attributesToRetrieve: [Attribute] = [], requestOptions: RequestOptions? = nil) throws -> ObjectsResponse<T> { let command = Command.MultipleIndex.GetObjects(indexName: name, objectIDs: objectIDs, attributesToRetreive: attributesToRetrieve, requestOptions: requestOptions) return try execute(command) } // MARK: - Replace object /** Replace an existing object with an updated set of attributes. - Note: The save method is used to redefine the entire set of an object’s attributes (except of course its [ObjectID]). In other words, it fully replaces an existing object. Saving objects has the same effect as the add objects method if you specify objectIDs for every record. This method differs from partial update objects in a significant way: With save objects you define an object’s full set of attributes. Attributes not specified will no longer exist. For example, if an existing object contains attribute X, but X is not defined in a later update call, attribute X will no longer exist for that object. In contrast, with partial update objects you can single out one or more attributes, and either remove them, add them, or update their content. Additionally, attributes that already exist but are not specified in a partial update are not impacted. When updating large numbers of objects, or large sizes, be aware of our rate limit. You’ll know you’ve reached the rate limit when you start receiving errors on your indexing operations. This can only be resolved if you wait before sending any further indexing operations. - Parameter objectID: The ObjectID to identify the object. - Parameter record: The record T to replace. - Parameter requestOptions: Configure request locally with RequestOptions - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func replaceObject<T: Encodable>(withID objectID: ObjectID, by object: T, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<ObjectRevision>) -> Operation & TransportTask { let command = Command.Indexing.ReplaceObject(indexName: name, objectID: objectID, replacementObject: object, requestOptions: requestOptions) return execute(command, completion: completion) } /** Replace an existing object with an updated set of attributes. - See_also: replaceObject - Parameter objectID: The ObjectID to identify the object. - Parameter record: The record T to replace. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: ObjectRevision object */ @discardableResult func replaceObject<T: Encodable>(withID objectID: ObjectID, by object: T, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<ObjectRevision> { let command = Command.Indexing.ReplaceObject(indexName: name, objectID: objectID, replacementObject: object, requestOptions: requestOptions) return try execute(command) } // MARK: - Replace objects /** Replace multiple objects with an updated set of attributes. - See: replaceObject - Parameter replacements: The list of paris of ObjectID and the replacement object . - Parameter requestOptions: Configure request locally with RequestOptions - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func replaceObjects<T: Encodable>(replacements: [(objectID: ObjectID, object: T)], requestOptions: RequestOptions? = nil, completion: @escaping ResultBatchesCallback) -> Operation { return batch(replacements.map { .update(objectID: $0.objectID, $0.object) }, requestOptions: requestOptions, completion: completion) } /** Replace multiple objects with an updated set of attributes. - See: replaceObject - Parameter replacements: The list of paris of ObjectID and the replacement object . - Parameter requestOptions: Configure request locally with RequestOptions - Returns: ObjectRevision object */ @discardableResult func replaceObjects<T: Encodable>(replacements: [(objectID: ObjectID, object: T)], requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<BatchesResponse> { return try batch(replacements.map { .update(objectID: $0.objectID, $0.object) }, requestOptions: requestOptions) } // MARK: - Delete object /** Remove an object from an index using its ObjectID. - Parameter objectID: The ObjectID to identify the record. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronousoperation */ @discardableResult func deleteObject(withID objectID: ObjectID, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<ObjectDeletion>) -> Operation & TransportTask { let command = Command.Indexing.DeleteObject(indexName: name, objectID: objectID, requestOptions: requestOptions) return execute(command, completion: completion) } /** Remove an object from an index using its ObjectID. - Parameter objectID: The ObjectID to identify the record. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: Requested record */ @discardableResult func deleteObject(withID objectID: ObjectID, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<ObjectDeletion> { let command = Command.Indexing.DeleteObject(indexName: name, objectID: objectID, requestOptions: requestOptions) return try execute(command) } // MARK: - Delete objects /** Remove multiple objects from an index using their ObjectID. - Parameter objectIDs: The list ObjectID to identify the records. - Parameter requestOptions: Configure request locally with RequestOptions - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func deleteObjects(withIDs objectIDs: [ObjectID], requestOptions: RequestOptions? = nil, completion: @escaping ResultBatchesCallback) -> Operation { return batch(objectIDs.map { .delete(objectID: $0) }, requestOptions: requestOptions, completion: completion) } /** Remove multiple objects from an index using their ObjectID. - Parameter objectIDs: The list ObjectID to identify the records. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: BatchResponse object */ @discardableResult func deleteObjects(withIDs objectIDs: [ObjectID], requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<BatchesResponse> { return try batch(objectIDs.map { .delete(objectID: $0) }, requestOptions: requestOptions) } /** Remove all objects matching a DeleteByQuery. - Note: This method enables you to delete one or more objects based on filters (numeric, facet, tag or geo queries). It does not accept empty filters or a query. If you have a way to fetch the list of ObjectID you want to delete, use the deleteObjects method instead as it is more performant. The delete by method only counts as 1 operation - even if it deletes more than one object. This is exceptional; most indexing options that affect more than one object normally count each object as a separate operation. When deleting large numbers of objects, or large sizes, be aware of our rate limit. You’ll know you’ve reached the rate limit when you start receiving errors on your indexing operations. This can only be resolved if you wait before sending any further indexing operations. - Parameter query: DeleteByQuery to match records for deletion. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func deleteObjects(byQuery query: DeleteByQuery, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Indexing.DeleteByQuery(indexName: name, query: query, requestOptions: requestOptions) return execute(command, completion: completion) } /** Remove all objects matching a DeleteByQuery. - Parameter query: DeleteByQuery to match records for deletion. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: RevisionIndex object */ @discardableResult func deleteObjects(byQuery query: DeleteByQuery, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Indexing.DeleteByQuery(indexName: name, query: query, requestOptions: requestOptions) return try execute(command) } // MARK: - Partial update object /** Update one or more attributes of an existing record. - Note: This method enables you to update only a part of an object by singling out one or more attributes of an existing object and performing the following actions: - add new attributes - update the content of existing attributes Specifying existing attributes will update them in the object, while specifying new attributes will add them. You need to use the save objects method if you want to completely redefine an existing object, replace an object with a different one, or remove attributes. You cannot individually remove attributes. Nested attributes cannot be individually updated. If you specify a nested attribute, it will be treated as a replacement of its first-level ancestor. To change nested attributes, you will need to use the save object method. You can initially get the object’s data either from your own data or by using the get object method. The same can be said about array attributes: you cannot update individual elements of an array. If you have a record in which one attribute is an array, you will need to retrieve the record’s array, change the element(s) of the array, and then resend the full array using this method. When updating large numbers of objects, or large sizes, be aware of our rate limit. You’ll know you’ve reached the rate limit when you start receiving errors on your indexing operations. This can only be resolved if you wait before sending any further indexing operations. - Parameter objectID: The ObjectID identifying the record to partially update. - Parameter partialUpdate: PartialUpdate - Parameter createIfNotExists: When true, a partial update on a nonexistent record will create the record (generating the objectID and using the attributes as defined in the record). When false, a partial update on a nonexistent record will be ignored (but no error will be sent back). - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func partialUpdateObject(withID objectID: ObjectID, with partialUpdate: PartialUpdate, createIfNotExists: Bool = true, requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<ObjectRevision>) -> Operation & TransportTask { let command = Command.Indexing.PartialUpdate(indexName: name, objectID: objectID, partialUpdate: partialUpdate, createIfNotExists: createIfNotExists, requestOptions: requestOptions) return execute(command, completion: completion) } /** Update one or more attributes of an existing record. - Parameter objectID: The ObjectID identifying the record to partially update. - Parameter partialUpdate: PartialUpdate - Parameter createIfNotExists: When true, a partial update on a nonexistent record will create the record (generating the objectID and using the attributes as defined in the record). When false, a partial update on a nonexistent record will be ignored (but no error will be sent back). - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: ObjectRevision object */ @discardableResult func partialUpdateObject(withID objectID: ObjectID, with partialUpdate: PartialUpdate, createIfNotExists: Bool = true, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<ObjectRevision> { let command = Command.Indexing.PartialUpdate(indexName: name, objectID: objectID, partialUpdate: partialUpdate, createIfNotExists: createIfNotExists, requestOptions: requestOptions) return try execute(command) } // MARK: - Partial update objects /** Update one or more attributes of existing records. - Parameter updates: The list of pairs of ObjectID identifying the record and its PartialUpdate. - Parameter createIfNotExists: When true, a partial update on a nonexistent record will create the record (generating the objectID and using the attributes as defined in the record). When false, a partial update on a nonexistent record will be ignored (but no error will be sent back). - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func partialUpdateObjects(updates: [(objectID: ObjectID, update: PartialUpdate)], createIfNotExists: Bool = true, requestOptions: RequestOptions? = nil, completion: @escaping ResultBatchesCallback) -> Operation { return batch(updates.map { .partialUpdate(objectID: $0.objectID, $0.update, createIfNotExists: createIfNotExists) }, requestOptions: requestOptions, completion: completion) } /** Update one or more attributes of existing records. - Parameter replacements: The list of pairs of ObjectID identifying the record and its PartialUpdate. - Parameter createIfNotExists: When true, a partial update on a nonexistent record will create the record (generating the objectID and using the attributes as defined in the record). When false, a partial update on a nonexistent record will be ignored (but no error will be sent back). - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: BatchResponse object */ @discardableResult func partialUpdateObjects(updates: [(objectID: ObjectID, update: PartialUpdate)], createIfNotExists: Bool = true, requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<BatchesResponse> { return try batch(updates.map { .partialUpdate(objectID: $0.objectID, $0.update, createIfNotExists: createIfNotExists) }, requestOptions: requestOptions) } // MARK: - Batch operations /** Perform several indexing operations in one API call. - Note: This method enables you to batch multiple different indexing operations in one API, like add or delete records potentially targeting multiple indices. - Parameter batchOperations: List of BatchOperation - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func batch(_ batchOperations: [BatchOperation], requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<BatchesResponse> { let responses = try batchOperations.chunked(into: configuration.batchSize).map { try internalBatch($0) } let response = BatchesResponse(indexName: name, responses: responses) return .init(batchesResponse: response, index: self) } /** Perform several indexing operations in one API call. - Parameter batchOperations: List of BatchOperation - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: BatchesResponse object */ @discardableResult func batch(_ batchOperations: [BatchOperation], requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<WaitableWrapper<BatchesResponse>>) -> Operation { let operation = BlockOperation { completion(.init { try self.batch(batchOperations, requestOptions: requestOptions) }) } return launch(operation) } // MARK: - Clear objects /** Clear the records of an index without affecting its settings. - Note: This method enables you to delete an index’s contents (records) without removing any settings, rules and synonyms. If you want to remove the entire index and not just its records, use the delete method instead. Clearing an index will have no impact on its Analytics data because you cannot clear an index’s analytics data. - Parameter requestOptions: Configure request locally with RequestOptions. - Parameter completion: Result completion - Returns: Launched asynchronous operation */ @discardableResult func clearObjects(requestOptions: RequestOptions? = nil, completion: @escaping ResultTaskCallback<IndexRevision>) -> Operation & TransportTask { let command = Command.Indexing.ClearObjects(indexName: name, requestOptions: requestOptions) return execute(command, completion: completion) } /** Clear the records of an index without affecting its settings. - Parameter requestOptions: Configure request locally with RequestOptions. - Returns: RevisionIndex object */ @discardableResult func clearObjects(requestOptions: RequestOptions? = nil) throws -> WaitableWrapper<IndexRevision> { let command = Command.Indexing.ClearObjects(indexName: name, requestOptions: requestOptions) return try execute(command) } // MARK: - Replace all objects /** Push a new set of objects and remove all previous ones. Settings, synonyms and query rules are untouched. Replace all objects in an index without any downtime. Internally, this method copies the existing index settings, synonyms and query rules and indexes all passed objects. Finally, the existing index is replaced by the temporary one. - Parameter objects: A list of replacement objects. - Parameter requestOptions: Configure request locally with RequestOptions - Parameter safe: Whether to wait for indexing operations. - Parameter completion: Result completion */ func replaceAllObjects<T: Encodable>(with objects: [T], autoGeneratingObjectID: Bool = false, safe: Bool = false, requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<[IndexedTask]>) { let moveOperations: [BatchOperation] = objects.map { .add($0, autoGeneratingObjectID: autoGeneratingObjectID) } let sourceIndexName = name let destinationIndexName: IndexName = "\(name)_tmp_\(Int.random(in: 0...100000))" let destinationIndex = Index(name: destinationIndexName, transport: transport, operationLauncher: operationLauncher, configuration: configuration) func extract<V>(_ result: Result<V, Error>, process: (V) -> Void) { switch result { case .failure(let error): completion(.failure(error)) case .success(let value): process(value) } } copy([.settings, .rules, .synonyms], to: destinationIndexName) { extract($0) { copyTaskWrapper in destinationIndex.batch(moveOperations) { extract($0) { batchTaskWrapper in destinationIndex.move(to: sourceIndexName) { extract($0) { moveTaskWrapper in let tasks: [IndexedTask] = [ .init(indexName: sourceIndexName, taskID: copyTaskWrapper.task.taskID), .init(indexName: destinationIndexName, taskID: moveTaskWrapper.task.taskID) ] + batchTaskWrapper.wrapped.tasks guard safe else { completion(.success(tasks)) return } let client = SearchClient(appID: self.applicationID, apiKey: self.apiKey) let tasksToWait = tasks.map { Waitable(client: client, task: $0) } WaitableWrapper(wrapped: tasks, tasksToWait: tasksToWait).wait { result in completion(result.map { _ in tasks}) } } } } } } } } /** Push a new set of objects and remove all previous ones. Settings, synonyms and query rules are untouched. Replace all objects in an index without any downtime. Internally, this method copies the existing index settings, synonyms and query rules and indexes all passed objects. Finally, the existing index is replaced by the temporary one. - Parameter requestOptions: Configure request locally with RequestOptions - Returns: [TaskIndex] object */ @discardableResult func replaceAllObjects<T: Encodable>(with objects: [T], autoGeneratingObjectID: Bool = false, requestOptions: RequestOptions? = nil) throws -> [IndexedTask] { let moveOperations: [BatchOperation] = objects.map { .add($0, autoGeneratingObjectID: autoGeneratingObjectID) } let destinationIndexName = IndexName(rawValue: "\(name)_tmp_\(Int.random(in: 0...100000))") let destinationIndex = Index(name: destinationIndexName, transport: transport, operationLauncher: operationLauncher, configuration: configuration) let moveTasks = try destinationIndex.batch(moveOperations).wrapped.tasks return [ .init(indexName: name, taskID: try copy([.settings, .rules, .synonyms], to: destinationIndexName).task.taskID), .init(indexName: destinationIndexName, taskID: try destinationIndex.move(to: name).task.taskID) ] + moveTasks } } extension Index { @discardableResult func internalBatch(_ batchOperations: [BatchOperation], requestOptions: RequestOptions? = nil, completion: @escaping ResultCallback<BatchResponse>) -> Operation & TransportTask { let command = Command.Index.Batch(indexName: name, batchOperations: batchOperations, requestOptions: requestOptions) return execute(command, completion: completion) } @discardableResult func internalBatch(_ batchOperations: [BatchOperation], requestOptions: RequestOptions? = nil) throws -> BatchResponse { let command = Command.Index.Batch(indexName: name, batchOperations: batchOperations, requestOptions: requestOptions) return try execute(command) } }
// // EventsDataManager.swift // Volunteer Opportunity Tracker // // Created by Cindy Zhang on 3/8/18. // Copyright © 2018 Cindy Zhang. All rights reserved. // import Foundation import UIKit import MapKit import CoreLocation import FirebaseDatabase import FirebaseStorage class EventsDataManager { static var sharedInstance = EventsDataManager() //MARK: references to firebase server database & storage let ref = Database.database().reference(withPath: "event-item") let storageRef = Storage.storage().reference() let imagesRef:StorageReference //MARK: arrays of ___ fileprivate var allEvents = [EventObject]() fileprivate var annotations:[EventAnnotation] = [] init(){ imagesRef = storageRef.child("images"); } func getNumberOfItems() -> Int { return allEvents.count } func addEventToDatabase(_ event: EventObject, _ photo: UIImage){ let key = event.name.lowercased() // save info to database let eventItemRef = self.ref.child(key) eventItemRef.setValue(event.toAnyObject()) // save image to storage if let uploadData = UIImagePNGRepresentation(photo){ imagesRef.child(event.key).putData(uploadData, metadata: nil) { (metadata, error) in if error != nil { print(error!) return } if let photoURL = metadata?.downloadURL()?.absoluteString { self.ref.child(key).child("imageURL").setValue(photoURL) } } } } func updateEventSpotsOnDatabase(_ event: EventObject) { let key = event.name.lowercased() let eventItemRef = self.ref.child(key) eventItemRef.child("spotsRemaining").setValue(event.spotsRemaining); eventItemRef.child("spotsTaken").setValue(event.spotsTaken); } func removeEventFromDatabase(_ indexPath: IndexPath){ let event = allEvents[indexPath.row] ref.child(event.key).removeValue() let desertRef = imagesRef.child(event.key) desertRef.delete { error in if let error = error { print ("Uh-oh, an error occurred!", error) } else { print ("deleted image successfully") } } } func getItem(at indexPath: IndexPath) -> EventObject{ return allEvents[indexPath.item] } func updateEvents(finished: @escaping() -> Void) { ref.observeSingleEvent(of: .value, with: { snapshot in var newItems: [EventObject] = [] for item in snapshot.children { if ((item as! DataSnapshot).hasChild("imageURL")){ let event = EventObject(snapshot: item as! DataSnapshot) newItems.append(event) } } self.allEvents = newItems finished() }) } } extension EventsDataManager { // for managing maps func fetchAnnotations(completion: @escaping(_ annotations:[EventAnnotation]) -> ()) { updateEvents { if self.annotations.count > 0 { self.annotations.removeAll() } for e in self.allEvents { let address = e.address let geoCoder = CLGeocoder() geoCoder.geocodeAddressString(address) { (placemarks, error) in guard let placemarks = placemarks, let location = placemarks.first?.location else { print("no location found", error!) return } self.annotations.append(EventAnnotation(title: e.name, locationName: e.location, discipline: "Monument", coordinate: location.coordinate)) completion(self.annotations) } } } } func currentRegion (latDelta:CLLocationDegrees, longDelta:CLLocationDegrees) -> MKCoordinateRegion { guard let item = annotations.first else { return MKCoordinateRegion() } let span = MKCoordinateSpanMake(latDelta, longDelta) return MKCoordinateRegion(center: item.coordinate, span: span) } }
// // SettingViewController.swift // Asoft-Intern-Final-Demo // // Created by Danh Nguyen on 12/30/16. // Copyright © 2016 Danh Nguyen. All rights reserved. // import UIKit class SettingViewController: UIViewController { @IBOutlet weak var settingTableView: UITableView! override func viewDidLoad() { super.viewDidLoad() AppDelegate.shared.homeNavigation.navigationItem.rightBarButtonItem = nil AppDelegate.shared.homeNavigation.navigationItem.hidesBackButton = true if let backButton = AppDelegate.shared.backBarButtonItem { self.navigationItem.leftBarButtonItem = backButton } self.navigationItem.title = AppNavigationTitle.kSettingNavigationTitle self.settingTableView.dataSource = self self.settingTableView.delegate = self self.settingTableView.tableFooterView = UIView(frame: CGRect.zero) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } //#MARK: - UITableView DataSource extension SettingViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{ return AppResourceIdentifiers.kSettingOptionArray.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { switch indexPath.row { case 0, 1: let cell = tableView.dequeueReusableCell(withIdentifier: Constants.kIdentifierSettingTableViewCellHaveSwitch, for: indexPath) as! SettingHaveSwitchTableViewCell cell.optionTextLabel.text = AppResourceIdentifiers.kSettingOptionArray[indexPath.row] cell.switchControl.onTintColor = UIColor.untGreyishBrownSwitch cell.switchControl.tintColor = UIColor.untWatermelon cell.switchControl.layer.cornerRadius = 16 cell.switchControl.backgroundColor = UIColor.untWatermelon if indexPath.row == 0 { cell.switchControl.isOn = true } else { cell.switchControl.isOn = false } cell.selectionStyle = .none return cell default: let cell = tableView.dequeueReusableCell(withIdentifier: Constants.kIdentifierSettingTableViewCellBasic, for: indexPath) cell.textLabel?.text = AppResourceIdentifiers.kSettingOptionArray[indexPath.row] return cell } } } //#MARK: - UITableView Delegate extension SettingViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableView.bounds.height / 10 } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) switch indexPath.row { case 0, 1: let cell = tableView.cellForRow(at: indexPath) as! SettingHaveSwitchTableViewCell cell.switchControl.setOn(!cell.switchControl.isOn, animated: true) default: break } } }
//* /** DataCleanExample Created on 03/05/2021 */ import Foundation import FirebaseAuth import FirebaseFirestore
// // VCMap.swift // STrip // // Created by Carlos Brito on 31/01/16. // Copyright © 2016 Carlos Brito. All rights reserved. // import Cocoa class VCMap: UIViewController { }
// // TopViewController.swift // Xdungeon // // Created by michiharu on 2018/04/26. // Copyright © 2018年 michiharu. All rights reserved. // import UIKit class HomeViewController: UIViewController { @IBAction func playStart(_ sender: UIButton) { section = nil stage = nil mode = nil let game = storyboard!.instantiateViewController(withIdentifier: "ChallengeGame") as! GameViewController game.modalTransitionStyle = .crossDissolve self.present(game, animated: true, completion: nil) } @IBOutlet weak var playStartButton: UIButton! @IBOutlet weak var highScore: UILabel! @IBOutlet weak var stageSelectButton: UIButton! @IBAction func moveToStages(_ sender: UIButton) { let stages = storyboard!.instantiateViewController(withIdentifier: "Stages") stages.modalTransitionStyle = .crossDissolve self.present(stages,animated: true, completion: nil) } @IBOutlet weak var progressBar: UIProgressView! @IBOutlet weak var percent: UILabel! override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white playStartButton.setTitle(NSLocalizedString("start!", comment: ""), for: .normal) stageSelectButton.setTitle(NSLocalizedString("Stage Select", comment: ""), for: .normal) let ud = UserDefaults.standard ud.register(defaults: [u.getKeyForHighScore(): 0]) ud.set(true, forKey: u.getKeyStageCanPlay(1, 1)) ud.register(defaults: [u.getKeyStageComplete(): 0]) let high = ud.integer(forKey: u.getKeyForHighScore()) highScore.text = NSLocalizedString("High Score: ", comment: "") + high.description let complete = ud.integer(forKey: u.getKeyStageComplete()) let rate: Float = Float(complete) / 120 progressBar.progress = rate let per: Int = Int(rate * 100) percent.text = per.description + "%" if per < 100 { playStartButton.isHidden = true; highScore.isHidden = true } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
// // SpotImages.swift // Harvey // // Created by Sean Hart on 8/30/17. // Copyright © 2017 TangoJ Labs, LLC. All rights reserved. // import UIKit class SpotContent { var contentID: String! var spotID: String! var datetime: Date! var type: Constants.ContentType! var lat: Double! var lng: Double! var status: String = "active" var image: UIImage? var imageFilePath: String? var imageDownloading: Bool = false var deletePending: Bool = false convenience init(contentID: String!, spotID: String!, datetime: Date!, type: Constants.ContentType!, lat: Double!, lng: Double!) { self.init() self.contentID = contentID self.spotID = spotID self.datetime = datetime self.type = type self.lat = lat self.lng = lng } }
// // ReviewCollectionViewCell.swift // MovieProject // // Created by MacOSSierra on 3/16/20. // Copyright © 2020 ITI. All rights reserved. // import UIKit class ReviewCollectionViewCell: UICollectionViewCell { @IBOutlet weak var content: UITextView! @IBOutlet weak var author: UILabel! }
// // UploaderCommon.swift // AccountFileTests // // Created by Christopher G Prince on 7/21/20. // @testable import Server import ServerShared import ChangeResolvers import XCTest import ServerAccount import LoggerAPI private enum Errors: Error { case errorLookingUpFile } public struct ExampleComment { static let messageKey = "messageString" public let messageString:String public let id: String public var record:CommentFile.FixedObject { var result = CommentFile.FixedObject() result[CommentFile.idKey] = id result[Self.messageKey] = messageString return result } public var updateContents: Data { return try! JSONSerialization.data(withJSONObject: record) } } public protocol UploaderCommon { var accountManager:AccountManager! {get} var db:Database! {get} func expectation(description: String) -> XCTestExpectation func waitForExpectations(timeout: TimeInterval, handler: XCWaitCompletionHandler?) } enum FileIsInCloudStorageError: Swift.Error { case noFileGroupUUID case failedFileGroupLookup } public extension UploaderCommon { func downloadCommentFile(fileName: String, userId: UserId) -> CommentFile? { guard let cloudStorage = FileController.getCreds(forUserId: userId, userRepo: UserRepository(db), accountManager: accountManager, accountDelegate: nil)?.cloudStorage(mock: MockStorage()) else { XCTFail() return nil } let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: "text/plain") var commentFile: CommentFile? let exp2 = expectation(description: "apply") cloudStorage.downloadFile(cloudFileName: fileName, options: options) { result in switch result { case .success(data: let data, checkSum: _): commentFile = try? CommentFile(with: data) default: XCTFail("\(result)") } exp2.fulfill() } waitForExpectations(timeout: 10, handler: nil) return commentFile } internal func createUploadForTextFile(deviceUUID: String, fileUUID: String, fileGroup: ServerTestCase.FileGroup? = nil, sharingGroupUUID: String, userId: UserId, deferredUploadId: Int64? = nil, updateContents: Data? = nil, uploadCount: Int32 = 1, uploadIndex:Int32 = 1, batchUUID: String, state:UploadState = .vNUploadFileChange, informAllButSelf: Bool? = nil) -> Upload? { let upload = Upload() upload.deviceUUID = deviceUUID upload.fileUUID = fileUUID upload.mimeType = "text/plain" upload.state = state upload.userId = userId upload.updateDate = Date() upload.sharingGroupUUID = sharingGroupUUID upload.uploadContents = updateContents upload.uploadCount = uploadCount upload.uploadIndex = uploadIndex upload.deferredUploadId = deferredUploadId upload.fileGroupUUID = fileGroup?.fileGroupUUID upload.objectType = fileGroup?.objectType upload.batchUUID = batchUUID upload.batchExpiryDate = Date() if let informAllButSelf = informAllButSelf, informAllButSelf { upload.informAllButUserId = userId } let addUploadResult = UploadRepository(db).add(upload: upload, fileInFileIndex: true) guard case .success(let uploadId) = addUploadResult else { return nil } upload.uploadId = uploadId return upload } func createDeferredUpload(userId: UserId, fileGroupUUID: String? = nil, sharingGroupUUID: String, batchUUID: String?, status: DeferredUploadStatus) -> DeferredUpload? { let deferredUpload = DeferredUpload() deferredUpload.fileGroupUUID = fileGroupUUID deferredUpload.status = status deferredUpload.sharingGroupUUID = sharingGroupUUID deferredUpload.userId = userId deferredUpload.batchUUID = batchUUID let addResult = DeferredUploadRepository(db).add(deferredUpload) guard case .success(deferredUploadId: let deferredUploadId) = addResult else { return nil } deferredUpload.deferredUploadId = deferredUploadId return deferredUpload } func getFileIndex(fileUUID: String) -> FileIndex? { let key = FileIndexRepository.LookupKey.primaryKey(fileUUID: fileUUID) let lookupResult = FileIndexRepository(db).lookup(key: key, modelInit: FileIndex.init) guard case .found(let model) = lookupResult, let fileIndex = model as? FileIndex else { return nil } return fileIndex } // Download the comment file and check it against the expectedCommentFile. func checkCommentFile(expectedComment: ExampleComment, recordIndex: Int = 0, recordCount: Int = 1, fileVersion: FileVersionInt = 1, deviceUUID: String, fileUUID: String, userId: UserId) -> Bool { let fileName = Filename.inCloud(deviceUUID: deviceUUID, fileUUID: fileUUID, mimeType: "text/plain", fileVersion: fileVersion) guard let commentFile = downloadCommentFile(fileName: fileName, userId: userId) else { XCTFail() return false } guard commentFile.count == recordCount else { XCTFail() return false } guard let record = commentFile[recordIndex] else { XCTFail() return false } guard record[CommentFile.idKey] as? String == expectedComment.id else { XCTFail() return false } guard record["messageString"] as? String == expectedComment.messageString else { XCTFail() return false } return true } func fileIsInCloudStorage(fileIndex: FileIndex, services: UploaderServices) throws -> Bool { var boolResult: Bool = false guard let fileGroupUUID = fileIndex.fileGroupUUID else { throw FileIsInCloudStorageError.noFileGroupUUID } let exp2 = expectation(description: "run") guard let fg = try? FileGroupRepository(db).getFileGroup(forFileGroupUUID: fileGroupUUID) else { throw FileIsInCloudStorageError.failedFileGroupLookup } // Need to make sure the file has been removed from cloud storage. let (_, cloudStorage) = try UserRepository(db).getCloudStorage(owningUserId: fg.owningUserId, services: services) let cloudFileName = Filename.inCloud(deviceUUID: fileIndex.deviceUUID, fileUUID: fileIndex.fileUUID, mimeType: fileIndex.mimeType, fileVersion: fileIndex.fileVersion) let options = CloudStorageFileNameOptions(cloudFolderName: ServerTestCase.cloudFolderName, mimeType: fileIndex.mimeType) var error: Error? cloudStorage.lookupFile(cloudFileName: cloudFileName, options: options) { result in switch result { case .success(let found): boolResult = found Log.debug("cloudStorage.lookupFile: \(found)") default: error = Errors.errorLookingUpFile } exp2.fulfill() } waitForExpectations(timeout: 10, handler: nil) if let resultError = error { throw resultError } return boolResult } }
// // UIColor+Theme.swift // CornerJudgeTrainer // // Created by Maya Saxena on 8/26/16. // Copyright © 2016 Maya Saxena. All rights reserved. // import UIKit extension UIColor { // class var flatBlue: UIColor { // return // } static let flatBlue = UIColor(red: 54.0 / 255.0, green: 108.0 / 255.0, blue: 172.0 / 255.0, alpha: 1.0) class var flatRed: UIColor { return UIColor(red: 186.0 / 255.0, green: 65.0 / 255.0, blue: 65.0 / 255.0, alpha: 1.0) } class var flatBlack: UIColor { return UIColor(white: 39.0 / 255.0, alpha: 1.0) } class var flatWhite: UIColor { return UIColor(white: 246.0 / 255.0, alpha: 1.0) } class var penaltyGold: UIColor { return UIColor(red: 255.0 / 255.0, green: 208.0 / 255.0, blue: 70.0 / 255.0, alpha: 1.0) } class var penaltyRed: UIColor { return UIColor(red: 150.0 / 255.0, green: 2.0 / 255.0, blue: 0.0, alpha: 1.0) } class var darkGrey: UIColor { return UIColor(white: 62.0 / 255.0, alpha: 1.0) } static let textFieldBackground = UIColor.flatBlue }
// // 演算子.swift // swift.sintax // // Created by 鳥嶋晃次 on 2019/09/23. // Copyright © 2019 鳥嶋晃次. All rights reserved. // /* 演算子 + +a aの値 - -a -aの正負を反転した値 + a + b 加算 - a - b 減算 * a * b 掛け算 / a / b 割り算 % a % b 余り */ let a = 1 + 3 * 2 // 7 let b = 10 / (4 - 2) // ()が優先 5 let c = 5 % 3 // 5割る3の余りが2 つまり2が出力 2 let d = -11 % 4 // -3 print ((a,b,c,d)) //タプルで出力 //整数計算の注意点 let ans1 = 3 + (10/4) // 整数計算しているので整数でを足しているため出力は5 実際は5.5 print(ans1)//5 /* 10/4 の結果が2.5になるには、 定数 ans1 の型を let ans1: Double にするか 3.0 のように、式に含まれている最低1個の数値を浮動小数点にする */ let ans2:Double = 3 + (10/4) print(ans2) // 5.5 let ans3 = 3.0 + (10/4) print(ans3) // 5.5 /* 論理演算子 && , || , ! Bool型の値(trueまたはfalse) の演算を行うのが理論演算子 結果はtrue または false のいずれかになる !演算子は !a のように空白を詰めて書く */ let s = true let w = false let and = s && w let or = s || w let not = !s print((and,or,not)) // (false, true, false) /* 比較演算子 > a > b aの方がbより大き時true < a < b aの方がbより小さい時true >= a >= b aはb以上(bを含む)時 true <= a <= b aはb以下(bを含む)時 true == a == b aとbが等しい時 true != a != b aとbが等しくない時 true */ /* 代入演算子   = a = b aにbの値を代入 */ var n = 100 let m = n //100 n = n + 1 //101 print(n , m) // 101 100 /* 複合代入演算子 += a += b aにbを足した値をaに代入 -= a -= b aからbを引いた値をaに代入 *= a *= b aにbをかけた値をaに代入 /= a /= b aをbで割った値をaに代入 %= a %= b aをbで割った余りをaに代入 &&= a &&= b aとbの論理積の値をaに代入 ||= a ||= b aとbの論理和の値をaに代入 */ var q = 1 var f = 3 q += 1 // 1を加算 f *= 2 // 2倍 print((q,f)) //(2,6) /* 三項演算子 ? : 条件式 ? trueの場合の式 : falseの場合の式 */ let aa = 33 let bb = 22 let bigger1 = (aa>bb) ? aa : bb // aaの方が大きければaa , そうでなけれbbを代入 print("aaは\(aa), bbは\(bb), bigger1は\(bigger1)") // aaは33, bbは22, biggerは33 // if の場合 let cc = 33 let dd = 22 var bigger2: Int if cc > dd { bigger2 = cc } else { bigger2 = dd } print("ccは\(cc), ddは\(dd), bigger2は\(bigger2)") // ccは33, ddは22, bigger2は33 /* レンジ演算子 ..< , ... 開始値 ..< 終了値 (終了値は含まない) 開始値 ... 終了値 (終了値は含む) 数値が範囲内にあるかどうかを調べる contains()でチェックできる */ // 整数の範囲 let rengeInt = -5 ..< 5 print(rengeInt.contains(-3)) // true print(rengeInt.contains(2)) // true print(rengeInt.contains(5)) // false print("------------------") // 実数の範囲 let rengeDouble = 0.0 ... 1.0 print(rengeDouble.contains(0.1)) // true print(rengeDouble.contains(1.0)) // true print(rengeDouble.contains(1.5)) // false //true //true //false // ------------------ //true //true //false /* ビット演算子 << . >> . & . | . ^ . ~ むずい 2進数や16進数の値を扱う演算子 2進数の値は0b1111のように 接頭辞に0b(ゼロと小文字b)をつける 16進数の値はOxFFFFFFのように 接頭辞に0x(ゼロと小文字x)をつける orint(0xFF)のように出力すると 10進数に換算された255が出力する ビットシフト 数値を2進数で表現した時、指定した方向に桁をシフトする演算 10進数の数値を左へ一桁シフトする(例えば25を250にする)と値が10倍になるように 2進数の値を左へ1桁シフトすると値が2倍になる 左へ2桁シフトすると4倍になる << a << b aを左へb行シフトする >> a >> b aを右へb行シフトする */ let v:UInt8 = 0b00000101 let v2 = v << 1 print(v, v2) //
// // EraseViewController.swift // AppliTest // // Created by GUERNEVÉ Sébastien on 23/10/2020. // Copyright © 2020 GUERNEVÉ Sébastien. All rights reserved. // import UIKit class EraseViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var erasedMailTableView: UITableView! let _ERASED_MAIL = eraseMail() func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return _ERASED_MAIL.count() } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell_errase_mail", for: indexPath) if let textLabel = cell.textLabel { textLabel.text = _ERASED_MAIL.getListEraseMail(at: indexPath.row) } return cell } override func viewDidLoad() { super.viewDidLoad() erasedMailTableView.dataSource = self } }
/* File Browser for Swift Playgrounds */ import UIKit import QuickLook import PlaygroundSupport class FBFilesTableViewController : UITableViewController, QLPreviewControllerDataSource { var files = Array<String>() var path = "/" required init(path: String) { super.init(style: .plain) self.title = (path as NSString).lastPathComponent do { self.files = try FileManager.default.contentsOfDirectory(atPath: path) } catch _ { if path == "/System" { self.files = ["Library"] } } let label = NSString(format: "%lu items", self.files.count) let itemCountBarItem = UIBarButtonItem(title: label as String, style: .plain, target: nil, action: nil) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) self.setToolbarItems([flexibleSpace, itemCountBarItem, flexibleSpace], animated: false) self.path = path self.tableView.register(UITableViewCell.classForCoder(), forCellReuseIdentifier: "cell") } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 72 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return files.count } override func numberOfSections(in tableView: UITableView) -> Int { return 1 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let files = self.files let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) var newPath : NSString = (self.path as NSString).appendingPathComponent(files[indexPath.row]) as NSString cell.textLabel?.text = newPath.lastPathComponent cell.imageView?.tintColor = UIColor(colorLiteralRed: 0.565, green: 0.773, blue: 0.961, alpha: 1.0) var isDirectory = ObjCBool(false) FileManager.default.fileExists(atPath:newPath as String, isDirectory: &isDirectory) if isDirectory.boolValue { cell.imageView?.image = UIImage(named: "Folder") } else if (newPath as NSString).pathExtension == "png" { cell.imageView?.image = UIImage(named: "Picture") } else { cell.imageView?.image = UIImage(named: "Document") } return cell } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let files = self.files var newPath = self.path as NSString newPath = newPath.appendingPathComponent(files[indexPath.row]) as NSString var isDirectory = ObjCBool(false) FileManager.default.fileExists(atPath:newPath as String, isDirectory: &isDirectory) if isDirectory.boolValue { let tableVC = FBFilesTableViewController(path:newPath as String) self.navigationController?.pushViewController(tableVC, animated: true) } else { let previewVC = QLPreviewController() previewVC.dataSource = self self.navigationController?.pushViewController(previewVC, animated: true) } } func numberOfPreviewItems(in controller: QLPreviewController) -> Int { return 1 } func previewController(_ controller: QLPreviewController, previewItemAt index: Int) -> QLPreviewItem { let files = self.files var newPath = self.path as NSString newPath = newPath.appendingPathComponent(files[self.tableView.indexPathForSelectedRow!.row]) as NSString return URL(fileURLWithPath: newPath as String) as QLPreviewItem } } let tableVC = FBFilesTableViewController(path:"/") let navVC = UINavigationController(rootViewController: tableVC) navVC.isToolbarHidden = false let window = UIWindow() window.rootViewController = navVC window.makeKeyAndVisible() window.autoresizingMask = [.flexibleHeight,.flexibleWidth] PlaygroundPage.current.liveView = window
// // ServiceResolver.swift // countit // // Created by David Grew on 02/02/2019. // Copyright © 2019 David Grew. All rights reserved. // import Foundation class ServiceResolver { private let repositoryResolver: RepositoryResolver private let clock: Clock private let calendar: Calendar private let properties: Properties private let messageBroker: MessageBroker private var itemService: ItemService? private var activityService: ActivityService? private var progressService: ProgressService? private var userInstructionService: UserInstructionService init(repositoryResolver: RepositoryResolver, clock: Clock, calendar: Calendar, properties: Properties, messageBroker: MessageBroker) { self.repositoryResolver = repositoryResolver self.clock = clock self.calendar = calendar self.properties = properties self.messageBroker = messageBroker self.userInstructionService = UserInstructionServiceImpl(messageBroker: messageBroker, properties: properties) } func getItemService() -> ItemService { if itemService != nil { return itemService! } else { itemService = ItemServiceImpl(itemRepository: repositoryResolver.getItemRepository(), messageBroker: messageBroker, clock: clock) return itemService! } } func getActivityService() -> ActivityService { if activityService != nil { return activityService! } else { activityService = ActivityServiceImpl(activityRepository: repositoryResolver.getActivityRepository(), clock: clock, calendar: calendar) return activityService! } } func getProgressService() -> ProgressService { if progressService != nil { return progressService! } else { progressService = ProgressServiceImpl(itemService: getItemService(), activityService: getActivityService(), calendar: calendar, clock: clock) return progressService! } } }
// // ViewController.swift // TNL // // Created by Gabriel Schmit Dall Agnol on 23/01/20. // Copyright © 2020 Gabriel Schmit Dall Agnol. All rights reserved. // import UIKit class LandingViewController: UIViewController { // MARK: Outlets @IBOutlet weak var backgroundView: UIView! { didSet { backgroundView.backgroundColor = UIColor.darkBlueGrey } } @IBOutlet weak var backgroundImage: UIImageView! { didSet { backgroundImage.image = UIImage(named: "fill1") } } @IBOutlet weak var logoImage: UIImageView! { didSet { logoImage.image = UIImage(named: "logo") } } @IBOutlet weak var termsLabel: UILabel! { didSet { let attributedString = NSMutableAttributedString(string: "By using TNL, you agree to our Terms of Use and Privacy Policy", attributes: [ .font: UIFont.systemFont(ofSize: 14.0, weight: .regular), .foregroundColor: UIColor.white ]) attributedString.addAttributes([ .font: UIFont.systemFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.whiteTwo ], range: NSRange(location: 31, length: 12)) attributedString.addAttributes([ .font: UIFont.systemFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.whiteTwo ], range: NSRange(location: 48, length: 14)) termsLabel.attributedText = attributedString termsLabel.textAlignment = .center termsLabel.numberOfLines = 0 termsLabel.lineBreakMode = .byWordWrapping termsLabel.adjustsFontSizeToFitWidth = true let labelTap = UITapGestureRecognizer(target: self, action: #selector(self.termsAndPrivacyGestureRecognizer(gesture:))) self.termsLabel.isUserInteractionEnabled = true self.termsLabel.addGestureRecognizer(labelTap) } } @IBOutlet weak var registerButton: UIButton! { didSet { registerButton.addTarget( self, action: #selector(tappedRegisterButton), for: .touchUpInside ) let attributedString = NSMutableAttributedString(string: "Register", attributes: [ .font: UIFont.systemFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.whiteTwo ]) registerButton.setAttributedTitle(attributedString, for: .normal) registerButton.backgroundColor = UIColor.turquoiseBlue registerButton.layer.cornerRadius = registerButton.frame.height / 2 } } @IBOutlet weak var loginButton: UIButton! { didSet { loginButton.addTarget( self, action: #selector(tappedLoginButton), for: .touchUpInside ) let attributedString = NSMutableAttributedString(string: "Log in", attributes: [ .font: UIFont.systemFont(ofSize: 14.0, weight: .bold), .foregroundColor: UIColor.whiteTwo ]) loginButton.setAttributedTitle(attributedString, for: .normal) loginButton.backgroundColor = UIColor.white16 loginButton.layer.cornerRadius = loginButton.frame.height / 2 } } // MARK: Override override func viewDidAppear(_ animated: Bool) { navigationController?.navigationBar.barStyle = .black self.navigationController?.navigationBar.isHidden = true } override func viewDidLoad() { super.viewDidLoad() } } // MARK: Extension ViewController private extension LandingViewController { @objc func termsAndPrivacyGestureRecognizer(gesture: UITapGestureRecognizer) { if gesture.didTapAttributedTextInLabel(label: termsLabel, inRange: NSRange(location: 31, length: 12)) { let viewController = SimpleNotificationViewController() viewController.titleModal = "Terms of Use" viewController.descriptionInfo = "You are allowed to use <b>if you promisse tell about this app to all your friends</b>.<br>" viewController.titleButton = "ALL RIGHT" viewController.modalPresentationStyle = .overCurrentContext present(viewController, animated: false, completion: nil) } else if gesture.didTapAttributedTextInLabel(label: termsLabel, inRange: NSRange(location: 48, length: 14)) { let viewController = SimpleNotificationViewController() viewController.titleModal = "Privacy Policy" viewController.descriptionInfo = "<br>In Pregress. <br><br>But stay cool, <b>your privacy it's garanted</b>.<br>" viewController.titleButton = "AMAZING" viewController.modalPresentationStyle = .overCurrentContext present(viewController, animated: false, completion: nil) } } @objc func tappedLoginButton() { let viewModel = LoginViewModel() let viewController = LoginViewController(viewModel: viewModel) self.navigationController!.pushViewController(viewController, animated: true) } @objc func tappedRegisterButton() { let viewController = SimpleNotificationViewController() viewController.titleModal = "Ops..." viewController.descriptionInfo = "This feature still in development. <br><br>But fell free to <b>Login</b>, read our <b>Terms of Use</b> or give a look in the <b>Privacy Policy</b>." viewController.titleButton = "OK" viewController.modalPresentationStyle = .overCurrentContext present(viewController, animated: false, completion: nil) } }
// // CurrentWeather.swift // Stormy // // Created by Henry Moran on 8/21/18. // Copyright © 2018 Treehouse. All rights reserved. // import Foundation import UIKit //Struct as data model // Model the data from the Dark Sky API docs struct CurrentWeather { let temperature: Double let humidity: Double let precipProbability: Double let summary: String let icon: String } // This extension is being used to convert a String from the API to an image using the icon name in the asset folder extension CurrentWeather { var iconImage: UIImage { switch icon { case "clear-day": return #imageLiteral(resourceName: "clear-day") case "clear-night": return #imageLiteral(resourceName: "clear-night") case "rain": return #imageLiteral(resourceName: "rain") case "snow": return #imageLiteral(resourceName: "snow") case "sleet": return #imageLiteral(resourceName: "sleet") case "wind": return #imageLiteral(resourceName: "wind") case "fog": return #imageLiteral(resourceName: "fog") case "cloudy": return #imageLiteral(resourceName: "cloudy") case "partly-cloudy-day": return #imageLiteral(resourceName: "partly-cloudy") case "partly-cloud-night": return #imageLiteral(resourceName: "partly-cloudy-night") default: return #imageLiteral(resourceName: "default") } } }
// // KeyspaceDrop.swift // scale // // Created by Adrian Herridge on 17/04/2017. // // import Foundation import SWSQLite class KeyspaceDrop { init(_ request: Request, params: KeyspaceParams) { // look to see if this keyspace already exists, if it does throw an error if !Keyspace.Exists(params.keyspace) { request.setError("Keyspace with name '\(params.keyspace)' does not exist. Unable to drop.") return } let key = Keyspace.Get(params.keyspace) _ = sys.write((key?.Delete())!) let schemaChanges = KeyspaceSchema.ToCollection(sys.read(sql: "SELECT * FROM KeyspaceSchema WHERE keyspace = ?", params: [params.keyspace]).results) for ks in schemaChanges { _ = sys.write(ks.Delete()) } // now lock all the shards, and delete everything associated with this keyspace Shards.DeleteShardsForKeyspace(params.keyspace) } }
import Cocoa // part two of Ab Fab: Classes class Shape: CustomStringConvertible { // enumerates stored properties var centerX: Double; var centerY: Double var isSolid: Bool // defines computed type read-only var quadrant: Int { // postulating centers don't lie on axis grids if centerX == 0 || centerY == 0 { return -1 } else if centerX > 0 && centerY > 0 { return 0 // quadrant 0 } else if centerX > 0 { // centerY is less than 0 return 3 // quadrant three } else if centerY > 0 { // centerX is less than 0 return 1 } else{ return 2 // both centers are negative } } var description: String { return("centerX: \(centerX) centerY: \(centerY) isSolid: \(isSolid)") } // denoting inits init(centerX: Double, centerY: Double, isSolid: Bool){ self.centerX = centerX self.centerY = centerY self.isSolid = isSolid } convenience init(centerX: Double, centerY: Double){ self.init(centerX: centerX, centerY: centerY, isSolid: false) } convenience init(){ self.init(centerX: 0.0, centerY: 0.0, isSolid: false) } // defining functionality // func to print out "I am a shape" func draw(){ print("I am a shape") } // function to amend the values of the centerpoint func translate(deltaX: Int, deltaY: Int) { // doesn't need mutating for its a reference type centerX += Double(deltaX) centerY += Double(deltaY) } // function to flip center point according to referenced axis func flip(axis: Character) { if axis == "x" || axis == "X"{ // flip on x-axis centerY *= Double(-1) } else if axis == "y" || axis == "Y"{ // flip on y-axis centerX *= Double(-1) } else{ // invalid char inputted return } } // function to return perimeter func perimeter() -> Double { return 0.0 } // function to return area func area() -> Double { return 0.0 } } // defining a subclass Rectangle class Rectangle: Shape{ // enumerating stored properties var width: Double; var height: Double // defining read only computed properties var isSquare: Bool { return width == height ? true : false } override var description: String { // don't need to reconform to protocol, just override return "\(super.description) width: \(width) height: \(height)" } // inits defined init(centerX: Double, centerY: Double, isSolid: Bool, height: Double, width: Double){ self.height = height self.width = width super.init(centerX: centerX, centerY: centerY, isSolid: isSolid) } convenience init(height: Double, width: Double){ self.init(centerX: 0.0, centerY: 0.0, isSolid: false, height: height, width: width) } convenience init(){ self.init(centerX: 0.0, centerY: 0.0, isSolid: false, height: 0.0, width: 0.0) } // listing various behaviours of Rectangle // overriden method to print state override func draw(){ print("I am a rectangle \(super.draw())") } // function to determine if set of coordinates reside within rectangle func contains(x: Double, y: Double) -> Bool{ return abs(centerX - x).isLessThanOrEqualTo(width) && abs(centerY - y).isLessThanOrEqualTo(height) ? true : false } // function to return perimeter override func perimeter() -> Double { return (width*2) + (height*2) } // function to return area override func area() -> Double { return width * height } } // declared an array of shapes var sketchpad: [Shape] = [Shape(), Shape(centerX:25.0, centerY: 25.0), Shape(centerX: 30, centerY: -15.0, isSolid: true), Rectangle(), Rectangle(height: 100.0, width: 50.0), Rectangle(centerX: -25.0, centerY: -35.0, isSolid: true, height: 250.0, width: 250.0)] // function to print out average perimeter func averagePerimeter(shapeCollection: [Shape]) { var averagePer: Double = 0 for shape in shapeCollection { averagePer += shape.perimeter() } print(averagePer/Double(shapeCollection.count)) } averagePerimeter(shapeCollection: sketchpad) func smallestArea(shapeCollection: [Shape]) { var smallestArea: Double = 0 for i in stride(from: 2, to: sketchpad.count, by: 2){ if i == 2{ smallestArea = sketchpad[i].area() } else if smallestArea > sketchpad[i].area() { smallestArea = sketchpad[i].area() } } print("smallest area is: \(smallestArea)") } smallestArea(shapeCollection: sketchpad) func translation(shapeCollection: [Shape]){ for i in 0 ..< shapeCollection.count{ if i <= 2 { shapeCollection[i].flip(axis: "x") } else{ shapeCollection[i].flip(axis: "y") } } } translation(shapeCollection: sketchpad) func firstLastQuadrant(shapeCollection: [Shape]) { print("First element's quadrant: \(shapeCollection[0].quadrant). Last element's quadrant: \(shapeCollection[shapeCollection.count - 1].quadrant)") } firstLastQuadrant(shapeCollection: sketchpad) func randomShift(shapeCollection: [Shape]) { print("\nBefore shift") for shape in shapeCollection.reversed(){ print("new locations X: \(shape.centerX) Y: \(shape.centerY)") } for shape in shapeCollection{ shape.centerX += Double.random(in: -100...100) shape.centerY += Double.random(in: -100...100) } print("\nAfter shift") for shape in shapeCollection.reversed(){ print("new locations X: \(shape.centerX) Y: \(shape.centerY)") } } randomShift(shapeCollection: sketchpad)
// // WebErrorView.swift // Sohulc // // Created by 李博武 on 2018/10/25. // Copyright © 2018年 linjing. All rights reserved. // import UIKit class WebErrorView: UIView { @IBOutlet weak var navView: UIView! @IBOutlet weak var navViewHeight: NSLayoutConstraint! @IBOutlet weak var errorImage: UIImageView! @IBOutlet weak var tipTitle: UILabel! @IBOutlet weak var tipDes: UILabel! @IBOutlet weak var refreshBtn: UIButton! var ConnectView:UIView! var buttonCallBack:(() -> ())? override init(frame: CGRect) { super.init(frame: frame) ConnectView = loadViewFromNib() addSubview(ConnectView) addConstraints() initialSetup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) ConnectView = loadViewFromNib() addSubview(ConnectView) addConstraints() initialSetup() } func loadViewFromNib() -> UIView { let className = type(of: self) let bundle = Bundle(for: className) let name = NSStringFromClass(className).components(separatedBy: ".").last let nib = UINib(nibName: name!, bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView return view } func addConstraints() { ConnectView.translatesAutoresizingMaskIntoConstraints = false var constraint = NSLayoutConstraint(item: ConnectView, attribute: .leading, relatedBy: .equal, toItem: self, attribute: .leading, multiplier: 1, constant: 0) addConstraint(constraint) constraint = NSLayoutConstraint(item: ConnectView, attribute: .trailing, relatedBy: .equal, toItem: self, attribute: .trailing, multiplier: 1, constant: 0) addConstraint(constraint) constraint = NSLayoutConstraint(item: ConnectView, attribute: .top, relatedBy: .equal, toItem: self, attribute: .top, multiplier: 1, constant: 0) addConstraint(constraint) constraint = NSLayoutConstraint(item: ConnectView, attribute: .bottom, relatedBy: .equal, toItem: self, attribute: .bottom, multiplier: 1, constant: 0) addConstraint(constraint) } //初始化默认属性配置 func initialSetup(){ self.layoutIfNeeded() self.setNeedsLayout() errorImage.image = UIImage(named: "web_error") tipTitle.text = "网络正在开小差~" tipDes.text = "数据加载失败,请稍后再试!" refreshBtn.layer.contents = UIImage(named: "web_refresh_btn")?.cgImage refreshBtn.contentMode = .scaleToFill refreshBtn.layer.cornerRadius = 3 //iphoneX及有刘海的机型 if #available(iOS 11.0, *) { if (screenH >= 812) { navHeight = Int(UIApplication.shared.statusBarFrame.height) + 44 } } if self.navViewHeight != nil { navView.removeConstraint(self.navViewHeight) navView.snp.remakeConstraints { (make) in make.height.equalTo(CGFloat(navHeight)) } } navView.layer.contents = UIImage(named: "nav_bar_bg")?.cgImage navView.contentMode = .scaleToFill } @IBAction func RefreshAction(_ sender: Any) { if buttonCallBack != nil { buttonCallBack!() } } }
// // HomeViewController.swift // GotHealthy // // Created by Josh Rosenzweig on 3/29/17. // Copyright © 2016 Volt. All rights reserved. // import UIKit import CoreData import CoreMotion import QuartzCore class HomeViewController: UIViewController { var managedObjectContext: NSManagedObjectContext? var sharedDefaults: UserDefaults! = UserDefaults(suiteName: defaultsSuiteName) let defaults = UserDefaults.standard var distanceAdd = 0.00 var totalDistance = 0.00 let inset: CGFloat = 15.0 @IBOutlet weak var daysLeftLabel: UILabel! @IBOutlet weak var totalDistanceLabel: UILabel! @IBOutlet weak var progressView: UIProgressView! @IBOutlet weak var stepCountLabel: UILabel! @IBOutlet weak var distanceLabel: UILabel! @IBAction func newRunButtonPressed(_ sender: AnyObject) { let detailViewController = storyboard?.instantiateViewController(withIdentifier: "RunSetupViewController") as! RunSetupViewController navigationController?.pushViewController(detailViewController, animated: true) } override func viewDidLoad() { super.viewDidLoad() UIApplication.shared.statusBarStyle = .lightContent //addWidget() totalDistance = UserDefaults.standard.double(forKey: "Total Miles") if (defaults.object(forKey: "Final Distance") as? Double) != nil { distanceAdd = (defaults.object(forKey: "Final Distance") as? Double)! } if distanceAdd > 0 { if totalDistance <= 100.00{ totalDistance += Double(String(format: "%.2f", distanceAdd))! defaults.set(totalDistance, forKey: "Total Miles") UserDefaults.standard.setValue(0.00, forKey: "Final Distance") } else{ totalDistance += distanceAdd defaults.set(totalDistance, forKey: "Total Miles") UserDefaults.standard.setValue(0.00, forKey: "Final Distance") } } totalDistanceLabel.text = "\(defaults.double(forKey: "Total Miles"))" let tap: UITapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(HomeViewController.dismissKeyboard)) view.addGestureRecognizer(tap) // Set user defaults if userGoal == 0 { userGoal = 10_000 } // Progress view appearance progressView.layer.cornerRadius = 8.0 progressView.layer.masksToBounds = true } func dismissKeyboard() { view.endEditing(true) } // Defines intervals for progress bar color let StepCountIntervalLow = Float(0)...Float(0.4) let StepCountIntervalMed = Float(0.4)...Float(0.8) var unitSystemType: UnitSystem? { get { let raw = sharedDefaults.integer(forKey: UnitTypeKey) return UnitSystem(rawValue: raw) } set { sharedDefaults.set(newValue!.rawValue, forKey: UnitTypeKey) updateInterface() } } var unitDisplayType: UnitDisplay? { get { let raw = sharedDefaults.integer(forKey: UnitDisplayKey) return UnitDisplay(rawValue: raw) } set { sharedDefaults.set(newValue!.rawValue, forKey: UnitDisplayKey) updateInterface() } } var userGoal: Float { get { return sharedDefaults.float(forKey: UserGoalKey) } set { sharedDefaults.set(newValue, forKey: UserGoalKey) updateInterface() } } var unitSystemWord: String { switch (unitSystemType!) { case .imperial: switch (unitDisplayType!) { case .short: return UnitSystemImperialWordShort case .long: return UnitSystemImperialWord } case .metric: switch (unitDisplayType!) { case .short: return UnitSystemMetricWordShort case .long: return UnitSystemMetricWord } } } // Pedometer var stepCount: Int var distance: Double var pedometer: CMPedometer // MARK: - Initializers init() { stepCount = 0 distance = 0.0 pedometer = CMPedometer() sharedDefaults = UserDefaults(suiteName: defaultsSuiteName)! super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { stepCount = 0 distance = 0.0 pedometer = CMPedometer() sharedDefaults = UserDefaults(suiteName: defaultsSuiteName)! super.init(coder: aDecoder) } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) // Read from user defaults to show while updating data stepCount = sharedDefaults.integer(forKey: StepCountKey) distance = sharedDefaults.double(forKey: DistanceKey) // Update interface before updateInterface() updatePedometer() NotificationCenter.default.addObserver(self, selector: #selector(TodayViewController.updateInterface), name: UserDefaults.didChangeNotification, object: nil) } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) sharedDefaults.set(stepCount, forKey: StepCountKey) sharedDefaults.set(distance, forKey: DistanceKey) sharedDefaults.synchronize() NotificationCenter.default.removeObserver(self) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { navigationItem.title = nil if segue.identifier == "RunSetup"{ let vc = segue.destination as UIViewController vc.navigationItem.title = "Run" navigationItem.title = "Home" } } // MARK: - Widget func updatePedometer () { // Ensure device has motion coprocessor if CMPedometer.isStepCountingAvailable() { // Get data from midnight to now pedometer.queryPedometerData(from: Date.midnight, to: Date(), withHandler: { data, error in if data != nil { // Store data self.stepCount = data!.numberOfSteps.intValue if CMPedometer.isDistanceAvailable() { self.distance = data!.distance!.doubleValue } self.updateInterface() } // Update as user moves self.pedometer.startUpdates(from: Date(), withHandler: { data, error in if data != nil { // Add to existing counts self.stepCount += data!.numberOfSteps.intValue if CMPedometer.isDistanceAvailable() { self.distance += data!.distance!.doubleValue } self.updateInterface() } }) }) } } func updateInterface () { DispatchQueue.main.async(execute: { // Update step count label, format nicely if self.stepCount < 10_000 { self.stepCountLabel.text = "\(self.stepCount)" } else { let number = NSNumber(value: self.stepCount as Int) let formatter = NumberFormatter() formatter.numberStyle = .decimal formatter.groupingSeparator = "," self.stepCountLabel.text = formatter.string(for: number) } }); // Update distance label if available if CMPedometer.isDistanceAvailable() { // Update mile count label var convertedDistance = self.distance switch self.unitSystemType! { case .imperial: convertedDistance /= mileInMeters case .metric: convertedDistance /= 1000 } let distanceExtension = (self.unitDisplayType == .long && self.distance != 1) ? "s" : "" DispatchQueue.main.async(execute: { self.distanceLabel.isHidden = false self.distanceLabel.text = NSString(format: "%.2f %@%@", convertedDistance, self.unitSystemWord, distanceExtension) as String }); } else { DispatchQueue.main.async(execute: { self.distanceLabel.isHidden = true }); } // Update progress indicator let percent = min(Float(self.stepCount) / Float(self.userGoal), 1.0) self.progressView.setProgress(percent, animated: false) switch percent { case StepCountIntervalLow: self.progressView.progressTintColor = UIColor.red case StepCountIntervalMed: self.progressView.progressTintColor = UIColor.yellow default: self.progressView.progressTintColor = UIColor.green } } }
// // FeaturedSectionController.swift // iFlixDemo // // Created by Wahyu Sumartha on 19/03/2017. // Copyright © 2017 Wahyu Sumartha . All rights reserved. // import IGListKit import SDWebImage class FeaturedSectionController: IGListSectionController { var movie: Movie? override init() { super.init() } } extension FeaturedSectionController: IGListSectionType { func numberOfItems() -> Int { return 1 } func sizeForItem(at index: Int) -> CGSize { if let width = collectionContext?.containerSize.width { return CGSize(width: width, height: 200) } else { return .zero } } func cellForItem(at index: Int) -> UICollectionViewCell { let cell = collectionContext?.dequeueReusableCell(withNibName: "FeaturedCollectionViewCell", bundle: nil, for: self, at: index) as! FeaturedCollectionViewCell if let posterPath = movie?.posterPath { var posterImage = PosterImage() posterImage.posterSize = "original" cell.imageView.sd_setImage(with: posterImage.getImageUrl(from: posterPath), completed: nil) } return cell } func didUpdate(to object: Any) { movie = object as? Movie } func didSelectItem(at index: Int) { } }
// // EmoticonViewController.swift // MGWeiBo2 // // Created by MGBook on 2020/9/23. // Copyright © 2020 穆良. All rights reserved. // import UIKit private let EmoticonCellId = "EmoticonCellId" class EmoticonViewController: UIViewController { private lazy var manager = EmoticonManager() private lazy var collectionView: UICollectionView = UICollectionView(frame: .zero, collectionViewLayout: EmoticonCollectionViewLayout()) private lazy var toolBar: UIToolbar = UIToolbar() /// 点击表情回调闭包 var callback: (_ emoticon: Emoticon)->() init(emoticonCallBack: @escaping (_ emoticon: Emoticon)->()) { self.callback = emoticonCallBack super.init(nibName: nil, bundle: nil) } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewDidLoad() { super.viewDidLoad() setupUI() prepareForCollectionView() prepareForToolBar() } } //MARK:- UI界面相关 extension EmoticonViewController { private func setupUI() { // 1.添加子控件 view.addSubview(collectionView) view.addSubview(toolBar) // 2.设置子控件frame collectionView.translatesAutoresizingMaskIntoConstraints = false toolBar.translatesAutoresizingMaskIntoConstraints = false let views: [String : Any] = ["cView": collectionView, "tBar": toolBar] var cons = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[cView]-0-|", options: [], metrics: nil, views: views) cons += NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tBar]-0-|", options: [], metrics: nil, views: views) cons += NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[cView]-[tBar]-0-|", options: [], metrics: nil, views: views) view.addConstraints(cons) } private func prepareForCollectionView() { collectionView.backgroundColor = UIColor.white collectionView.dataSource = self collectionView.delegate = self collectionView.register(EmoticonViewCell.self, forCellWithReuseIdentifier: EmoticonCellId) } private func prepareForToolBar() { toolBar.tintColor = .lightGray var items = [UIBarButtonItem]() var index = 0 for title in ["最近", "默认", "Emoji", "浪小花"] { // 1.创建item let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(itemClick(_:))) item.tag = index index += 1 items.append(item) // 2.弹簧 let flexItem = UIBarButtonItem(barButtonSystemItem: UIBarButtonItem.SystemItem.flexibleSpace, target: nil, action: nil) items.append(flexItem) } items.removeLast() // 将item添加到toolbar上 toolBar.items = items } @objc private func itemClick(_ item: UIBarButtonItem) { // 1.创建indexPath let indexPath = IndexPath(item: 0, section: item.tag) // 2.滚动到指定的indexPath,滚到最左边 collectionView.scrollToItem(at: indexPath, at: .left, animated: false) } } //MARK:- Collection的数据源和代理方法 extension EmoticonViewController: UICollectionViewDataSource, UICollectionViewDelegate { func numberOfSections(in collectionView: UICollectionView) -> Int { return manager.packages.count } // 告诉系统每组多少个 func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { let emoticons = manager.packages[section].emoticons return emoticons.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // 1.取出cell let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCellId, for: indexPath) as! EmoticonViewCell //cell.backgroundColor = (indexPath.item % 2 == 0) ? UIColor.red: UIColor.purple // 2.设置数据 let package = manager.packages[indexPath.section] let emoticon = package.emoticons[indexPath.item] cell.emoticon = emoticon // 3.返回cell return cell } /// 监听表情点击 func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { // 1. 取出表情 let package = manager.packages[indexPath.section] let emoticon = package.emoticons[indexPath.item] // 2.插入到最近分组中 insertRecentlyEmoticon(emoticon) // 3.将表情回调给外面控制器 callback(emoticon) } private func insertRecentlyEmoticon(_ emoticon: Emoticon) { // 1.空白、删除按钮,不需要插入 if emoticon.isEmpty || emoticon.isRemove { return } // 2.删除一个表情 if manager.packages.first!.emoticons.contains(emoticon) { //最近表情中存在 let index = manager.packages.first!.emoticons.firstIndex(of: emoticon)! manager.packages.first?.emoticons.remove(at: index) } else { // manager.packages.first?.emoticons.remove(at: 19) } // 3.将emoticon插入到最近分组中,永远保持 manager.packages.first?.emoticons.insert(emoticon, at: 0) } } class EmoticonCollectionViewLayout: UICollectionViewFlowLayout { override func prepare() { super.prepare() // 1.计算cell宽度 let itemWH = UIScreen.main.bounds.width / 7 itemSize = CGSize(width: itemWH, height: itemWH) minimumInteritemSpacing = 0 minimumLineSpacing = 0 scrollDirection = .horizontal // 2.设置collectionView collectionView?.bounces = false collectionView?.isPagingEnabled = true collectionView?.showsHorizontalScrollIndicator = false collectionView?.showsVerticalScrollIndicator = false // 3.设置上下内边距,上下布局合理,等高 let insetMargin = (collectionView!.bounds.height - 3 * itemWH) / 4 collectionView?.contentInset = UIEdgeInsets(top: insetMargin, left: 0, bottom: insetMargin, right: 0) } }
// // TableViewController.swift // TableViewDemo // // Created by Nick Kohrn on 2/8/15. // Copyright (c) 2015 Nick Kohrn. All rights reserved. // import UIKit class TableViewController: UITableViewController { let arrayOfStrings = ["Arthur", "Broccoli", "Coffee", "Dessert", "Elephant", "Fragile", "Ghost", "Isabel", "Jump", "Keys", "Lemon", "Mother", "Nickel", "Over", "Peck", "Quest", "Right", "Sled", "Teeth", "Umbrella", "Visor", "Wax", "X-ray", "Yellow", "Zebra"] override func viewDidLoad() { super.viewDidLoad() // Uncomment the following line to preserve selection between presentations // self.clearsSelectionOnViewWillAppear = false // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { // #warning Potentially incomplete method implementation. // Return the number of sections. return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // #warning Incomplete method implementation. // Return the number of rows in the section. return arrayOfStrings.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("stringCell", forIndexPath: indexPath) as UITableViewCell // Configure the cell... let stringItem = arrayOfStrings[indexPath.row] cell.textLabel?.text = stringItem.capitalizedString return cell } /* // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the specified item to be editable. return true } */ /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return NO if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetailView" { let detailViewController = segue.destinationViewController as DetailViewController if let indexPath = tableView.indexPathForCell(sender as UITableViewCell) { detailViewController.detailString = arrayOfStrings[indexPath.row] } } } }
// // WFImageCollectionViewCell.swift // niinfor // // Created by 王孝飞 on 2017/10/7. // Copyright © 2017年 孝飞. All rights reserved. // import UIKit class WFImageCollectionViewCell: UICollectionViewCell { var deletImageData : ((_ cell : UICollectionViewCell )->())? override func awakeFromNib() { super.awakeFromNib() // Initialization code } ///删除按钮点击 @IBAction func deleteBtnClick(_ sender: Any) { deletImageData?(self) } @IBOutlet weak var mainImageView: UIImageView! }
// // ReserveAppointment.swift // Animal House // // Created by Roy Geagea on 9/30/19. // Copyright © 2019 Roy Geagea. All rights reserved. // import SwiftUI struct ReserveAppointmentPage: View { @EnvironmentObject var viewModel: ReserveAppointmentViewModel @State var apDate: Date = Date() @State var apTime: Date = Date() @State var selectedPet: String = "Select Pet" @State var selectedType: String = "Select Your Appointment Type" @State var selectedDoctor: String = "Select Doctor" @State var isButtonLoading: Bool = false var body: some View { VStack { Form { Section(header: Text("Your Pet")) { NavigationLink(destination: MyPetsListPage(viewModel: PetsToAdoptListViewModel(), selectedPet: self.$selectedPet)) { Text(selectedPet) } } Section(header: Text("Appointment Type")) { NavigationLink(destination: AppointmentTypesListPage(viewModel: AppointmentTypesViewModel(), selectedType: self.$selectedType)) { Text(selectedType) } } Section(header: Text("Your Doctor")) { NavigationLink(destination: DoctorsListPage(viewModel: DoctorsListViewViewModel(), isReservation: true, selectedDoctor: self.$selectedDoctor)) { Text(selectedDoctor) } } Section(header: Text("Appointment Date")) { CustomDatePicker(birthDate: $apDate) } Section(header: Text("Appointment Time")) { VStack { DatePicker(selection: $apTime, displayedComponents: .hourAndMinute) { Text("") } } } RoundedButton(title: "Reserve", isDisabled: !self.viewModel.validateInput(), isLoading: self.isButtonLoading, action: { self.isButtonLoading = true self.viewModel.addAppointment(date: self.apDate, time: self.apTime) }) } } .onReceive(self.viewModel.objectWillChange) { (userProfile) in self.isButtonLoading = false } } }
// // otherJobCollectionCell.swift // WorkingBeez // // Created by Swami on 3/8/17. // Copyright © 2017 Brainstorm. All rights reserved. // import UIKit class otherJobCollectionCell: UICollectionViewCell { @IBOutlet weak var lblOtherJobCategoryTitle: UILabel! @IBOutlet weak var lblOtherJobCounter: UILabel! }
// // Customer.swift // LemonStand // // Created by Robin Somlette on 27-11-2014. // Copyright (c) 2014 Robin Somlette. All rights reserved. // import Foundation struct Customer { var index = 0 var preference = "" var didpurchase = false }
// swift-tools-version:5.3 // Package.swift // myPublicPod // // Created by MacPro on 2021/4/23. // import PackageDescription let package = Package( name: "myPublicPod", platforms: [SupportedPlatform.iOS(.v10)], products: [Product.library(name: "myPublicPod", targets: ["myPublicPod"])], dependencies: [Package.Dependency.package(name: "AFNetworking", url: "https://github.com/AFNetworking/AFNetworking.git", from: "4.0.0")], targets: [Target.target(name: "myPublicPod", path: "myPublicPod")] )
// // ClassPoint.swift // recognizer // // Created by Andrew Johnsson on 13.02.16. // Copyright © 2016 gingercode. All rights reserved. // import UIKit class ClassPoint: Point{ var points: [Point] = [] var wasMoved = false private var color: CGColor = UIColor.whiteColor().CGColor func addPoint(pt: Point){ self.points.append(pt) pt.setClass(self) } func getColor() -> CGColor{ return self.color } func setCoord(coord: (UInt16, UInt16)){ self.coordinate.x = coord.0 self.coordinate.y = coord.1 self.wasMoved = true } override init() { super.init() self.color = UIColor(hue: CGFloat(arc4random() % 256) / 256, saturation: CGFloat(arc4random() % 64) / 256 + 0.5, brightness: CGFloat(arc4random() % 128) / 256 + 0.5, alpha: 1).CGColor } }
import Foundation import SwiftyJSON public let SHJSON = SHJSONJSONManager() open class SHJSONJSONManager { open func createJSONData(fromObject object: AnyObject) -> Data? { var jsonData: Data? do { jsonData = try JSONSerialization.data(withJSONObject: object, options: JSONSerialization.WritingOptions.prettyPrinted) } catch let error as NSError { NSLog("JSON error = \(error)")//TODO: Add to Errors } return jsonData } open func createJSONObject(fromObject object: AnyObject) -> [String : AnyObject] { var JSON = [String : AnyObject]() switch object { case is [AnyObject]: parseArray(array: object as! [AnyObject], parentKey: "", toJSON: &JSON) case is [String : AnyObject]: parseDictionary(dictionary: object as! [String: AnyObject], parentKey: "", toJSON: &JSON) default: break } return JSON } internal func createJSONObjectFrom(_ incomingData: Data) -> JSON? { return JSON(incomingData) } fileprivate func parseDictionary(dictionary: [String: AnyObject], parentKey: String, toJSON JSON: inout [String : AnyObject]) { for (var key, value) in dictionary { key = parentKey == "" ? key : parentKey + "[\(key)]" switch value { case is String, is Int, is Double: JSON[key] = value case is [AnyObject]: parseArray(array: value as! [AnyObject], parentKey: key, toJSON: &JSON) case is [String : AnyObject]: parseDictionary(dictionary: value as! [String : AnyObject], parentKey: key, toJSON: &JSON) default: NSLog("Unsupported type") break } } } fileprivate func parseArray(array: [AnyObject], parentKey: String, toJSON JSON: inout [String : AnyObject]) { for (i, obj) in array.enumerated() { let key = parentKey == "" ? "" : parentKey + "[\(i)]" switch obj { case is String, is Int, is Double: JSON[key] = obj case is [[String : AnyObject]]: parseArray(array: obj as! [[String : AnyObject]] as [AnyObject], parentKey: key, toJSON: &JSON) case is [String : AnyObject]: parseDictionary(dictionary: obj as! [String : AnyObject], parentKey: key, toJSON: &JSON) default: NSLog("Unsupported type") break } } } }
// // SearchTournamentsContainer.swift // app // // Created by Иван Лизогуб on 21.11.2020. // // import UIKit final class SearchTournamentsContainer { let input: SearchTournamentsModuleInput let viewController: UIViewController private(set) weak var router: SearchTournamentsRouterInput! static func assemble(with context: SearchTournamentsContext) -> SearchTournamentsContainer { let router = SearchTournamentsRouter() //TODO: номер телефона let interactor = SearchTournamentsInteractor() //TODO: номер телефона let presenter = SearchTournamentsPresenter(router: router, interactor: interactor) let viewController = SearchTournamentsViewController(output: presenter) presenter.view = viewController presenter.moduleOutput = context.moduleOutput interactor.output = presenter router.navigationControllerProvider = { [weak viewController] in viewController?.navigationController } return SearchTournamentsContainer(view: viewController, input: presenter, router: router) } private init(view: UIViewController, input: SearchTournamentsModuleInput, router: SearchTournamentsRouterInput) { viewController = view self.input = input self.router = router } } struct SearchTournamentsContext { weak var moduleOutput: SearchTournamentsModuleOutput? //TODO: номер телефона }
// // ImageDataDao.swift // ios-base64-demo // // Created by Eiji Kushida on 2017/07/22. // Copyright © 2017年 Eiji Kushida. All rights reserved. // final class ImageDataDao { static let dao = RealmDaoHelper<ImageData>() static func add(model: ImageData) { let object = ImageData() object.imageId = ImageDataDao.dao.newId()! object.imageData = model.imageData object.imageDataType = model.imageDataType ImageDataDao.dao.add(d: object) } }
// // UserCacheManager.swift // Swift-Base // // Created by Maksim Kapitonov on 24/11/2021. // Copyright © 2021 Flatstack. All rights reserved. // import Foundation protocol UserCacheManager { // MARK: - Instance Methods func createOrUpdate(from fragment: UserFragment, context: StorageContext) -> User func fetch(with id: String?) -> User? func fetch(with ids: [String?]) -> [User] func save(context: StorageContext) func remove() func remove(with id: String) }
// // PokemonViewModel.swift // PokeFinder // // Created by Estudiantes on 4/12/21. // import Foundation class PokemonViewModel: ObservableObject { @Published var pokemonCards: [pokemon.Cards] = [] func fetchCards(name: String){ guard let url = URL(string: "https://api.pokemontcg.io/v2/cards?q=name:\(name)") else { print("API Error") return } let request = URLRequest(url: url) URLSession.shared.dataTask(with: request) { data, response, error in if let data = data { if let response = try? JSONDecoder().decode(pokemon.self, from: data) { DispatchQueue.main.async { self.pokemonCards = response.data } return } } }.resume() } }
// // Image.swift // glosss // // Created by Mauricio Lorenzetti on 20/01/21. // import Foundation struct Image: Codable { let id: String let imageDescription: String? let datetime: Int let type: String let animated: Bool let width, height, size, views: Int let link: String let mp4, gifv, hls: String? enum CodingKeys: String, CodingKey { case id case imageDescription = "description" case datetime, type, animated, width, height, size, views, link case mp4, gifv, hls } var mediaType: MediaType? { return MediaType(value: type) } }
// // Created by Иван Лизогуб on 14.11.2020. // import UIKit class UserRegistrationContainer { let input: UserRegistrationModuleInput let viewController: UIViewController private(set) weak var router: UserRegistrationRouterInput! class func assemble(with context: UserRegistrationContext) -> UserRegistrationContainer { let router = UserRegistrationRouter() let interactor = UserRegistrationInteractor() let presenter = UserRegistrationPresenter(router: router, interactor: interactor) let viewController = UserRegistrationViewController(output: presenter) presenter.view = viewController presenter.moduleOutput = context.moduleOutput interactor.output = presenter router.navigationControllerProvider = { [weak viewController] in viewController?.navigationController } return UserRegistrationContainer(view: viewController, input: presenter, router: router) } private init(view: UIViewController, input: UserRegistrationModuleInput, router: UserRegistrationRouterInput) { viewController = view self.input = input self.router = router } } struct UserRegistrationContext { weak var moduleOutput: UserRegistrationModuleOutput? //var phoneNumber: String }
// // FilterSelectorHeaderView.swift // BeastlySearch // // Created by Trevor Beasty on 11/4/17. // Copyright © 2017 Trevor Beasty. All rights reserved. // import UIKit protocol FilterSelectorHeaderViewDelegate: class { func didTapSectionWithIndex(_ index: Int) } class FilterSelectorHeaderView: UITableViewHeaderFooterView { weak var delegate: FilterSelectorHeaderViewDelegate? var index: Int? override init(reuseIdentifier: String?) { super.init(reuseIdentifier: reuseIdentifier) setUpTap() } required init?(coder aDecoder: NSCoder) { fatalError() } private func setUpTap() { let tap = UITapGestureRecognizer(target: self, action: #selector(didTap(tap:))) contentView.addGestureRecognizer(tap) } @objc private func didTap(tap: UITapGestureRecognizer) { guard let index = index else { return } delegate?.didTapSectionWithIndex(index) } func configure(index: Int, delegate: FilterSelectorHeaderViewDelegate) { self.index = index self.delegate = delegate } }
// // AppLovinViewController.swift // TeadsSampleApp // // Created by Vincent Saluzzo on 15/03/2022. // Copyright © 2022 Teads. All rights reserved. // import Foundation class AppLovinViewController: TeadsViewController { var isMREC = false }
// // ViewController01.swift // HelpingHand // // Created by amota511 on 12/28/17. // Copyright © 2017 Aaron Motayne. All rights reserved. // import UIKit class ViewController01: UIViewController { override func viewDidLoad() { super.viewDidLoad() } }
// // iTipJarConfiguration.swift // iTipJarMaster // // Created by Andrew Halls on 9/26/14. // Copyright (c) 2014 Thinkful. All rights reserved. // import Foundation import StoreKit class iTipJarConfiguration { //MARK: Class Methods /** Returns the store identifer for the item at index. By default @param index Index of the tip level */ class func storeIdentifer(index: Int) -> String { return iTipJarConfiguration.sharedInstance.identifer(index) } class func setStoreIdentifer(index: Int, identifer: String) { iTipJarConfiguration.sharedInstance.setIdentifer(index, identifer: identifer) } //MARK: Singleton Pattern // http://code.martinrue.com/posts/the-singleton-pattern-in-swift class var sharedInstance: iTipJarConfiguration { struct Static { static var sharedInstance: iTipJarConfiguration? static var token: dispatch_once_t = 0 } dispatch_once(&Static.token) { Static.sharedInstance = iTipJarConfiguration() } return Static.sharedInstance! } //MARK: Initializer let paymentQueue = SKPaymentQueue.defaultQueue() let paymentTransactionObserver = iTipJarPaymentTransactionObserver() init() { paymentQueue.addTransactionObserver(paymentTransactionObserver) } //MARK: Identifers private var identifers = Dictionary<Int,String>() private var bundleIdentifer: String { return NSBundle.mainBundle().bundleIdentifier ?? "com.thinkful.itipjar.store" } private func defaultIdentifer(index: Int) -> String { return bundleIdentifer + ".store.\(index)" } private func identifer(index: Int) -> String { if let result = identifers[index] { return result } return defaultIdentifer(index) } private func setIdentifer(index: Int, identifer: String) { identifers[index] = identifer } }
// // MainTableView.swift // SimpleListView-Example // // Created by Gollum on 2020/7/30. // Copyright © 2020 Gollum. All rights reserved. // import UIKit import SimpleListView class MainTableView: SLTableView { func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { return section == 0 ? "Table View" : "Colleciton View" } }
// // bookData.swift // textbook // // Created by Zuhao Hua on 11/27/20. // Copyright © 2020 Anya Ji. All rights reserved. // import Foundation import MessageKit enum SellType{ case sell case exchange } struct RecentlyAdded: Codable{ var success: Bool var data:[Book] } struct Book: Codable,Equatable{ static func == (lhs: Book, rhs: Book) -> Bool { if lhs.id == rhs.id{ return true } else{ return false } } var id: Int var image: [BookImage] var title: String var author: String var courseName: String var isbn: String var edition: String var price: String var available: Bool var createdAt: String var updatedAt: String? var sellerId: Int var condition: String func toDict() -> [String: Any]{ return [ "id": id, "title": title, "author": author, "courseName": courseName, "isbn": isbn, "edition": edition, "price": price, "available": available, "condition": condition ] } } struct BookImage: Codable{ var bookId: Int var url:String var createdAt: String } struct uploadBookBackEndNoImageStruct: Codable{ var title: String var price: Double var sellerId: Int var image: String var author: String var courseName: String var isbn: String var edition: String var condition: String } struct uploadBookBackEndResponse: Codable{ var success: Bool var data:uploadBookBackEndResponseStruct } struct uploadBookBackEndResponseStruct: Codable{ var id: Int var image: [BookImage] var title: String var author: String var courseName: String var isbn: String var edition: String var price: String var available: Bool var createdAt: String var updatedAt: String? var sellerId: Int } struct addCartStruct:Codable{ var bookId:Int } struct userInfoResponse:Codable{ var success: Bool var data:userInfoResponseDataStruct } struct userInfoResponseDataStruct:Codable{ var id:Int var email:String var name:String var selling:[Book] var cart:[Book] } class User: Codable { var session_token: String var session_expiration: String var update_token: String var id:Int init(session_token: String, session_expiration: String, update_token: String, userId:Int) { self.session_token = session_token self.session_expiration = session_expiration self.update_token = update_token self.id = userId } } struct accountDetails: Codable { var session_token: String var session_expiration: String var update_token: String var id:Int } struct accountError: Codable { var error: String } struct UserInfo: Codable { var id: Int var email: String var name: String func toDict() -> [String: Any]{ return ["id": id, "email": email, "name": name] } static func fromDB(data: [String: Any]) -> UserInfo{ return UserInfo(id: data["id"] as! Int, email: data["email"] as! String, name: data["name"] as! String) } } struct Sender: SenderType { var senderId: String var displayName: String } struct Message: MessageType { var sender: SenderType var messageId: String var sentDate: Date var kind: MessageKind } struct BookInfo{ var id: Int var title: String var author: String var courseName: String var isbn: String var edition: String var price: String var available: Bool var condition: String static func fromDB(data: [String: Any]) -> BookInfo{ let id = data["id"] as! Int let title = data["title"] as! String let author = data["author"] as! String let courseName = data["courseName"] as! String let isbn = data["isbn"] as! String let edition = data["edition"] as! String let price = data["price"] as! String let available = data["available"] as! Bool let condition = data["condition"] as! String return BookInfo(id: id, title: title, author: author, courseName: courseName, isbn: isbn, edition: edition, price: price, available: available, condition: condition) } } struct ChatInfo { var id: String var updated: Date var buyer: UserInfo var seller: UserInfo var bookInfo: BookInfo var userIds: [Int] }
// // HomeController.swift // Control de Ingreso2 // // Created by Esteban Choque Villalobos on 9/14/20. // Copyright © 2020 Esteban Choque Villalobos. All rights reserved. // import UIKit struct Item { var nombre : String var imageName : String } class HomeController: UIViewController { @IBOutlet weak var collectionView: UICollectionView! //var items = ["First Cell", "Second Cell", "Third Cell", "Cuarta Celda", "Quinta Celda"] var items : [Item] = [ Item(nombre:"Escanear QR", imageName:"icono_scan_qr"), Item(nombre:"Buscar CI", imageName:"icono_carnet"), Item(nombre:"VISITAS", imageName:"icono_visita"), Item(nombre:"VISITANTES", imageName:"icono_visitantes"), Item(nombre:"HORARIOS", imageName:"icono_horario"), Item(nombre:"EMPRESAS", imageName:"icono_empresa"), Item(nombre:"USUARIOS", imageName:"icono_usuarios")] var collectionViewFlowLayout: UICollectionViewFlowLayout! let cellIdentifier = "CollectionViewCell" //let viewImageSegueIdentifier = "viewImageSegueIdentifier" let buscarXQRSegue = "buscarXQRSegue" let buscarXCISegue = "buscarXCISegue" let visitasSegue = "visitasSegue" let visitantesSegue = "visitantesSegue" let horariosSegue = "horariosSegue" let empresasSegue = "empresasSegue" let usuariosSegue = "usuariosSegue" var whosLogin : String! override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() setupCollectionViewItemSize() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. setupCollectionView() //Barra de navegacion //edgesForExtendedLayout = [] //setUpNavBar() self.navigationItem.setHidesBackButton(true, animated: true) } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { let item = sender as! Item /*if segue.identifier == buscarXQRSegue { if let vc = segue.destination as? PruebaController { } }*/ } private func setupCollectionView() { collectionView.delegate = self collectionView.dataSource = self let nib = UINib(nibName: "CollectionViewCell", bundle: nil) collectionView.register(nib, forCellWithReuseIdentifier: cellIdentifier) } private func setupCollectionViewItemSize() { if(collectionViewFlowLayout == nil) { let numberOfItemPerRow:CGFloat = 2 let lineSpacing:CGFloat = 5 let interItemSpacing:CGFloat = 5 let width = (collectionView.frame.width-(numberOfItemPerRow-1)*interItemSpacing)/numberOfItemPerRow let height = width collectionViewFlowLayout = UICollectionViewFlowLayout() collectionViewFlowLayout.itemSize = CGSize(width:width, height:height) collectionViewFlowLayout.sectionInset = UIEdgeInsets.zero collectionViewFlowLayout.scrollDirection = .vertical collectionViewFlowLayout.minimumLineSpacing = lineSpacing collectionViewFlowLayout.minimumInteritemSpacing = interItemSpacing collectionView.setCollectionViewLayout(collectionViewFlowLayout, animated: true) } } func setUpNavBar(){ //For title in navigation bar self.navigationController?.view.backgroundColor = UIColor.white self.navigationController?.view.tintColor = UIColor.orange self.navigationItem.title = "About Us" //For back button in navigation bar let backButton = UIBarButtonItem() backButton.title = "Back" self.navigationController?.navigationBar.topItem?.backBarButtonItem = backButton } } extension HomeController : UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellIdentifier, for: indexPath) as! CollectionViewCell cell.imageView.image = UIImage(named: items[indexPath.row].imageName) cell.proLbl.text = items[indexPath.row].nombre return cell } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { let item = items[indexPath.item] //performSegue(withIdentifier: viewImageSegueIdentifier, sender: item) //Se obtiene la posicion del item seleccionado //print("The message is: \(indexPath.item)") if(indexPath.item == 0) { performSegue(withIdentifier: buscarXQRSegue, sender: item) } else if(indexPath.item == 1) { performSegue(withIdentifier: buscarXCISegue, sender: item) } else if(indexPath.item == 2) { performSegue(withIdentifier: visitasSegue, sender: item) } else if(indexPath.item == 3) { performSegue(withIdentifier: visitantesSegue, sender: item) } else if(indexPath.item == 4) { performSegue(withIdentifier: horariosSegue, sender: item) } else if(indexPath.item == 5) { performSegue(withIdentifier: empresasSegue, sender: item) } else if(indexPath.item == 6) { performSegue(withIdentifier: usuariosSegue, sender: item) } } }
// // DataAccess.swift // Lab3 // // Created by Rishabh Sanghvi on 11/4/15. // Copyright © 2015 Rishabh Sanghvi. All rights reserved. // import Foundation class DataAccess : NSObject { var data: [String:[String:String]]! = ["mlk":["name":"King Library","building":"Dr. Martin Luther King, Jr. Library, 150 East San Fernando Street, San Jose, CA 95112"], "eng":["name":"Engineering Building","building":"San José State University Charles W. Davidson College of Engineering, 1 Washington Square, San Jose, CA 95112"], "yuh":["name":"Yoshihiro Uchida Hall","building":"Yoshihiro Uchida Hall, San Jose, CA 95112"], "bbc":["name":"BBC","building":"Boccardo Business Complex, San Jose, CA 95112"], "su":["name":"Student Union","building":"Student Union Building, San Jose, CA 95112"], "sp":["name":"South​P​arking​G​arage","building":"San Jose State University South Garage, 330 South 7th Street, San Jose, CA 95112"] ] func getData(buildingName: String) -> [String:String] { return self.data[buildingName]! } func getDataObject(buildingName: String) -> DataObj! { let data: DataObj! = DataObj() let extractedValue = getData(buildingName) data.setBuildingName(extractedValue["name"]!) data.setAddress(extractedValue["building"]!) return data } func getAllBuildingDataObject() -> [DataObj]! { var results: [DataObj]! = [DataObj]() for (_,value) in self.data { let result: DataObj = DataObj() result.setBuildingName(value["name"]!) result.setAddress(value["building"]!) results.append(result) } return results } func getAddressForBuildingName(buildingName: String) -> String { let data: DataObj! = DataObj() let extractedValue = getData(buildingName) data.setBuildingName(extractedValue["name"]!) data.setAddress(extractedValue["building"]!) return data.getAddress() } }
import UIKit import CoreData class TransactionViewController: UIViewController, LBZSpinnerDelegate, NSFetchedResultsControllerDelegate { /** Atributos **/ @IBOutlet var transactionAccount:LBZSpinner! @IBOutlet weak var transactionType: UISegmentedControl! @IBOutlet weak var transactionDescription: UITextField! @IBOutlet weak var transactionAmount: UITextField! @IBOutlet weak var transactionCategory: UITextField! @IBOutlet weak var transactionDate: UIDatePicker! var accounts = [] var accountsDescriptions: [String] = [] var managedContext: NSManagedObjectContext! var transaction:Transaction! var transactionTypeSelected: Int! var fetchResultController:NSFetchedResultsController! override func viewDidLoad() { super.viewDidLoad() /** Load Accounts **/ loadAccounts() /** Spinner **/ transactionAccount.updateList(accountsDescriptions) transactionAccount.delegate = self /** Persistencia **/ if let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate { managedContext = appDelegate.managedObjectContext } } func spinnerChoose(spinner:LBZSpinner, index:Int, value:String) { NSLog("\(value)") } @IBAction func cancel(sender: AnyObject) { dismissViewControllerAnimated(true, completion: nil) } @IBAction func save(sender: AnyObject) { if (transactionDescription.text == "" || transactionAmount.text == "" || transactionCategory.text == "") { let alertController = UIAlertController(title: "Atenção", message: "Favor preencher todos os campos.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } // saveTransaction() } func saveTransaction(accont: String, descr: String, amount: Double, category: String, date: NSDate) { dismissViewControllerAnimated(true, completion: nil) } func loadAccounts() { /** Parametros Carregar contas **/ let fetchRequest = NSFetchRequest(entityName: "Account") let sortDescriptor = NSSortDescriptor(key: "descr", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] /** Carregar contas **/ if let managedObjectContext = (UIApplication.sharedApplication().delegate as? AppDelegate)?.managedObjectContext { fetchResultController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: managedObjectContext, sectionNameKeyPath: nil, cacheName: nil) fetchResultController.delegate = self do { try fetchResultController.performFetch() accounts = fetchResultController.fetchedObjects as! [Account] for account in accounts { accountsDescriptions.append(String(account.valueForKey("descr")!)) } } catch let error as NSError { NSLog("Could not fetch \(error), \(error.userInfo)") } } } func convertLocalizedStringToDouble (decimalAsString: String, thousandSeparator: Bool) -> Double { let formatter = NSNumberFormatter() formatter.usesGroupingSeparator = thousandSeparator formatter.locale = NSLocale.currentLocale() var decimalAsDouble = formatter.numberFromString(decimalAsString)?.doubleValue // The below should never happen! Only happens, if string equals "1,00034.00", so wrong placement of thousand separator if decimalAsDouble == nil { decimalAsDouble = 0 } // returning an "Err-Code of 0" if let decimalAsDoubleUnwrapped = formatter.numberFromString(decimalAsString) { decimalAsDouble = decimalAsDoubleUnwrapped.doubleValue } return decimalAsDouble! } }
// // Trail.swift // Trail of History // // Created by Dagna Bieda & Robert Vaessen on 8/22/16. // Copyright © 2016 CLT Mobile. All rights reserved. // import Foundation import MapKit // A singleton instance of the Trail class dispences all of the information provided by the Trail of History's various data files: // // 1) Trail.instance.region - An MKCoordinateRegion that defines the geospatial boundary of the trail. // The region can be used to zoom a map to the trail's location. This information is obtained from // the Trail Bounds file. // // 2) Trail.instance.route - An MKOverlay that can be added to a map to display the actual route of the trail. // a. Trail.instance.route.renderer - An MKOverlayRenderer () that can be used by a map to draw the route. // The renderer gets its image from the Trail Route file. // // 3) Trail.instance.pointsOfInterest - A PointOfInterest array containing all of the trail's points of interest. The // information comes from the Points Of Interest file. The POIs are sorted by longitude, westmost first. // The POIs implement MKAnnotation and so can be added to a map. // // In addition the Trail is a CLLocationManagerDelegate. When the Trail is instantiated it creates a Location Manger // and starts location updates. As the Trail receives the updates it uses them to update the distance from the user // to each of the points of interest. class Trail : NSObject { static let instance: Trail = Trail() let route: Route // Usage: MapView.addOverlay(Trail.instance.route) let region: MKCoordinateRegion // Usage: MapView.region = Trail.instance.region let pointsOfInterest: [PointOfInterest] // Usage: MapView.addAnnotations(Trail.instance.pointsOfInterest). Sorted by longitude, westmost first. fileprivate let locationManager : CLLocationManager? // The bounds file is a dictionary of coordinates fileprivate let boundsFileName = "TrailBounds.plist" fileprivate enum Coordinates: String { case midCoord case topLeftCoord case topRightCoord case bottomLeftCoord } fileprivate override init() { let boundsFileNameComponents = boundsFileName.components(separatedBy: ".") let boundsFilePath = Bundle.main.path(forResource: boundsFileNameComponents[0], ofType: boundsFileNameComponents[1])! let properties = NSDictionary(contentsOfFile: boundsFilePath)! func makeCoordinate(_ name: String) -> CLLocationCoordinate2D { let point = CGPointFromString(properties[name] as! String) return CLLocationCoordinate2DMake(CLLocationDegrees(point.x), CLLocationDegrees(point.y)) } let midCoordinate = makeCoordinate(Coordinates.midCoord.rawValue) let topLeftCoordinate = makeCoordinate(Coordinates.topLeftCoord.rawValue) let topRightCoordinate = makeCoordinate(Coordinates.topRightCoord.rawValue) let bottomLeftCoordinate = makeCoordinate(Coordinates.bottomLeftCoord.rawValue) let topLeftPoint = MKMapPointForCoordinate(topLeftCoordinate); let topRightPoint = MKMapPointForCoordinate(topRightCoordinate); let bottomLeftPoint = MKMapPointForCoordinate(bottomLeftCoordinate); let boundingRect = MKMapRectMake(topLeftPoint.x, topLeftPoint.y, fabs(topLeftPoint.x - topRightPoint.x), fabs(topLeftPoint.y - bottomLeftPoint.y)) route = Route(midCoordinate: midCoordinate, boundingMapRect: boundingRect) let latitudeDelta = fabs(topLeftCoordinate.latitude - bottomLeftCoordinate.latitude) let longitudeDelta = fabs(topLeftCoordinate.longitude - topRightCoordinate.longitude) let span = MKCoordinateSpanMake(latitudeDelta, longitudeDelta) region = MKCoordinateRegionMake(midCoordinate, span) pointsOfInterest = PointOfInterest.getPointsOfInterest() locationManager = CLLocationManager.locationServicesEnabled() ? CLLocationManager() : nil super.init() if let manager = locationManager { //locationManager.desiredAccuracy = 1 //locationManager.distanceFilter = 0.5 manager.delegate = self manager.startUpdatingLocation() } else { alertUser("Location Services Needed", body: "Please enable location services so that Trail of History can show you where you are on the trail and what the distances to the points of interest are.") } } fileprivate func alertUser(_ title: String?, body: String?) { if let topController = UIApplication.topViewController() { let alert = UIAlertController(title: title, message: body, preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "Okay", style: UIAlertActionStyle.default, handler: nil)) topController.present(alert, animated: false, completion: nil) } } } extension Trail { class Route: NSObject, MKOverlay { class Renderer : MKOverlayRenderer { fileprivate static let routeImageFileName = "TrailRoute" fileprivate let pathImage = UIImage(named: routeImageFileName) override func draw(_ mapRect: MKMapRect, zoomScale: MKZoomScale, in context: CGContext) { let rendererRect = rect(for: overlay.boundingMapRect) context.scaleBy(x: 1.0, y: -1.0) context.translateBy(x: 0.0, y: -rendererRect.size.height) context.draw((pathImage?.cgImage)!, in: rendererRect) } } // MKOverlay implementation fileprivate(set) var coordinate: CLLocationCoordinate2D fileprivate(set) var boundingMapRect: MKMapRect fileprivate(set) var renderer: Renderer! fileprivate init(midCoordinate: CLLocationCoordinate2D, boundingMapRect: MKMapRect) { self.coordinate = midCoordinate self.boundingMapRect = boundingMapRect super.init() renderer = Renderer(overlay: self) } } } extension Trail { class PointOfInterest: NSObject, MKAnnotation { fileprivate static func getPointsOfInterest() -> [PointOfInterest] { // The POI file is a dictionary of dictionaries. The keys of the outer dictionary // are the POI names. The inner dictionaries contain the POI's data. let poiFileName = "PointsOfInterest.plist" var pointsOfInterest = [PointOfInterest]() let poiFileNameComponents = poiFileName.components(separatedBy: ".") let poiFilePath = Bundle.main.path(forResource: poiFileNameComponents[0], ofType: poiFileNameComponents[1])! for (name, data) in NSDictionary(contentsOfFile: poiFilePath)! { let poiData = data as! [String:String] if let poiLocation = poiData["location"], let description = poiData["description"] { let location = CGPointFromString(poiLocation) let coordinate = CLLocationCoordinate2D(latitude: CLLocationDegrees(location.x), longitude: CLLocationDegrees(location.y)) let title = name as! String let poi = PointOfInterest(title: title, coordinate: coordinate, narrative: description) pointsOfInterest.append(poi) } } return pointsOfInterest.sorted { $0.coordinate.longitude < $1.coordinate.longitude } } // MKAnnotation implementation let title: String? let subtitle: String? let coordinate: CLLocationCoordinate2D let narrative: String let location: CLLocation fileprivate(set) var distance: Double? // The distance will remain nil if location services are unavailable or unauthorized. fileprivate init(title: String, coordinate: CLLocationCoordinate2D, narrative: String) { self.title = title self.coordinate = coordinate self.narrative = narrative subtitle = "lat \(coordinate.latitude), long \(coordinate.longitude)" location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) } } } extension Trail : CLLocationManagerDelegate { func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { switch status { case CLAuthorizationStatus.notDetermined: manager.requestWhenInUseAuthorization(); case CLAuthorizationStatus.authorizedWhenInUse: manager.startUpdatingLocation() default: alertUser("Location Access Not Authorized", body: "Trail of History will not be able show you the distance to the points of interest. You can change the authorization in Settings") break } } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { let YardsPerMeter = 1.0936 let userLocation = locations[locations.count - 1] for poi in pointsOfInterest { poi.distance = userLocation.distance(from: poi.location) * YardsPerMeter } } }
// // ViewController.swift // Canvas // // Created by Joseph Andy Feidje on 11/2/18. // Copyright © 2018 Softmatech. All rights reserved. // import UIKit class CanvasViewController: UIViewController, UIGestureRecognizerDelegate { @IBOutlet weak var trayView: UIView! var trayOriginalCenter: CGPoint! var trayDownOffset: CGFloat! var trayUp: CGPoint! var trayDown: CGPoint! var newlyCreatedFace: UIImageView! var newlyCreatedFaceOriginalCenter: CGPoint! var trayCenterWhenOpen: CGPoint! var trayCenterWhenClosed: CGPoint! var faceCreatedCenter: CGPoint! var newCreatedFace: UIImageView! var originalCenter = CGPoint() override func viewDidLoad() { super.viewDidLoad() trayDownOffset = 160 trayUp = trayView.center // The initial position of the tray trayDown = CGPoint(x: trayView.center.x ,y: trayView.center.y + trayDownOffset) // The position of the tray transposed down trayCenterWhenOpen = self.trayView.center trayCenterWhenClosed = CGPoint(x: self.trayView.center.x, y: self.trayView.center.y + 160) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func didPanTray(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) if sender.state == .began { print("Gesture began") trayOriginalCenter = trayView.center } else if sender.state == .changed { print("Gesture is changing") // view.center = CGPoint(x: trayOriginalCenter.x, y: trayOriginalCenter.y + translation.y) } else if sender.state == .ended { print("Gesture ended") // let velocity = sender.velocity(in: view) if sender.velocity(in: trayView).y > 0 { UIView.animate(withDuration:0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] ,animations: { () -> Void in self.trayView.center = self.trayDown }, completion: nil) self.trayView.center = self.trayCenterWhenClosed } else { UIView.animate(withDuration:0.4, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 1, options:[] ,animations: { () -> Void in self.trayView.center = self.trayDown }, completion: nil) self.trayView.center = self.trayCenterWhenOpen } } } @IBAction func didPanface(_ sender: UIPanGestureRecognizer) { let translation = sender.translation(in: view) if sender.state == .began { faceCreatedCenter = sender.view?.center let imageView = sender.view as! UIImageView let panGesture = UIPanGestureRecognizer(target: self, action: #selector(didPanface(sender:))) newCreatedFace = UIImageView(image: imageView.image) newCreatedFace.isUserInteractionEnabled = true newCreatedFace.addGestureRecognizer(panGesture) view.addSubview(newCreatedFace) newCreatedFace.center = imageView.center newCreatedFace.center.y += trayView.frame.origin.y } else if sender.state == .changed { newCreatedFace.center = CGPoint(x: faceCreatedCenter.x + sender.translation(in: newCreatedFace).x, y: 347 + faceCreatedCenter.y + sender.translation(in: newCreatedFace).y) } else if sender.state == .ended { } } @objc func didPanface(sender: UIPanGestureRecognizer) { if sender.state == .began { originalCenter = (sender.view?.center)! sender.view?.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } else if sender.state == .changed { sender.view?.center = CGPoint(x: (originalCenter.x) + sender.translation(in: sender.view).x, y: (originalCenter.y) + sender.translation(in: sender.view).y) } else if sender.state == .ended { sender.view?.transform = CGAffineTransform.identity } } @IBAction func didTapTray(_ sender: UITapGestureRecognizer) { // trayView.removeFromSuperview() } @IBAction func didPinchTray(_ sender: UIPinchGestureRecognizer) { if sender.state == .began { originalCenter = (sender.view?.center)! sender.view?.transform = CGAffineTransform(scaleX: 1.5, y: 1.5) } else if sender.state == .changed { // sender.view?.center = CGPoint(x: (originalCenter.x) + sender.translation(in: sender.view).x, y: (originalCenter.y) + sender.translation(in: sender.view).y) } else if sender.state == .ended { sender.view?.transform = CGAffineTransform.identity } } }
import UIKit import EvmKit import SectionsTableView import ThemeKit protocol ISwapSettingsDataSource: AnyObject { func viewDidLoad() func buildSections(tableView: SectionsTableView) -> [SectionProtocol] func didTapApply() var onOpen: ((UIViewController) -> ())? { get set } var onClose: (() -> ())? { get set } var onReload: (() -> ())? { get set } var onChangeButtonState: ((Bool, String) -> ())? { get set } } class SwapSettingsModule { static func viewController(dataSourceManager: ISwapDataSourceManager, dexManager: ISwapDexManager) -> UIViewController? { let viewController = SwapSettingsViewController(dataSourceManager: dataSourceManager) return ThemeNavigationController(rootViewController: viewController) } } extension SwapSettingsModule { enum AddressError: Error { case invalidAddress } enum SlippageError: Error { case zeroValue case tooLow(min: Decimal) case tooHigh(max: Decimal) } enum DeadlineError: Error { case zeroValue } }
// // Consts.swift // BTCUSDChart // // Created by Андрей Ежов on 28.10.17. // Copyright © 2017 Андрей Ежов. All rights reserved. // import UIKit struct Consts { struct JSON { static let ticks = "ticks" static let s = "s" static let b = "b" static let bf = "bf" static let a = "a" static let af = "af" static let spr = "spr" } struct Positions { static let BTCUSD = "BTCUSD" } enum Socket { static let url = "wss://quotes.exness.com:18400/" case subscribe(String) case unsubscribe(String) var asComand: String { switch self { case .subscribe(let unit): return "SUBSCRIBE: \(unit)" case .unsubscribe(let unit): return "UNSUBSCRIBE: \(unit)" } } } }
import XCTest import EncoderDecoder final class EncoderDecoderTests: XCTestCase { }
import Foundation // Using tuple array instead of a dictionary to prevent unwanted reordering let fizzBuzzBazzValues: [(key: Int, value: String)] = [ (3, "Fizz"), (5, "Buzz"), (7, "Bazz"), (11, "Boo") ] func printFizzBuzz(_ value: Int) { let result = fizzBuzzBazzValues .filter { value % $0.key == 0 } .map { $0.value } .reduce("", +) switch result { case let x where x.length > 0: print("\(x)") default: print("\(value)") } } for i in 1...100 { printFizzBuzz(i) }
// // ViewController.swift // Multiplication Exercises // // Created by Samuel Fox on 8/25/18. // Copyright © 2018 Samuel Fox. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet var multiplicand: UILabel! @IBOutlet var multiplier: UILabel! @IBOutlet var result: UILabel! @IBOutlet var questionsStatus: UILabel! @IBOutlet var questionStatusAlias: UILabel! @IBOutlet var submitNextButton: UIButton! @IBOutlet var correctLabel: UILabel! @IBOutlet var answerChoicesSegmentedControl: UISegmentedControl! @IBOutlet var progressBar: UIProgressView! @IBOutlet var hintButton: UIButton! var internalResultCollection = [Int]() let numberOfChoicesDisplayed = 4 var internalMultiplicand = 0 var internalMultiplier = 0 var internalResult = 0 var attempts = 0 var totalCorrect = 0 var internalResultIndex = 0 func generateMultiplicationValues(){ var randomResult = 0 internalResultCollection = [Int]() internalMultiplicand = Int(arc4random_uniform(15)+1) internalMultiplier = Int(arc4random_uniform(15)+1) multiplicand.text = String(internalMultiplicand) multiplier.text = String(internalMultiplier) internalResult = internalMultiplicand * internalMultiplier // Populate a collection of random results as well as the correct one for internal use while internalResultCollection.count < numberOfChoicesDisplayed { if Int(arc4random_uniform(2)) == 1 { randomResult = internalResult + Int(arc4random_uniform(5))+1 } else { randomResult = internalResult - Int(arc4random_uniform(5))+1 } if !(internalResultCollection.contains(randomResult)) && randomResult != internalResult && randomResult > 0{ internalResultCollection.append(randomResult) } } // Put the correct value randomly in the array internalResultIndex = Int(arc4random_uniform(4)) internalResultCollection[internalResultIndex] = internalResult var index = 0 answerChoicesSegmentedControl.removeAllSegments() for i in internalResultCollection { answerChoicesSegmentedControl.insertSegment(withTitle: String(i), at: index, animated: true) index += 1 } } func startAndRestartGame(){ // Initialize all values to their start value. answerChoicesSegmentedControl.isEnabled = true answerChoicesSegmentedControl.selectedSegmentIndex = -1 progressBar.progress = 0 internalMultiplicand = 0 internalMultiplier = 0 internalResult = 0 attempts = 0 totalCorrect = 0 internalResultCollection = [Int]() questionsStatus.text = "\(totalCorrect)/\(attempts) Questions Correct" questionStatusAlias.text = questionsStatus.text result.text = String("___") correctLabel.textColor = UIColor.black correctLabel.text = "You are..." submitNextButton.setTitle("Submit", for: UIControlState.normal) submitNextButton.isEnabled = false hintButton.isEnabled = true generateMultiplicationValues() } @IBAction func hintRequest(_ sender: Any) { var value = 0 var i = 0 var remove = 0 // Can only remove two random answers. if answerChoicesSegmentedControl.numberOfSegments >= 3 { while i < answerChoicesSegmentedControl.numberOfSegments { value = Int(answerChoicesSegmentedControl.titleForSegment(at: i)!)! if value == internalResult { internalResultIndex = i } i = i + 1 } remove = internalResultIndex while remove == internalResultIndex { remove = Int(arc4random_uniform(UInt32(answerChoicesSegmentedControl.numberOfSegments))) } answerChoicesSegmentedControl.removeSegment(at: remove, animated: true) } else { hintButton.isEnabled = false } } @IBAction func segmentedControlAction(_ sender: Any) { submitNextButton.isEnabled = true } @IBAction func submitAndNextButton(_ sender: Any) { // Function for dealing with what to do if Submit or Next button are pressed. if submitNextButton.currentTitle == "Submit" { let selectedChoice = answerChoicesSegmentedControl.selectedSegmentIndex answerChoicesSegmentedControl.isEnabled = false hintButton.isEnabled = false result.text = String(internalResult) // Since I know I will have something in my segmented control, I force unwrap the value. if Int(answerChoicesSegmentedControl.titleForSegment(at: selectedChoice)!)! != internalResult { correctLabel.textColor = UIColor.red correctLabel.text = "Wrong!" attempts = attempts + 1 } else { correctLabel.textColor = UIColor.green correctLabel.text = "Correct!" attempts = attempts + 1 totalCorrect = totalCorrect + 1 progressBar.progress = progressBar.progress + 0.2 } questionsStatus.text = "\(totalCorrect)/\(attempts) Questions Correct" questionStatusAlias.text = questionsStatus.text if totalCorrect == 5 { let alert = UIAlertController(title: "Congrats!", message: "You answered correctly 5 times, hit OK to restart!", preferredStyle: UIAlertControllerStyle.alert) alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil)) self.present(alert, animated: true, completion: nil) startAndRestartGame() } else { submitNextButton.setTitle("Next", for: UIControlState.normal) } } else { result.text = String("___") internalResultCollection = [Int]() generateMultiplicationValues() correctLabel.textColor = UIColor.black correctLabel.text = "You are..." submitNextButton.setTitle("Submit", for: UIControlState.normal) submitNextButton.isEnabled = false answerChoicesSegmentedControl.isEnabled = true hintButton.isEnabled = true answerChoicesSegmentedControl.selectedSegmentIndex = -1 } } override func viewDidLoad() { super.viewDidLoad() startAndRestartGame() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // infoPaisScreen.swift // dasCriancas // // Created by Cassia Aparecida Barbosa on 16/07/19. // Copyright © 2019 Cassia Aparecida Barbosa. All rights reserved. // import UIKit class infoPaisScreen: UIViewController { @IBOutlet var descricao: UILabel! @IBOutlet var imagem: UIImageView! var paisScreenImages: [UIImage] = [UIImage(named: "pS1")!, UIImage(named: "pS2")!, UIImage(named: "pS3")!, UIImage(named: "pS4")!, UIImage(named: "pS5")!, UIImage(named: "pS6")!, UIImage(named: "pS7")!, UIImage(named: "pS8")!, UIImage(named: "pS9")!, UIImage(named: "pS10")!, UIImage(named: "pS11")!] override func viewDidLoad() { super.viewDidLoad() imagem.frame.size.width = self.view.frame.width * 0.7 imagem.frame.size.height = self.view.frame.height * 0.6 imagem.center.x = self.view.center.x imagem.center.y = self.view.center.y * 1.34 imagem.animationImages = paisScreenImages imagem.animationDuration = 11 imagem.startAnimating() imagem.layer.cornerRadius = 10 imagem.layer.borderWidth = 2 imagem.layer.borderColor = #colorLiteral(red: 0.1019607857, green: 0.2784313858, blue: 0.400000006, alpha: 1) descricao.adjustsFontForContentSizeCategory = true } }
// // ProductEntity+CoreDataProperties.swift // Store // // Created by Vladimir on 24/08/2019. // Copyright © 2019 VladimirYakutin. All rights reserved. // // import Foundation import CoreData extension ProductEntity { @nonobjc public class func fetchRequest() -> NSFetchRequest<ProductEntity> { return NSFetchRequest<ProductEntity>(entityName: "ProductEntity") } @NSManaged public var cost: Int64 @NSManaged public var productDescription: String @NSManaged public var name: String }
// // Created by zh on 2021/6/28. // public enum BrickResponse<T: BrickModel> { case error(String?) case success(T) } extension BrickResponse { var result: T? { guard case let .success(r) = self else { return nil } return r } var error: String? { guard case let .error(e) = self else { return nil } return e } var isSuccessful: Bool { let code = result?.code ?? -999 return code == Providers.instance.successfulCode } }
// // ColorThemeCollectionViewCell.swift // Task 12 Wallets // // Created by Liza Kryshkovskaya on 29.09.21. // import UIKit class ColorThemeCollectionViewCell: UICollectionViewCell { var imageView: UIImageView = { let view = UIImageView() let blurEffect = UIBlurEffect(style: UIBlurEffect.Style.light) let blurEffectView = UIVisualEffectView(effect: blurEffect) blurEffectView.frame = view.bounds blurEffectView.autoresizingMask = [.flexibleWidth, .flexibleHeight] // view.addSubview(blurEffectView) view.translatesAutoresizingMaskIntoConstraints = false return view }() override init(frame: CGRect) { super.init(frame: frame) configure() } required init?(coder: NSCoder) { fatalError("Not implemented") } func configure() { backgroundColor = .clear let view = KLView() addSubview(view) view.addSubview(imageView) NSLayoutConstraint.activate([ view.topAnchor.constraint(equalTo: topAnchor), view.leftAnchor.constraint(equalTo: leftAnchor), view.rightAnchor.constraint(equalTo: rightAnchor), view.bottomAnchor.constraint(equalTo: bottomAnchor) ]) NSLayoutConstraint.activate([ imageView.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 25), imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor, constant: -25), imageView.topAnchor.constraint(equalTo: view.topAnchor, constant: 30), imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -30) ]) } }
// // DateExtensions.swift // GoodJob // // Created by Mookyung Kwak on 2016-12-14. // Copyright © 2016 Mookyung Kwak. All rights reserved. // import Foundation extension Date { func toFriendlyDateTimeString(_ numericDates:Bool) -> String { let calendar = Calendar.current let now = Date() //print(now) //print(self) let earliest = (now as NSDate).earlierDate(self) let latest = (earliest == now) ? self : now let components:DateComponents = (calendar as NSCalendar).components([NSCalendar.Unit.minute , NSCalendar.Unit.hour , NSCalendar.Unit.day , NSCalendar.Unit.weekOfYear , NSCalendar.Unit.month , NSCalendar.Unit.year , NSCalendar.Unit.second], from: earliest, to: latest, options: NSCalendar.Options()) //print(components) if (components.year! >= 2) { return "\(components.year!)년전" } else if (components.year! >= 1){ if (numericDates){ return "1년전" } else { return "작년" } } else if (components.month! >= 2) { return "\(components.month!)달전" } else if (components.month! >= 1){ if (numericDates){ return "1달전" } else { return "지난달" } } else if (components.weekOfYear! >= 2) { return "\(components.weekOfYear!)주전" } else if (components.weekOfYear! >= 1){ if (numericDates){ return "1주전" } else { return "지난주" } } else if (components.day! >= 2) { return "\(components.day!)일전" } else if (components.day! >= 1){ if (numericDates){ return "1일전" } else { return "어제" } } else if (components.hour! >= 2) { return "\(components.hour!)시간전" } else if (components.hour! >= 1){ if (numericDates){ return "1시간전" } else { return "한시간전" } } else if (components.minute! >= 2) { return "\(components.minute!)분전" } else if (components.minute! >= 1){ if (numericDates){ return "1분전" } else { return "일분전" } } else if (components.second! >= 3) { return "\(components.second!)초전" } else { return "몇초전" } } }
// // AuthorizationManager.swift // mobiita // // Created by Shunsaku Miki on 2017/06/21. // Copyright © 2017年 Shunsaku Miki. All rights reserved. // import UIKit final class AuthorizationManager { // MARK: - Methods /// Auth認証用URL生成 /// /// - Returns: URL private class func genAuthUrl() -> URL?{ return URL(string: kAuthUrl + "?" + prefixCilentId + kClientId + "&" + preficScope + kScope) } /// 認証画面表示 class func openOAuthUrl() { guard let url = genAuthUrl() else { return } UIApplication.shared.openURL(url) } /// アクセストークン取得用コード生成 /// /// - Parameter arg: コードが含まれている文字列 class func genCode(_ arg: String) -> String { guard arg.contains("code=") else { return "" } var strArr = arg.components(separatedBy: "=") return strArr[1] } // MARK: - Property /** qiitaAPIクライアントID */ static let kClientId = "de1b2dd6bd71d8c71fbdce0e066562c759bcce9a" /** QiitaクライントSecret */ static let kClientSecret = "f6551191b43e82c3de17fa665da9f8ddd0a9c5b5" /** 認証用サイトURL */ static let kAuthUrl = "https://qiita.com/api/v2/oauth/authorize" /** スコープ(クエリ) */ static let kScope = "read_qiita" /** State(クエリ) */ static let kState = "" /** クライアントIDキー */ static let prefixCilentId = "client_id=" /** scopeキー */ static let preficScope = "scope=" }
// // CoreExtensions.swift // PunchOutTabs // // Created by Steve Goldman on 7/6/15. // Copyright (c) 2015 Steve Goldman. All rights reserved. // import UIKit extension UIStoryboardSegue { // MARK: - Properties var displayController: UIViewController { if let navController = destinationViewController as? UINavigationController { return navController.visibleViewController } return destinationViewController as! UIViewController } }
// // File.swift // // // Created by Sendbird-Jaesung on 2020/07/03. // import UIKit /** `URL` 통해서 가져온 이미지를 캐싱합니다. 캐싱된 이미지가 없으면 `load(url:completion:)` `URL` 요청을 통해 이미지를 로딩합니다. */ class ImageCache { typealias imageHandler = ((UIImage?, Error?) -> ()) static let shared = ImageCache() enum ImageCacheError: Error { case failedToLoadImage } func cachedImage(for imageRequest: URLRequest) -> UIImage? { // If there is no cached response for the image request, return immediately. guard let data = URLCache.shared.cachedResponse(for: imageRequest)?.data else { return nil } return UIImage(data: data) } func load(url: URL, completion: @escaping imageHandler) { DispatchQueue.global(qos: .userInitiated).async { // useProtocolCachePolicy: A default policy for URL load requests. let imageRequest = URLRequest(url: url, cachePolicy: .useProtocolCachePolicy) // If there is cached image, return immediately. if let cachedImage = self.cachedImage(for: imageRequest) { completion(cachedImage, nil) return } URLSession.shared.dataTask(with: imageRequest) { data, response, error in // If image is invalid, return immediately. guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let data = data, let image = UIImage(data: data), error == nil else { completion(nil, ImageCacheError.failedToLoadImage) return } // Cache response and return loaded image let cacheData = CachedURLResponse(response: httpURLResponse, data: data) URLCache.shared.storeCachedResponse(cacheData, for: imageRequest) completion(image, nil) } .resume() } } }
// // AppCoordinator.swift // Halo Mind // // Created by Alan Fineberg on 3/13/18. // Copyright © 2018 Halo Neuro. All rights reserved. // import Foundation import UIKit class AppCoordinator:GameLoadingCoordinatorDelegate, GamePlayCoordinatorDelegate, GameOverCoordinatorDelegate { private let window: UIWindow private let navigationController: UINavigationController var gameLoadingCoordinator:GameLoadingCoordinator? var gamePlayCoordinator: GamePlayCoordinator? var gameOverCoordinator: GameOverCoordinator? init(window: UIWindow) { self.window = window self.navigationController = UINavigationController() } func start() { if let userID = UserDefaults.standard.object(forKey: "userID") { // get config from server } else { let userID = UUID().uuidString UserDefaults.standard.set(userID, forKey: "userID") } let navRootViewController = UIViewController() navRootViewController.view.backgroundColor = UIColor.blue navigationController.pushViewController(navRootViewController, animated: false) navigationController.setNavigationBarHidden(true, animated: false) window.rootViewController = navigationController startGame() } func startGame() { gameLoadingCoordinator = GameLoadingCoordinator(delegate: self, pushViewController: pushViewController) gameLoadingCoordinator?.start() } private func pushViewController(viewController: UIViewController) { DispatchQueue.main.async { [weak self] in self?.navigationController.show(viewController, sender: self) } } func didStartGame(game:NBackGame, images:Dictionary<String, UIImage>) { gameLoadingCoordinator = nil gamePlayCoordinator = GamePlayCoordinator(delegate: self, pushViewController: pushViewController, game: game, images: images) gamePlayCoordinator?.start() } func gameEnded(result:NBackResult) { gamePlayCoordinator = nil gameOverCoordinator = GameOverCoordinator(delegate: self, pushViewController: pushViewController, gameResult: result) gameOverCoordinator?.start() } func didTapRestart() { gameOverCoordinator = nil navigationController.popToRootViewController(animated: true) startGame() } }
// // MenuScene.swift // ColorSwitchClone // // Created by Samuel Reaves on 9/4/21. // import SpriteKit class MenuScene: SKScene { let fontName = "AvenirNext-Bold" override func didMove(to view: SKView) { backgroundColor = UIColor(red: 44/255, green: 62/255, blue: 80/255, alpha: 1.0) addLogo() addLabels() } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { for touch in touches { let location = touch.location(in: self) let touchedNode = self.nodes(at: location) for node in touchedNode { if node.name == "playLabel" { startGame() } } } } func addLogo() { let logo = SKSpriteNode(imageNamed: "colorcircle") logo.size = CGSize(width: frame.width / 4, height: frame.width / 4) logo.position = CGPoint(x: frame.midX, y: frame.midY + frame.size.height / 4) addChild(logo) } func addLabels() { let playLabel = SKLabelNode(text: "Tap to Play") playLabel.fontName = fontName playLabel.fontSize = 40.0 playLabel.position = CGPoint(x: frame.midX, y: frame.midY) playLabel.name = "playLabel" addChild(playLabel) animateLabel(label: playLabel) let highScoreLabel = SKLabelNode(text: "High Score: \(UserDefaults.standard.integer(forKey: "highScore"))") highScoreLabel.fontName = fontName highScoreLabel.fontSize = 26.0 highScoreLabel.position = CGPoint(x: frame.midX, y: frame.midY - highScoreLabel.frame.size.height * 4) addChild(highScoreLabel) let lastScoreLabel = SKLabelNode(text: "Last Score: \(UserDefaults.standard.integer(forKey: "lastScore"))") lastScoreLabel.fontName = fontName lastScoreLabel.fontSize = 26.0 lastScoreLabel.position = CGPoint(x: frame.midX, y: highScoreLabel.position.y - lastScoreLabel.frame.size.height * 2) addChild(lastScoreLabel) } func animateLabel(label: SKLabelNode) { let scaleUp = SKAction.scale(by: 1.05, duration: 0.82) let scaleDown = SKAction.scale(by: 0.95, duration: 0.82) let sequence = SKAction.sequence([scaleUp, scaleDown]) label.run(SKAction.repeatForever(sequence)) } func startGame() { let gameScene = GameScene(size: view!.bounds.size) view?.presentScene(gameScene) } }
// // ViewController.swift // CayugasoftTest2 // // Created by Alexander on 16.02.16. // Copyright © 2016 Alexander. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var graphView: GraphView! override func viewDidLoad() { super.viewDidLoad() graphView.f = { 0.01 * $0 * $0 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
// // ViewController.swift // fileTable // // Created by Jz D on 2020/3/14. // Copyright © 2020 Jz D. All rights reserved. // import Cocoa class ViewController: NSViewController { @IBOutlet weak var tableView: NSTableView! let tbProxy = TableProxy() override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. tableView.delegate = tbProxy tableView.dataSource = tbProxy tableView.reloadData() } override var representedObject: Any? { didSet { // Update the view, if already loaded. } } }
// // CLLocationCoordinate.swift // Vmee // // Created by Micha Volin on 2017-01-01. // Copyright © 2017 Vmee. All rights reserved. // import MapKit extension CLLocationCoordinate2D { func toCLLocation()->CLLocation { return CLLocation(latitude: latitude, longitude: longitude) } }
// // ContentView.swift // challengeM4.TabViews // // Created by David Estrada on 7/27/21. // import SwiftUI struct ContentView: View { @State var tabTag = 0 var body: some View { TabView (selection: $tabTag) { Text("This tab’s tag is \(tabTag).") .tabItem { VStack { Image(systemName: "tortoise") Text("Tab1") } } .tag(0) Button("Take me to tab3") { tabTag = 2 } .tabItem { VStack { Image(systemName: "arrow.right.circle.fill") Text("Tab2") } } .tag(1) List { ForEach(0..<100) { _ in Text("Te Amo cara de Marranito") } } .tabItem { VStack { Image(systemName: "hands.clap") Text("Tab 3") } } .tag(2) } } } struct ContentView_Previews: PreviewProvider { static var previews: some View { ContentView() } }
// // CountryNameTableCell.swift // Parsing Test // // Created by Saif Aion on 5/8/17. // Copyright © 2017 Saif Aion. All rights reserved. // import UIKit class CountryNameTableCell: UITableViewCell { @IBOutlet var imgView: UIImageView! @IBOutlet var authorLabel: UILabel! @IBOutlet var titleLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
// // ViewCalculated.swift // WavesWallet-iOS // // Created by mefilt on 25.07.2018. // Copyright © 2018 Waves Platform. All rights reserved. // import UIKit public protocol ViewCalculateHeight { associatedtype Model static func viewHeight(model: Model, width: CGFloat) -> CGFloat } public protocol ViewHeight { static func viewHeight() -> CGFloat }
// // HomerViewControllerExtensions.swift // CafeNomad // // Created by Albert on 2019/1/20. // Copyright © 2019 Albert.C. All rights reserved. // import Foundation import UIKit extension HomeViewController: UITableViewDataSource, UITableViewDelegate{ //MARK: TableView Functions func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if (search?.isActive)! { return searchResultArray.count } else { return cafeShopArray.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! HomePageTableViewCell let searchs = ((search?.isActive)!) ? searchResultArray[indexPath.row] : cafeShopArray[indexPath.row] cell.shopNameLabel.text = searchs.name cell.shopAddressLabel.text = searchs.address return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } //MRAK: Animate func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) { cell.alpha = 0 UIView.animate(withDuration: 0.2, delay: 0, options: .allowUserInteraction, animations: { cell.alpha = 1 }, completion: nil) } } extension HomeViewController: UISearchControllerDelegate, UISearchResultsUpdating { //MARK: Search Bar Funcations func settingSearchController() { search = UISearchController(searchResultsController: nil) search?.searchBar.autocapitalizationType = .none if #available(iOS 11.0, *) { navigationItem.searchController = search navigationItem.hidesSearchBarWhenScrolling = false } else { tableView.tableHeaderView = search?.searchBar } search?.delegate = self search?.searchResultsUpdater = self search?.dimsBackgroundDuringPresentation = false search?.searchBar.barTintColor = .white search?.searchBar.tintColor = UIColor(red: 0, green: 0, blue: 0, alpha: 1) search?.searchBar.searchBarStyle = .default search?.searchBar.placeholder = "搜尋店名、地址" definesPresentationContext = true } func filterContent(for searchText: String) { searchResultArray = cafeShopArray.filter({ (results) -> Bool in let name = results.name, address = results.address let isMach = name.localizedCaseInsensitiveContains(searchText) || address.localizedCaseInsensitiveContains(searchText) return isMach }) } func updateSearchResults(for searchController: UISearchController) { if let searchText = searchController.searchBar.text { filterContent(for: searchText) tableView.reloadData() } } }
// // MainViewController+UITableView.swift // LBCOffers // // Created by Mohamed Derkaoui on 12/04/2020. // Copyright © 2020 Mohamed Derkaoui. All rights reserved. // import UIKit extension MainViewController: UITableViewDelegate, UITableViewDataSource { func setupTableView() { self.tableView.frame = self.view.bounds self.view.addSubview(tableView) tableView.register(ArticleTableViewCell.self, forCellReuseIdentifier: "ArticleTableViewCell") tableView.dataSource = self tableView.delegate = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return self.articles?.count ?? 0 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCell(withIdentifier: "ArticleTableViewCell", for: indexPath) as? ArticleTableViewCell, let article = self.articles?[indexPath.row] { cell.setupCellWith(article: article) cell.categoryLabel.text = self.getCategoryOf(article) cell.selectionStyle = .none return cell } return UITableViewCell() } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 80 } }
// // DefaultHeaderFooterProperties.swift // ListableUI // // Created by Kyle Van Essen on 6/27/21. // import Foundation /// Allows specifying default properties to apply to a header / footer when it is initialized, /// if those values are not provided to the initializer. /// Only non-nil values are used – if you do not want to provide a default value, /// simply leave the property nil. /// /// The order of precedence used when assigning values is: /// 1) The value passed to the initializer. /// 2) The value from `defaultHeaderFooterProperties` on the contained `HeaderFooterContent`, if non-nil. /// 3) A standard, default value. public struct DefaultHeaderFooterProperties<Content:HeaderFooterContent> { public var sizing : Sizing? public var layouts : HeaderFooterLayouts? public init( sizing : Sizing? = nil, layouts : HeaderFooterLayouts? = nil ) { self.sizing = sizing self.layouts = layouts } }
// // commits.swift // Gopher // // Created by Dane Acena on 8/15/21. // import Foundation // Codable - used for decoding and ecoding the JSON data we get from our API call // Identifiable - used to help us make a unique identifier for our Commit object so the app can keep track of it struct Repository: Codable{ var sha: String var commit: Commit } struct Commit: Codable { let id: Int let author: Author } struct Author: Codable { let name: String }
import UIKit protocol CollectionViewModelDelegate: class { func didChangeTotalSlots(toSlots: UInt) func didChangeCompletedSlots(toSlots: UInt) } /// The collection view model keeps the collection view logic from the table view cell. This logic /// could be interchangable in the future. class CollectionViewModel: NSObject, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { static let CollectionCellIdentifier: String = "CollectionCellIdentifier" weak var delegate: CollectionViewModelDelegate? /// This represents how many slots can possibly be filled. fileprivate var numberOfSlots: UInt /// This represents the index of the furthest most completed slot. var slotCompleteIndex: Int = 0 var editMode: Bool = false { didSet { if !editMode && slotCompleteIndex == Int(numberOfSlots) { slotCompleteIndex -= 1 } } } init(numberOfSlots: UInt) { self.numberOfSlots = numberOfSlots super.init() } func numberOfSections(in collectionView: UICollectionView) -> Int { return 1 } func collectionView( _ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { var numberOfItems = Int(numberOfSlots) if editMode { numberOfItems += 1 } return numberOfItems } func collectionView( _ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell( withReuseIdentifier: CollectionViewModel.CollectionCellIdentifier, for: indexPath) as! SpellSlotsCollectionViewCell if indexPath.row > slotCompleteIndex { cell.deselect() } else { cell.select() } cell.isPlusCell = indexPath.row == Int(numberOfSlots) return cell } func collectionView( _ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { return CGSize( width: SpellSlotsCollectionViewCell.SpellSlotDiameter, height: SpellSlotsCollectionViewCell.SpellSlotDiameter) } func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) { collectionView.deselectItem(at: indexPath, animated: true) // Touching the cell at this index path row means the user is touching the plus button. if indexPath.row == Int(numberOfSlots) { numberOfSlots += 1 delegate?.didChangeTotalSlots(toSlots: numberOfSlots) collectionView.reloadData() return } // Touching on a plain cell while in edit mode will shrink the row back down to that point. if editMode { numberOfSlots = UInt(indexPath.row) delegate?.didChangeTotalSlots(toSlots: numberOfSlots) if slotCompleteIndex >= indexPath.row { slotCompleteIndex = indexPath.row - 1 delegate?.didChangeCompletedSlots(toSlots: UInt(slotCompleteIndex + 1)) } collectionView.reloadData() return } // Normal behavior of touching a cell. if indexPath.row == slotCompleteIndex { slotCompleteIndex = indexPath.row - 1 } else { slotCompleteIndex = indexPath.row } delegate?.didChangeCompletedSlots(toSlots: UInt(slotCompleteIndex + 1)) collectionView.reloadData() } }
// // Track.swift // SurfSchoolRadio // // Created by Nastya on 4/22/20. // Copyright © 2020 Surf. All rights reserved. // import UIKit struct Track { var title: String var artist: String var albumImage: UIImage? var albumLoaded = false init(title: String, artist: String) { self.title = title self.artist = artist } }
// // ContentVC.swift // EduTest // // Created by Noe Osorio on 08/06/18. // Copyright © 2018 Noe Osorio. All rights reserved. // import UIKit class ContentVC: UIViewController, UITableViewDelegate, UITableViewDataSource { var lecturas: [Lectura] = [] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 3 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "lectura", for: indexPath) as! LectureCell cell.subtitulo.text = "Subtema \(indexPath.row)" cell.texto.text = "En esta seccion va a ir el contenido del subtema que estemos trabajando" if let img:String = "university.png"{ cell.imagen.image = UIImage(named: img) } return cell } } struct Lectura{ var subtema: String? var texto: String? var imagen: UIImage? init(subtema: String, texto: String, imagen: String){ self.subtema = subtema self.texto = texto self.imagen = UIImage(named: imagen) } init(subtema: String, texto: String, imagen: UIImage){ self.subtema = subtema self.texto = texto self.imagen = imagen } }
// // MyCollection.swift // mapfinderme // // Created by pramono wang on 8/11/16. // Copyright © 2016 fnu. All rights reserved. // import UIKit class MyCollection: UICollectionViewController { let allSectionColors = [ UIColor.redColor(), UIColor.greenColor(), UIColor.blueColor() ] override init(collectionViewLayout layout: UICollectionViewLayout) { super.init(collectionViewLayout: layout) collectionView?.registerClass(UICollectionViewCell.classForCoder(), forCellWithReuseIdentifier: "cell") } convenience required init?(coder aDecoder: NSCoder) { let flowLayout = UICollectionViewFlowLayout() flowLayout.minimumLineSpacing = 20 flowLayout.minimumInteritemSpacing = 10 flowLayout.itemSize = CGSize(width: 80, height: 80) flowLayout.scrollDirection = .Vertical flowLayout.sectionInset = UIEdgeInsets(top: 10, left: 20, bottom: 10, right: 20) self.init(collectionViewLayout: flowLayout) } }
//: Playground - noun: a place where people can play import UIKit let name = "world" if name == "world" { print("hello, world") } else { print("I'm sorry \(name), but I don't recognize you") } /** The Swift standard library includes tuple comparison operators for tuples with fewer than seven elements. To compare tuples with seven or more elements, you must implement the comparison operators yourself. (1, "zebra") < (2, "apple") // true because 1 is less than 2; "zebra" and "apple" are not compared (3, "apple") < (3, "bird") // true because 3 is equal to 3, and "apple" is less than "bird" (4, "dog") == (4, "dog") // true because 4 is equal to 4, and "dog" is equal to "dog" */ var a:Int? = 2 var b = 3 var c = a ?? b // var c = (a != nil ? a! : b) for index in 1...5 {// [1,5] print("\(index) times 5 is \(index * 5)") } let names = ["Anna", "Alex", "Brian", "Jack"] let count = names.count for i in 0..<count {//[a,count) print("Person \(i + 1) is called \(names[i])") }
// // UserSessionNavigationBar.swift // diverCity // // Created by Lauren Shultz on 3/11/19. // Copyright © 2019 Lauren Shultz. All rights reserved. // import Foundation import UIKit class UserSessionNavigaitonBar: UINavigationBar { init (frame: CGRect, menuOptions: [MenuItemButton]) { super.init(frame: frame) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
//===----------------------------------------------------------------------===// // // This source file is part of the SwiftNIO open source project // // Copyright (c) 2021 Apple Inc. and the SwiftNIO project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of SwiftNIO project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// import Crypto import NIO import NIOSSH final class BenchmarkLinearThroughput: Benchmark { let serverRole = SSHConnectionRole.server(.init(hostKeys: [.init(ed25519Key: .init())], userAuthDelegate: ExpectPasswordDelegate("password"))) let clientRole = SSHConnectionRole.client(.init(userAuthDelegate: RepeatingPasswordDelegate("password"), serverAuthDelegate: ClientAlwaysAcceptHostKeyDelegate())) let b2b = BackToBackEmbeddedChannel() let messageCount: Int let messageSize: Int private var message: ByteBuffer? private var channel: Channel? init(messageCount: Int, messageSize: Int) { self.messageCount = messageCount self.messageSize = messageSize } func setUp() throws { self.b2b.client.connect(to: try .init(unixDomainSocketPath: "/foo"), promise: nil) self.b2b.server.connect(to: try .init(unixDomainSocketPath: "/foo"), promise: nil) let clientHandler = NIOSSHHandler(role: self.clientRole, allocator: self.b2b.client.allocator, inboundChildChannelInitializer: nil) try self.b2b.client.pipeline.addHandler(clientHandler).wait() try self.b2b.server.pipeline.addHandler(NIOSSHHandler(role: self.serverRole, allocator: self.b2b.server.allocator, inboundChildChannelInitializer: nil)).wait() try self.b2b.interactInMemory() let clientChannelPromise = self.b2b.client.eventLoop.makePromise(of: Channel.self) clientHandler.createChannel(clientChannelPromise, channelType: .session) { channel, _ in channel.eventLoop.makeSucceededVoidFuture() } try self.b2b.interactInMemory() self.channel = try clientChannelPromise.futureResult.wait() self.message = ByteBuffer(repeating: 0xFF, count: self.messageSize) } func tearDown() {} func run() throws -> Int { let channel = self.channel! let message = SSHChannelData(type: .channel, data: .byteBuffer(self.message!)) for _ in 0 ..< self.messageCount { channel.writeAndFlush(message, promise: nil) try self.b2b.interactInMemory() } return self.messageCount } }
// // UIView+StyleKit.swift // StyleKitSample // // Created by Van Nguyen on 4/5/16. // Copyright © 2016 Tonic Design. All rights reserved. // import UIKit extension UIView { private struct AssociatedKeys { static var styleTag = "" } @IBInspectable var styleTag: String? { get { return objc_getAssociatedObject(self, &AssociatedKeys.styleTag) as? String } set { if let newValue = newValue { objc_setAssociatedObject( self, &AssociatedKeys.styleTag, newValue as NSString?, .OBJC_ASSOCIATION_RETAIN_NONATOMIC ) } } } }
// // HudView.swift // MyLocations // // Created by 张润峰 on 2016/12/1. // Copyright © 2016年 FighterRay. All rights reserved. // import UIKit class HudView: UIView { var text = "" // Convinience constructor class func hud(inView view: UIView, animated: Bool) -> HudView { let hudView = HudView(frame: view.bounds) view.addSubview(hudView) view.isUserInteractionEnabled = false hudView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0) hudView.show(animated: true) return hudView } override func draw(_ rect: CGRect) { let boxWidth:CGFloat = 95 let boxHeight:CGFloat = 95 let boxRect = CGRect(x: round((bounds.size.width - boxWidth) / 2), y: round((bounds.size.height - boxHeight) / 2), width: boxWidth, height: boxHeight) let roundedRect = UIBezierPath(roundedRect: boxRect, cornerRadius: 10) UIColor(white: 0.3, alpha: 0.8).setFill() roundedRect.fill() // Add checkmark image if let image = UIImage(named: "checkmark") { let imagePoint = CGPoint(x: center.x - image.size.width / 2, y: center.y - image.size.height / 2 - boxHeight / 8) image.draw(at: imagePoint) } // Add text let attribs = [ NSFontAttributeName: UIFont.systemFont(ofSize: 16), NSForegroundColorAttributeName: UIColor.white] let textSize = text.size(attributes: attribs) let textPoint = CGPoint(x: center.x - round(textSize.width / 2), y: center.y - round(textSize.height / 2) + boxHeight / 4) text.draw(at: textPoint, withAttributes: attribs) } func show(animated: Bool) { if animated { alpha = 0 transform = CGAffineTransform(scaleX: 1.3, y: 1.3) UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 0.5, options: [], animations: { self.alpha = 1 self.transform = CGAffineTransform.identity }, completion: nil) } } }
// // Label+CoreDataClass.swift // FundooApp // // Created by admin on 29/06/20. // Copyright © 2020 admin. All rights reserved. // // import Foundation import CoreData public class Label: NSManagedObject { }
// // GameFactory.swift // TicTacToe // // Created by 2019_DEV_108 // @Brief: creates and configures GameViewController import Foundation import UIKit class GameFactory { func make() -> UIViewController { // gameViewController is a fixed 3x3 grid, but the viewModel is dynamic let viewModel = GameViewModelDefault(withGridSize: 3, players: ["🤖","😺"]) let gameViewController = GameViewController(withViewModel: viewModel) viewModel.delegate = gameViewController return UINavigationController(rootViewController: gameViewController) } }
//: Playground - noun: a place where people can play import UIKit // var myNumber = [4,5,6,3,9,7] for number in myNumber { print(number) } for (index, value) in myNumber.enumerated() { myNumber[index] += 1 } print(myNumber) // var checkArray = [Double]() checkArray = [2,5,56,13,8,7,9] for (index, value) in checkArray.enumerated() { checkArray[index] = value/2 } print(checkArray)
// // PhotoVCExt-CoreData.swift // Virtual Tourist // // Created by Che-Chuen Ho on 6/30/15. // Copyright (c) 2015 Che-Chuen Ho. All rights reserved. // import CoreData extension PhotosViewController: NSFetchedResultsControllerDelegate { }
// // ContentTableViewCell.swift // carolina_fever_0 // // Created by Caleb Kang on 7/26/19. // Copyright © 2019 Caleb Kang. All rights reserved. // import UIKit /*each object of this class will represent a fever game, with a time, description and number of points**/ class ContentTableViewCell: UITableViewCell { @IBOutlet var date: UILabel! @IBOutlet var gameString: UILabel! @IBOutlet var points: UILabel! override func awakeFromNib() { super.awakeFromNib() } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) self.selectionStyle = UITableViewCell.SelectionStyle.none } }
// // StoryViewController.swift // // // Created by Jacorey Brown on 3/19/19. // import UIKit class StoryViewController : UIViewController { let dismissButton : UIButton = { let button = UIButton(type: .system) button.setImage(#imageLiteral(resourceName: "cancel"), for: .normal) button.translatesAutoresizingMaskIntoConstraints = false button.addTarget(self, action: #selector(dismissScreen), for: .touchUpInside) return button }() override func viewDidLoad() { super.viewDidLoad() view.backgroundColor = .black setupDismissButton() } func setupDismissButton() { view.addSubview(dismissButton) dismissButton.anchor(top: view.topAnchor, leading: view.leadingAnchor, bottom: nil, trailing: nil, padding: UIEdgeInsets(top: 30, left: 15, bottom: 0, right: 0), size: CGSize(width: 25, height: 25)) } @objc func dismissScreen() { dismiss(animated: true, completion: nil) } }
// // BHJAnimation.swift // gravida // // Created by bhj on 2017/6/28. // Copyright © 2017年 bhj.com. All rights reserved. // import UIKit extension CAPropertyAnimation { class func bhj_tabBar() -> CAPropertyAnimation { // 1.创建动画 let rotationAnim = CABasicAnimation(keyPath: "transform.rotation.z") // 2.设置动画的属性 rotationAnim.fromValue = 0 rotationAnim.toValue = Double.pi * 2 rotationAnim.repeatCount = MAXFLOAT rotationAnim.duration = 5 // 这个属性很重要 如果不设置当页面运行到后台再次进入该页面的时候 动画会停止 rotationAnim.isRemovedOnCompletion = false return rotationAnim } }
// // MealTableViewController.swift // FoodTracker // // Created by GUIEEN on 5/8/19. // Copyright © 2019 GUIEEN. All rights reserved. // import UIKit import os.log class MealTableViewController: UITableViewController { //MARK: Properties var meals = [Meal]() override func viewDidLoad() { super.viewDidLoad() // Use the edit button item provided by the table view controller. // This will generate the screen like this:: (-) <- [ -----= ITEM =----- ] -> (Delete) navigationItem.leftBarButtonItem = editButtonItem // Load any saved meals, otherwise load sample data. if let savedMeals = loadMeals() { meals += savedMeals } else { // Load the sample data. loadSampleMeals() } } // MARK: - Table view data source // tells the table view how many sections to display override func numberOfSections(in tableView: UITableView) -> Int { return 1 } // tells the table view how many rows to display in a given section override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return meals.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { // Table view cells are reused and should be dequeued using a cell identifier. let cellIdentifier = "MealTableViewCell" // If no cells are available, dequeueReusableCell(withIdentifier:for:) instantiates a new one; however, as cells scroll off the scene, they are reused. The identifier tells dequeueReusableCell(withIdentifier:for:) which type of cell it should create or reuse. // -- In short, cells in the screen != CANNOT BE REUSED ;; cells out of the screen == REUSABLE so it won't try to make a new one to showing the cell in the screen but try to insert only the data to that cell and re-use it. // `as? MealTableViewCell` == downcast ( cast to its subclass ) to our custom class inherited from `UITableViewCell` and this will return an optional. So we used `guard let` to unwrap the optional & clean code. guard let cell = tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath) as? MealTableViewCell else { fatalError("The dequeued cell is not an instance of MealTableViewCell.") } // Fetches the appropriate meal for the data source layout. let meal = meals[indexPath.row] cell.nameLabel.text = meal.name cell.photoImageView.image = meal.photo cell.ratingControl.rating = meal.rating return cell } // Override to support conditional editing of the table view. override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } // Override to support editing the table view. override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { // Delete the row from the data source meals.remove(at: indexPath.row) // Save the meals. saveMeals() tableView.deleteRows(at: [indexPath], with: .fade) } else if editingStyle == .insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } //MARK: Actions // This method must be marked with the IBAction attribute and take a segue (UIStoryboardSegue) as a parameter. Because you want to unwind back to the meal list scene, you need to add an action method with this format // You need to downcast because sender.sourceViewController is of type UIViewController, but you need to work with a MealViewController. // The operator returns an optional value, which will be nil if the downcast wasn’t possible. If the downcast succeeds, the code assigns the MealViewController instance to the local constant sourceViewController, and checks to see if the meal property on sourceViewController is nil. If the meal property is non-nil, the code assigns the value of that property to the local constant meal and executes the if statement. @IBAction func unwindToMealList(sender: UIStoryboardSegue) { if let sourceViewController = sender.source as? MealViewController, let meal = sourceViewController.meal { if let selectedIndexPath = tableView.indexPathForSelectedRow { // This code checks whether a row in the table view is selected. // Update an existing meal. meals[selectedIndexPath.row] = meal tableView.reloadRows(at: [selectedIndexPath], with: .none) } else { // Add a new meal. let newIndexPath = IndexPath(row: meals.count, section: 0) meals.append(meal) tableView.insertRows(at: [newIndexPath], with: .automatic) } // Save the meals. saveMeals() } } // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { super.prepare(for: segue, sender: sender) // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. switch(segue.identifier ?? "") { case "AddItem": os_log("Adding a new meal.", log: OSLog.default, type: .debug) case "ShowDetail": guard let mealDetailViewController = segue.destination as? MealViewController else { fatalError("Unexpected destination: \(segue.destination)") } guard let selectedMealCell = sender as? MealTableViewCell else { fatalError("Unexpected sender: \(String(describing: sender))") } guard let indexPath = tableView.indexPath(for: selectedMealCell) else { fatalError("The selected cell is not being displayed by the table") } let selectedMeal = meals[indexPath.row] mealDetailViewController.meal = selectedMeal default: fatalError("Unexpected Segue Identifier; \(String(describing: segue.identifier))") } } //MARK: Private Methods private func loadSampleMeals() { let photo1 = UIImage(named: "meal1") let photo2 = UIImage(named: "meal2") let photo3 = UIImage(named: "meal3") guard let meal1 = Meal(name: "Caprese Salad", photo: photo1, rating: 4) else { fatalError("Unable to instantiate meal1") } guard let meal2 = Meal(name: "Chicken and Potatoes", photo: photo2, rating: 5) else { fatalError("Unable to instantiate meal2") } guard let meal3 = Meal(name: "Pasta with Meatballs", photo: photo3, rating: 3) else { fatalError("Unable to instantiate meal2") } meals += [meal1, meal2, meal3] } private func saveMeals() { // Deprecated // let isSuccessfulSave = NSKeyedArchiver.archiveRootObject(meals, toFile: Meal.ArchiveURL.path) // if isSuccessfulSave { // os_log("Meals successfully saved.", log: OSLog.default, type: .debug) // } else { // os_log("Failed to save meals...", log: OSLog.default, type: .error) // } let fullPath = Meal.ArchiveURL do { let data = try NSKeyedArchiver.archivedData(withRootObject: meals, requiringSecureCoding: false) try data.write(to: fullPath) os_log("Meals successfully saved.", log: OSLog.default, type: .debug) } catch { os_log("Failed to save meals...", log: OSLog.default, type: .error) } } private func loadMeals() -> [Meal]? { // Deprecated // return NSKeyedUnarchiver.unarchiveObject(withFile: Meal.ArchiveURL.path) as? [Meal] let fullPath = Meal.ArchiveURL if let nsData = NSData(contentsOf: fullPath) { do { let data = Data(referencing:nsData) if let loadedMeals = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? Array<Meal> { return loadedMeals } } catch { print("Couldn't read file.") return nil } } return nil } }
import Foundation import Cocoa class Refraction : NSManagedObject { @NSManaged var indexOfRefraction : Float @NSManaged var environment : String? override init(entity: NSEntityDescription, insertIntoManagedObjectContext context: NSManagedObjectContext?) { super.init(entity: entity, insertIntoManagedObjectContext: context) } }
// // WordListViewController // Kotoba // // Created by Will Hains on 2014-11-24. // Copyright (c) 2014 Will Hains. All rights reserved. // import UIKit class WordListViewController: UITableViewController { override func viewDidLoad() { super.viewDidLoad() prepareEditButton() prepareSelfSizingTableCells() } deinit { NotificationCenter.default.removeObserver(self) } } // MARK:- Add "Edit" button extension WordListViewController { func prepareEditButton() { self.navigationItem.rightBarButtonItem = self.editButtonItem } func prepareTextLabelForDynamicType(label: UILabel?) { label?.font = .preferredFont(forTextStyle: UIFont.TextStyle.body) } } // MARK:- Dynamic Type extension WordListViewController { func prepareSelfSizingTableCells() { // Self-sizing table rows tableView.estimatedRowHeight = 44 tableView.rowHeight = UITableView.automaticDimension // Update view when dynamic type changes NotificationCenter.default.addObserver( self, selector: #selector(WordListViewController.dynamicTypeSizeDidChange), name: UIContentSizeCategory.didChangeNotification, object: nil) } @objc func dynamicTypeSizeDidChange() { self.tableView.reloadData() } } // MARK:- Tap a word in the list to see its description extension WordListViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { // Search the dictionary let word = words[indexPath.row] let _ = showDefinition(forWord: word) // Reset the table view self.tableView.deselectRow(at: indexPath, animated: true) } } // MARK:- Swipe left to delete words extension WordListViewController { override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { words.delete(wordAt: indexPath.row) self.tableView.deleteRows(at: [indexPath], with: .automatic) } } } // MARK:- Data source extension WordListViewController { override func numberOfSections(in tableView: UITableView) -> Int { // Just a single, simple list return 1 } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return words.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Word", for: indexPath) cell.textLabel?.text = words[indexPath.row].text prepareTextLabelForDynamicType(label: cell.textLabel) return cell } }
// // Writer.swift // WriterReader // // Created by Osmar Hernández on 23/10/18. // Copyright © 2018 Operating Systems. All rights reserved. // import Foundation class Writer { var frequencie: Float var dispatcher: DispatchQueue init() { self.frequencie = 9 self.dispatcher = DispatchQueue.global() } func writeInBuffer(_ buffer: inout [Int]) { if buffer.count > 100 { print("There's no space in buffer") } else { var temporalBuffer = buffer let randomNumber = Int(arc4random_uniform(UInt32(10))) sleepTask() temporalBuffer.append(randomNumber) buffer = temporalBuffer } } func getSleepTime(from value: Float) -> Double { var sameValue = value sameValue *= 1000 let time = 10000 - Double(sameValue) return time / 1000 } func sleepTask() { let time = getSleepTime(from: self.frequencie) sleep(UInt32(time)) } }
// // Movie.swift // TrySectionsandCells // // Created by Sayed Abdo on 7/12/18. // Copyright © 2018 JETS. All rights reserved. // import UIKit class Movie: NSObject { var posterPath:String = "" }
// ___FILEHEADER___ import Foundation enum Result<T> { case success(T) case failure(Error) } class ___FILEBASENAMEASIDENTIFIER___ { static func get<K: Codable>(url: URL, parameters: [String: Any]? = [:], completion: @escaping (Result<K>) -> Void) { var request = URLRequest(url: url) request.httpMethod = "GET" var urlComp = URLComponents(url: url, resolvingAgainstBaseURL: false) parameters?.forEach({ urlComp?.queryItems?.append(URLQueryItem(name: $0.key, value: $0.value as? String)) }) NetworkClient.task(request: request, completion: completion).resume() } static func post<K: Codable>(url: URL, parameters: [String: Any], completion: @escaping (Result<K>) -> Void) { var request = URLRequest(url: url) request.httpMethod = "POST" guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: []) else { return } request.httpBody = httpBody request.setValue("Application/json", forHTTPHeaderField: "Content-Type") NetworkClient.task(request: request, completion: completion).resume() } fileprivate static func task<K: Codable>(request: URLRequest, completion: @escaping (Result<K>) -> Void) -> URLSessionDataTask { let session = URLSession(configuration: URLSessionConfiguration.default) return session.dataTask(with: request) { (responseData, response, responseError) in if let error = responseError { completion(.failure(error)) } else if let jsonData = responseData { let decoder = JSONDecoder() do { let objects = try decoder.decode(K.self, from: jsonData) let result: Result<K> = Result.success(objects) completion(result) } catch { completion(.failure(error)) } } } } }
// // HCProtocolViewModel.swift // HCPoems // // Created by cgtn on 2018/9/21. // Copyright © 2018年 houcong. All rights reserved. // import Foundation protocol ViewModelType { associatedtype Input associatedtype Output func transform(input: Input) -> Output }