blob_id
stringlengths
40
40
language
stringclasses
1 value
repo_name
stringlengths
6
116
path
stringlengths
5
872
src_encoding
stringclasses
7 values
length_bytes
int64
10
4.68M
score
float64
2.52
5.63
int_score
int64
3
5
detected_licenses
listlengths
0
47
license_type
stringclasses
2 values
text
stringlengths
7
4.81M
download_success
bool
1 class
a4641c1c18064e7628d71ee56ff6cf87d3719783
Swift
oscar20/Find-It
/Find It/Clases/URLImagen.swift
UTF-8
1,153
2.765625
3
[]
no_license
// // Ubicacion.swift // Find It // // Created by Oscar Almazan Lora on 01/07/18. // Copyright © 2018 d182_oscar_a. All rights reserved. // import Foundation import Alamofire import UIKit class URLImagen: UIViewController{ func obtenerImagenConURL(objetoStore : Product, completionHandler: @escaping (UIImage?, Error?) -> () ){ if let urlImagen = objetoStore.image{ //print("NO NIL") //print(urlImagen) let urlImagenPeticion = URL(string: urlImagen) Alamofire.request(urlImagenPeticion!).responseData { (responseData) in if let error = responseData.error{ print("No se pudo cargar la imagen \(error)") } guard let data = responseData.data else {return} let image = UIImage(data: data) DispatchQueue.main.async(execute: { completionHandler(image,nil) }) } }else{ print("nil") let imagenVacia = UIImage(named: "noDisponible") completionHandler(imagenVacia,nil) } } }
true
3847b922073d8bcaad274c636a5e84a24ddeb72b
Swift
will3/cali
/cali/DateTimePicker.swift
UTF-8
5,278
2.546875
3
[]
no_license
// // FloatingDateTimeSelectionView.swift // cali // // Created by will3 on 6/08/18. // Copyright © 2018 will3. All rights reserved. // import Foundation import UIKit import Layouts enum DateTimePickerPage { case date case time } protocol DateTimePickerDelegate : AnyObject { func dateTimePickerDidFinish(_ dateTimePicker: DateTimePicker) } /// Date time picker class DateTimePicker : UIView, UIScrollViewDelegate, DatePickerDelegate, TimePickerDelegate { /// Delegate weak var delegate : DateTimePickerDelegate? /// Initial page var initialPage = DateTimePickerPage.date override func didMoveToSuperview() { super.didMoveToSuperview() if !loaded { loadView() loaded = true } } /// View loaded private var loaded = false /// Date picker private let datePicker = DatePicker() /// Scroll view private let scrollView = UIScrollView() /// Content view private let contentView = UIView() /// Page control private let pageControl = UIPageControl() /// Left private let left = UIView() /// Right private let right = UIView() /// Time picker private let timePicker = TimePicker() /// Did set initial page private var didSetInitialPage = false /// Event service private let eventService = Injection.defaultContainer.eventService var event: Event? { didSet { datePicker.event = event timePicker.event = event } } private func loadView() { let paddingHorizontal: Float = 4 let paddingVertical: Float = 48 datePicker.totalWidth = UIScreen.main.bounds.width - CGFloat(paddingHorizontal) - CGFloat(paddingHorizontal) let blurEffect = UIBlurEffect(style: .dark) let blurView = UIVisualEffectView(effect: blurEffect) layout(blurView).matchParent(self).install() let tap = UITapGestureRecognizer(target: self, action: #selector(DateTimePicker.didTapBackground)) blurView.addGestureRecognizer(tap) datePicker.delegate = self scrollView.showsHorizontalScrollIndicator = false layout(scrollView).matchParent(self).install() layout(contentView).matchParent(scrollView).install() layout(contentView) .width(.ratio(2)) .height(.ratio(1)) .install() scrollView.isPagingEnabled = true layout(contentView).stackHorizontal([ layout(left).width(.ratio(0.5)), layout(right).width(.ratio(0.5))]) .install() layout(datePicker) .parent(left) .horizontal(.stretch) .left(paddingHorizontal) .right(paddingHorizontal) .vertical(.center) .install() timePicker.delegate = self layout(timePicker) .matchParent(right) .insets(UIEdgeInsetsMake( CGFloat(paddingVertical), CGFloat(paddingHorizontal), CGFloat(paddingVertical), CGFloat(paddingHorizontal))) .install() pageControl.numberOfPages = 2 pageControl.addTarget(self, action: #selector(DateTimePicker.didChangePage), for: .valueChanged) layout(pageControl) .parent(self) .pinLeft() .pinRight() .pinBottom() .height(60) .install() scrollView.delegate = self } override func layoutSubviews() { super.layoutSubviews() if !didSetInitialPage { if initialPage == .time { scrollView.contentOffset = CGPoint(x: scrollView.bounds.width, y: 0) } didSetInitialPage = true } } @objc private func didTapBackground() { dismiss() } @objc private func didChangePage() { let contentOffset = CGPoint(x: CGFloat(pageControl.currentPage) * scrollView.bounds.width, y: 0) scrollView.setContentOffset(contentOffset, animated: true) } /// Dismiss self func dismiss() { self.removeFromSuperview() } // MARK: UIScrollViewDelegate func scrollViewDidScroll(_ scrollView: UIScrollView) { let page = scrollView.contentOffset.x / scrollView.bounds.size.width if page == floor(page) { pageControl.currentPage = Int(page) } } // MARK: DatePickerDelegate func datePickerDidChange(_ datePicker: DatePicker) { guard let event = self.event else { return } guard let selectedDate = datePicker.selectedDate else { return } eventService.changeDay(event: event, day: selectedDate) self.event = event } func datePickerDidFinish(_ datePicker: DatePicker) { dismiss() delegate?.dateTimePickerDidFinish(self) } // MARK: TimePickerDelegate func timePickerDidChange(_ timePicker: TimePicker) { self.event = timePicker.event } func timePickerDidFinish(_ timePicker: TimePicker) { dismiss() delegate?.dateTimePickerDidFinish(self) } }
true
60d9b4e8ee94810b74befa14ac8df6ce80f8f23d
Swift
Apodini/Grebe
/Sources/Grebe-Framework/Calls/GBidirectionalStreamingCall.swift
UTF-8
3,667
3.15625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // GBidirectionalStreamingCall.swift // // // Created by Tim Mewe on 07.12.19. // import Combine import Foundation import GRPC import SwiftProtobuf /// #### A bidirectional streaming Grebe call. /// /// Both sides, the client and the server, send a sequence of messages. The two streams /// operate independently, so clients and servers can read and write and whatever /// oder they like: for example, the server could wait to receive all the client messages /// before writing its responses, or it could alternately read a message then write a /// message, or some other combination of reads and writes. /// /// ##### Example usage of `GBidirectionalStreamingCall` /// /// Consider the following protobuf definition for a simple echo service. /// The service defines one bidirectional streaming RPC. You send a stream of messages and it /// echoes a stream of messages back to you. /// /// ```proto /// syntax = "proto3"; /// /// service EchoService { /// rpc echo (stream EchoRequest) returns (stream EchoResponse); /// } /// /// message EchoRequest { /// string message = 1; /// } /// /// message EchoResponse { /// string message = 1; /// } /// ``` /// /// You can create a `GBidirectionalStreamingCall` like this: /// ``` /// let requests = Publishers.Sequence<[EchoRequest], Error>( /// sequence: [EchoRequest.with { $0.message = "hello"}, EchoRequest.with { $0.message = "world"}] /// ).eraseToAnyPublisher() /// /// GBidirectionalStreamingCall(request: requests, callOptions: callOptions, closure: echo) /// ``` /// public class GBidirectionalStreamingCall<Request: GRPCPayload, Response: GRPCPayload>: IGCall { public typealias CallClosure = ( _ callOptions: CallOptions?, _ handler: @escaping (Response) -> Void ) -> GRPC.BidirectionalStreamingCall<Request, Response> /// The request message stream for the call. public var requests: AnyPublisher<Request, Error> public let callClosure: CallClosure public let callOptions: CallOptions? /// Stores all cacellables. private var cancellables: Set<AnyCancellable> = [] /** Sets up an new bidirectional streaming Grebe call. - Parameters: - request: The request message stream for the call. - callOptions: Options to use for each service call. - closure: The closure which contains the executable call. */ public init( requests: AnyPublisher<Request, Error>, callOptions: CallOptions? = nil, closure: @escaping CallClosure ) { self.requests = requests self.callClosure = closure self.callOptions = callOptions } /** Executes the Grebe bidirectional streaming call. - Returns: A stream of `Response` elements. The response publisher may fail with a `GRPCStatus` error. */ public func execute() -> AnyPublisher<Response, GRPCStatus> { let subject = PassthroughSubject<Response, GRPCStatus>() let call = callClosure(callOptions) { response in subject.send(response) } requests .sink(receiveCompletion: { completion in switch completion { case .finished: call.sendEnd(promise: nil) case .failure: _ = call.cancel() } }, receiveValue: { message in call.sendMessage(message, promise: nil) }) .store(in: &cancellables) call.status.whenSuccess { subject.send(completion: $0.code == .ok ? .finished : .failure($0)) } return subject.eraseToAnyPublisher() } }
true
2148551dc4c718db8267203dd780eda2edd581d7
Swift
ahmedmadian/ITWorx
/NewsApp/NewsApp/Library/Storyboards.swift
UTF-8
554
2.65625
3
[]
no_license
// // Storyboards.swift // NewsApp // // Created by Ahmed Madian on 3/4/20. // Copyright © 2020 Ahmed Madian. All rights reserved. // import UIKit enum Storyboards: String { case main = "Main" public func instantiate<ViewController: UIViewController>() -> ViewController? { guard let viewController = UIStoryboard(name: self.rawValue, bundle: nil).instantiateViewController(withIdentifier: String(describing: ViewController.self)) as? ViewController else { return nil } return viewController } }
true
e26890edeb546652f913f9e82b292476c58b2102
Swift
starainDou/DDYDayly
/Elevator/elevator/Networking/DDUploadApi.swift
UTF-8
1,981
2.6875
3
[]
no_license
// // DDUploadApi.swift // elevator // // Created by ddy on 2023/1/18. // import Foundation import Moya public enum DDUploadApi { case uploadImageOfLift(Data, String) case uploadAllImagesOfLift([Data], [String]) } extension DDUploadApi { internal var handleResult: (url: String, params: [MultipartFormData]) { var baseParams = Array<MultipartFormData>() switch self { case let .uploadImageOfLift(data, fileName): baseParams.append(MultipartFormData(provider: .data(data), name: "multipartFile", fileName: fileName, mimeType: "image/jpeg")) return (DDBaseUrl + "/fileApp/uploadImageOfLift", baseParams) case let .uploadAllImagesOfLift(datas, names): for (index, data) in datas.enumerated() { if index < names.count { baseParams.append(MultipartFormData(provider: .data(data), name: "multipartFile", fileName: names[index], mimeType: "image/jpeg")) } else { fatalError("图片数大于名字数") } } return (DDBaseUrl + "/fileApp/uploadAllImagesOfLift", baseParams) } } } /// 遵循Moya TargetType 协议 extension DDUploadApi: TargetType { public var baseURL: URL { return URL(string: handleResult.url.replacingOccurrences(of: " ", with: ""))! } public var path: String { return "" } public var method: Moya.Method { return .post } public var sampleData: Data { return "".data(using: .utf8)! } public var task: Task { return .uploadMultipart(handleResult.params) } public var headers: [String : String]? { guard let token = DDShared.shared.token, let cookie = DDShared.shared.cookie else { return nil } return ["Authorization": token, "Cookie": cookie, "Content-type" : "multipart/form-data"] // , "Content-Type": "multipart/form-data" } }
true
51f9f9d2cf972c10d25ce418133c7db50d4f918c
Swift
TeamsMobilePlatform/react-native-code-push
/ios/CodePush/CodePush/Common/Managers/CodePushAcquisitionManager.swift
UTF-8
3,471
2.625
3
[ "LicenseRef-scancode-unknown-license-reference", "MIT" ]
permissive
// // CodePushAcquisitionManager.swift // CodePush // // Copyright © 2018 MSFT. All rights reserved. // import Foundation /** * Manager responsible for interacting with the CodePush Server */ class CodePushAcquisitionManager { /** * Query updates endpoint. */ private static let UpdateCheckEndpoint = "/updateCheck" /** * Protocol */ private static let Scheme = "https" /** * Instance of ```CodePushUtils``` to work with. */ private var codePushUtils: CodePushUtils /** * Instance of ```FileUtils``` to work with. */ private var fileUtils: FileUtils init(_ codePushUtils: CodePushUtils, _ fileUtils: FileUtils) { self.codePushUtils = codePushUtils self.fileUtils = fileUtils } /** * Sends a request to server for updates of the current package. * * Parameter configuration current application configuration. * Parameter currentPackage instance of ```CodePushLocalPackage```. * Returns: ```CodePushRemotePackage``` or ```nil``` if there is no update. * Throws: CodePushQueryUpdateException exception occurred during querying for update. */ func queryUpdate(withConfig configuration: CodePushConfiguration, withPackage currentPackage: CodePushLocalPackage, callback completion: @escaping (Result<CodePushRemotePackage?>) -> Void) { guard currentPackage.appVersion != nil else { completion(Result { throw CodePushErrors.invalidParam(cause: "Cannot query for an update without the app version") }) return } let updateRequest = CodePushUpdateRequest.createUpdateRequest(withKey: configuration.deploymentKey!, withLocalPackage: currentPackage, withClientUniqueId: configuration.clientUniqueId!) var urlComponents = URLComponents() urlComponents.scheme = CodePushAcquisitionManager.Scheme urlComponents.host = configuration.serverUrl urlComponents.path = CodePushAcquisitionManager.UpdateCheckEndpoint urlComponents.queryItems = codePushUtils.getQueryItems(fromObject: updateRequest) guard let url = urlComponents.url else { completion(Result { throw QueryUpdateErrors.failedToConstructUrl }) return } let query = ApiRequest(url) query.checkForUpdate(completion: { result in completion( Result { let json = try result.resolve() let result: CodePushUpdateResponse = try self.codePushUtils.convertStringToObject(withString: json) let updateInfo = result.updateInfo if (updateInfo.updateAppVersion)! { return CodePushRemotePackage.createDefaultRemotePackage(withVersion: updateInfo.appVersion!, updateVersion: updateInfo.updateAppVersion!) } else if !updateInfo.isAvailable! { return nil } return CodePushRemotePackage.createRemotePackage(withDeploymentKey: configuration.deploymentKey!, fromUpdateInfo: updateInfo) }) }) } }
true
821457d71a8be29af5e6bfd47e66a5a1c381096f
Swift
thallen96/SwiftUI-Bootstrap
/bootstrap/bootstrap/App/Common/Button/DynamicButton.swift
UTF-8
4,065
3.59375
4
[]
no_license
// // DynamicButton.swift // bootstrap // // Created by Elizabeth Johnston on 2/25/20. // Copyright © 2020 CapTech Consulting. All rights reserved. // //- Examples of dynamic buttons that visually change /// these are ideal for buttons that rotate through options, buttons that can be on or off, etc.. // import Foundation import SwiftUI //MARK: - VOLUME BUTTON /// Button that when pressed will rotate through the volume level options and return the shown volumeLevel enum struct VolumeButton: View { @Binding var volumeLevel: VolumeLevel var body: some View { Button(action: { self.volumeLevel = self.volumeLevel.nextLevel() }){ Spacer() Image(systemName: self.volumeLevel.icon()) .resizable() .frame(width: 20, height: 20) Spacer() }.primaryStyle .frame(width: 40, height: 30) .padding(.trailing, 5) } } //MARK: VOLUME LEVEL ENUM /// Enum containing the different volume level options and their corresponding icon extension VolumeButton { public enum VolumeLevel { case mute case low case medium case high func icon() -> String { //returns the icon name for that volume level switch self { case .mute: return SFSymbols.speaker_slash case .low: return SFSymbols.speaker1 case .medium: return SFSymbols.speaker2 case .high: return SFSymbols.speaker3 } } func nextLevel() -> VolumeLevel { //return the next volume level /// there is probably a more efficient way to itterate through the volume levels but this works fine switch self { case .mute: return .low case .low: return .medium case .medium: return .high case .high: return .mute } } } } //MARK: - POWER BUTTON /// Button that when pressed will turn on and off resulting in the variable switching back and forth from true to false struct PowerButton: View { @Binding var power: Bool /// true = on, false = off var body: some View { Button(action: { self.power.toggle() }){ VStack(spacing: 5){ Image(systemName: SFSymbols.power) .resizable() .frame(width: 20, height: 20) .padding(.top, 5) .foregroundColor(self.power ? Color.green : Color.gray) /// if power is true (on), makes the icon green. if power is false (off), makes the icon white Text(self.power ? "On" : "Off") .font(.custom(Avenir_Fonts.medium, size: 10)) .foregroundColor(self.power ? Color.green : Color.gray) /// if power is true (on), makes the text green. if power is false (off), makes the text white (just like icon above) }.frame(width: 50, height: 40) .padding(10) .background(Color.white) .cornerRadius(15) .overlay(self.power ? RoundedRectangle(cornerRadius: 15).stroke(Color(red: 236/255, green: 234/255, blue: 235/255), lineWidth: 1).shadow(color: Color(red: 192/255, green: 189/255, blue: 191/255), radius: 3, x: 3, y: 3).clipShape(RoundedRectangle(cornerRadius: 15)).shadow(color: Color.white, radius: 1, x: -1, y: -1).clipShape(RoundedRectangle(cornerRadius: 15)) : nil) /// this add an inverted shadow overlay if the power is on .shadow(color: Color(red: 192/255, green: 189/255, blue: 191/255), radius: self.power ? 0 : 1, x: self.power ? 0 : 1, y: self.power ? 0 : 1) /// if the power is off this will add an outward shadow } .padding(.trailing, 5) } }
true
b001bd3ebcda3eeb835b20663743f37aa2fbf2ce
Swift
EcoSeoul/Team_iOS
/EcoSeoul/EcoSeoul/Util/Service/ExchangeService.swift
UTF-8
1,603
2.609375
3
[]
no_license
// // ExchangeService.swift // EcoSeoul // // Created by 이충신 on 2018. 9. 28.. // Copyright © 2018년 GGOMMI. All rights reserved. // import Foundation import Alamofire import SwiftyJSON struct ExchangeService: PostableService { typealias NetworkData = Exchange static let shareInstance = ExchangeService() func exchange(url : String, params : [String : Any], completion : @escaping (NetworkResult<Exchange>) -> Void){ post(url, params: params) { (result) in switch result { case .success(let networkResult): switch networkResult.message { case "Successfully Exchange Mileage to Money" : completion(.networkSuccess(networkResult)) case "You can exchange money only if you have more than 20,000 points in mileage." : completion(.wrongInput) case "Insufficient miles to switch" : completion(.insufficient) case "The minimum exchange amount is 1000" : completion(.minimumValue) case "Null Value : user index and exchange" : completion(.nullValue) default : break } break case .error(let errMsg) : print(errMsg) break case .failure(_) : completion(.networkFail) } } } }
true
5d34eb43320ae73a81d57b5793dca6fbcf581789
Swift
michaelgwelch/swift-parsing
/Parsing/Parsing/Monad.swift
UTF-8
750
3.28125
3
[ "MIT" ]
permissive
// // Monad.swift // tibasic // // Created by Michael Welch on 7/22/15. // Copyright © 2015 Michael Welch. All rights reserved. // import Foundation // Like Haskell >>=, bind public func |>>=<T1, T2>(lhs:ParserOf<T1>, rhs:@escaping (T1) -> ParserOf<T2>) -> ParserOf<T2> { return lhs.bind(rhs) } // Like Haskell >> public func |>><T1,T2>(lhs:ParserOf<T1>, rhs:ParserOf<T2>) -> ParserOf<T2> { return lhs.bind { _ in rhs } } extension ParserType { public func bind<TB, PB:ParserType>(_ f:@escaping (TokenType) -> PB) -> ParserOf<TB> where PB.TokenType == TB { return ParserOf { input in return self.parse(input).flatMap { (a,output) in f(a).parse(output) } } } }
true
fbdc8b59c6e087354f7669337cadaf54001d145b
Swift
tomasholicky/spm-swiftui-combine
/NetworkCore/Sources/NetworkCore/Router/CoinGeckoRouter.swift
UTF-8
2,190
2.953125
3
[]
no_license
// // CoinGeckoRouter.swift // // // Created by Tomas Holicky on 13/05/2020. // import Foundation import Alamofire public enum CoinGeckoRouter { case getCoins case getCoin(id: String) } extension CoinGeckoRouter: URLRequestConvertible { // MARK: - Base URL var baseUrl: String { switch self { default: return "https://api.coingecko.com" } } // MARK: - Headers var headers: [(value: String, headerField: String)] { switch self { default: return [] } } // MARK: - Method var method: HTTPMethod { switch self { default: return .get } } // MARK: - Version var version: String { switch self { default: return "/api/v3" } } // MARK: - Path var path: String { switch self { case .getCoins: return "/coins/list" case .getCoin(id: let id): return "/coins/" + id } } // MARK: - Query var query: [URLQueryItem]? { switch self { default: return [] } } // MARK: - Parameters var parameters: [String: Any]? { switch self { default: return [:] } } /// Returns a URL request or throws if an `Error` was encountered. public func asURLRequest() throws -> URLRequest { var url = URLComponents(string: baseUrl) url?.path = version + path if let query = query, !query.isEmpty { url?.queryItems = query } var request = URLRequest(url: (url?.url)!) request.httpMethod = method.rawValue request.timeoutInterval = 15 * 1_000 request.cachePolicy = .reloadIgnoringCacheData // Adding Headers for header in headers { request.setValue(header.value, forHTTPHeaderField: header.headerField) } switch self { default: return try URLEncoding.default.encode(request, with: parameters ?? [:]) } } }
true
f196559b37a5887a0e6bff3ee472466ee32026c1
Swift
emrdgrmnci/MovieBox
/MovieBox/MovieBoxVIPER/Scenes/MovieDetail/MovieDetailViewController.swift
UTF-8
793
2.5625
3
[]
no_license
// // MovieDetailViewController.swift // MovieBoxMVVM // // Created by Göksel Köksal on 24.11.2018. // Copyright © 2018 Late Night Muhabbetleri. All rights reserved. // import UIKit final class MovieDetailViewController: UIViewController, MovieDetailViewProtocol { var presenter: MovieDetailPresenterProtocol! @IBOutlet private weak var movieTitleLabel: UILabel! @IBOutlet private weak var artistNameLabel: UILabel! @IBOutlet private weak var genreLabel: UILabel! override func viewDidLoad() { super.viewDidLoad() presenter.load() } func update(_ presentation: MovieDetailPresentation) { movieTitleLabel.text = presentation.title artistNameLabel.text = presentation.artistName genreLabel.text = presentation.genre } }
true
9663da811cec984a8fbd0596d2e63c09252be6fd
Swift
code-bunny/aural-player
/Aural/PlaylistAccessorDelegate.swift
UTF-8
1,875
2.859375
3
[]
no_license
import Foundation /* Concrete implementation of PlaylistAccessorDelegateProtocol */ class PlaylistAccessorDelegate: PlaylistAccessorDelegateProtocol { // The actual playlist private let playlist: PlaylistAccessorProtocol init(_ playlist: PlaylistAccessorProtocol) { self.playlist = playlist } func getTracks() -> [Track] { return playlist.getTracks() } func peekTrackAt(_ index: Int?) -> IndexedTrack? { return playlist.peekTrackAt(index) } func size() -> Int { return playlist.size() } func totalDuration() -> Double { return playlist.totalDuration() } func summary() -> (size: Int, totalDuration: Double) { return (playlist.size(), playlist.totalDuration()) } func search(_ searchQuery: SearchQuery) -> SearchResults { return playlist.search(searchQuery) } func search(_ searchQuery: SearchQuery, _ groupType: GroupType) -> SearchResults { return playlist.search(searchQuery, groupType) } func getGroupingInfoForTrack(_ track: Track, _ groupType: GroupType) -> GroupedTrack { return playlist.getGroupingInfoForTrack(groupType, track) } func displayNameFor(_ type: GroupType, _ track: Track) -> String { return playlist.displayNameFor(type, track) } func getGroupAt(_ type: GroupType, _ index: Int) -> Group { return playlist.getGroupAt(type, index) } func getGroupingInfoForTrack(_ type: GroupType, _ track: Track) -> GroupedTrack { return playlist.getGroupingInfoForTrack(type, track) } func getIndexOf(_ group: Group) -> Int { return playlist.getIndexOf(group) } func getNumberOfGroups(_ type: GroupType) -> Int { return playlist.getNumberOfGroups(type) } }
true
8c83b11d8cbe3c39ae3b858070e1b137dcddf6fd
Swift
timur-st94/TestProject
/TestProject/Helpers/TableManager.swift
UTF-8
3,797
2.671875
3
[]
no_license
import UIKit class TableManager: ListManager, UITableViewDataSource, UITableViewDelegate { private var headers = [Int: UIView]() private var footers = [Int: UIView]() var didSelect: ((Any, IndexPath) -> Void)? var didScroll: ParameterBlock<UITableView>? var sectionHeader: Block<Int, UIView?>? var sectionFooter: Block<Int, UIView?>? var tableView: UITableView! { didSet { tableView.dataSource = self tableView.delegate = self tableView.estimatedRowHeight = 92 tableView.backgroundColor = .white registerCells() } } @objc func resignFirstResponder() { tableView.endEditing(true) } func registerCells() {} override func reloadData() { super.reloadData() tableView.reloadData() } func smoothReload() { if #available(iOS 11.0, *) { tableView.performBatchUpdates({}) } else { tableView.beginUpdates() tableView.endUpdates() } } // MARK: - UITableViewDataSource func numberOfSections(in tableView: UITableView) -> Int { return filteredItems.count } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return filteredItems[section].count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let item = item(for: indexPath) else { fatalError("item not found for certain indexPath") } let cellId = itemIdentifier(for: item) guard let cell = tableView.dequeueReusableCell(withIdentifier: cellId, for: indexPath) as? ConfigurableTableViewCell else { fatalError("TableManager required working with cells type of ConfigurableCell") } cell.configure(with: item) return cell } private func header(for section: Int) -> UIView? { var header = headers[section] if header == nil { header = sectionHeader?(section) headers[section] = header } header?.layoutIfNeeded() return header } func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { return header(for: section) } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { guard let header = header(for: section) else { return 0 } header.layoutIfNeeded() return header.bounds.height } private func footer(for section: Int) -> UIView? { var footer = footers[section] if footer == nil { footer = sectionFooter?(section) footers[section] = footer } footer?.layoutIfNeeded() return footer } func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? { return footer(for: section) } func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat { return footer(for: section)?.bounds.height ?? 0 } // MARK: - UITableViewDelegate func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { guard let item = item(for: indexPath) else { return 0 } return height(for: item) } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if let item = item(for: indexPath) { didSelect?(item, indexPath) } } func scrollViewDidScroll(_ scrollView: UIScrollView) { didScroll?(tableView) } } class ConfigurableTableViewCell: UITableViewCell { func configure(with _: Any) {} }
true
618e8d81309a4759a5f7c6fe81da969dd5e54a5c
Swift
Chrisb616/CreepGame
/CreepGame/Creep.swift
UTF-8
2,662
3.4375
3
[]
no_license
// // Creep.swift // CreepGame // // Created by Christopher Boynton on 10/21/16. // Copyright © 2016 Flatiron School. All rights reserved. // import UIKit enum CreepType { case balanced case attack case tank case ranged case mage } class Creep: Attacking, Attackable, Moving { var name: String = "" var creepType: CreepType var rank: Int var healthPoints: Int = 0 var armorPoints: Int = 0 var damagePoints: Int = 0 var range: CGFloat = 0 var target: Attackable? var speed: CGFloat = 0 init(creepType: CreepType, rank: Int) { self.creepType = creepType self.rank = rank switch creepType { case .balanced: switch rank { case 1: name = "Page" healthPoints = 40 armorPoints = 10 damagePoints = 10 range = 0.5 speed = 10 default: print("Error: Creep Rank out of range in initializer") fatalError() } case .attack: switch rank { case 1: name = "Thug" healthPoints = 40 armorPoints = 5 damagePoints = 15 range = 0.5 speed = 12 default: print("Error: Creep Rank out of range in initializer") fatalError() } case .tank: switch rank { case 1: name = "Knight" healthPoints = 50 armorPoints = 20 damagePoints = 5 range = 0.5 speed = 5 default: print("Error: Creep Rank out of range in initializer") fatalError() } case .ranged: switch rank { case 1: name = "Slinger" healthPoints = 30 armorPoints = 10 damagePoints = 15 range = 5 speed = 15 default: print("Error: Creep Rank out of range in initializer") fatalError() } case .mage: switch rank { case 1: name = "Acolite" healthPoints = 40 armorPoints = 0 damagePoints = 20 range = 3 speed = 10 default: print("Error: Creep Rank out of range in initializer") fatalError() } } } }
true
f5acef12f17ba48d4666bcc66b9688d407af5460
Swift
SankaraIshema/CheckList
/CheckList/CheckListViewController.swift
UTF-8
1,954
2.5625
3
[]
no_license
// // ViewController.swift // CheckList // // Created by BT-Training on 26/08/16. // Copyright © 2016 BT-Training. All rights reserved. // import UIKit class CheckListViewController: UITableViewController { var dataModel = [CheckList]() override func viewDidLoad() { super.viewDidLoad() dataModel.append(CheckList(withTitle : "Promener le chien")) dataModel.append(CheckList(withTitle : "Brosser mes dents")) dataModel.append(CheckList(withTitle : "etr cordial dans mes commentaires youtubes")) dataModel.append(CheckList(withTitle : "M'entrainer à beer pong")) dataModel.append(CheckList(withTitle : "Envahir la Russie")) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension CheckListViewController { // UITableViewDelegate override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return dataModel.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("CheckListItem", forIndexPath: indexPath) let label = cell.viewWithTag(1000) as! UILabel let checkList = dataModel[indexPath.row] label.text = checkList.title cell.accessoryType = checkList.done ? .Checkmark : .None return cell } } extension CheckListViewController { // UITableViewDataSource override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { print("clic") let checkList = dataModel[indexPath.row] checkList.done = !checkList.done tableView.reloadRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } }
true
e1a3cccf2e002e8ad6b19ce6ec0ade1959fb3b25
Swift
NicoDB79/clean-countries
/CleanCountriesTests/CountryListViewControllerTests.swift
UTF-8
1,752
2.640625
3
[]
no_license
// // CountryListViewControllerTests.swift // CleanCountriesTests // // Created by Nicola De Bei on 15/12/2020. // import XCTest @testable import CleanCountriesDemo class CountryListViewControllerTests: XCTestCase { // MARK: - Subject under test var sut: CountryListViewController! var window: UIWindow! override func setUpWithError() throws { super.setUp() window = UIWindow() setupCountryListViewController() } override func tearDownWithError() throws { window = nil super.tearDown() } // MARK: - Test setup func setupCountryListViewController() { sut = CountryListViewController.instantiate(storyboardName: "CountryList") } func loadView() { window.addSubview(sut.view) RunLoop.current.run(until: Date()) } class CountryListBusinessLogicSpy: CountryListInteractorProtocol { var countries: [Country]? // MARK: Method call expectations var fetchCountriesCalled = false func fetchDatabaseCountries(completion: (() -> ())?) { fetchCountriesCalled = true } func fetchOnlineCountries() { fetchCountriesCalled = true } func searchCountries(with request: CountryListModels.SearchRequest) {} } func testShouldFetchCountriesWhenViewDidAppear() { // Given let interactor = CountryListBusinessLogicSpy() sut.interactor = interactor loadView() // When sut.viewDidAppear(true) // Then XCTAssert(interactor.fetchCountriesCalled, "Should fetch countries right after the view appears") } }
true
6161deee76c53f96a16229472bf934d5589d8840
Swift
sidepelican/iosdc2021
/Presentation/Presentation/Page/501.swift
UTF-8
413
2.5625
3
[ "MIT" ]
permissive
import PresentationKit import SwiftUI struct Page501Page: Page { var body: some View { TitleAndSubtitle(title: "さらなる改善へ") } func cunningText(step: Int) -> String { """ さらなる改善へ """ } } struct Page501Page_Previews: PreviewProvider { static var previews: some View { Page501Page() .virtualScreenPreview() } }
true
7c8eddd3b24960c56b5586ffd601173e1fe65ddb
Swift
renjitpeter/MovieAppForMS
/MovieAppForMS/CollectionViewModel.swift
UTF-8
5,144
2.953125
3
[]
no_license
// // CollectionViewModel.swift // MovieAppForMS // // Created by Renjit Peter on 8/31/17. // Copyright © 2017 Renjit Peter. All rights reserved. // import Foundation import UIKit import SDWebImage class CollectionViewModel:NSObject { fileprivate var dataManager:DataManagerProtocol? fileprivate let kNumberOfSectionsInCollectionView = 1 fileprivate var selectedCellIndexPath : IndexPath! fileprivate let reuseidentifier = "MovieCell" fileprivate var collectionId:Int? var movieList: [Movie] = [] var collection:Collection? init(collectionId:Int) { super.init() dataManager = DataManager() self.collectionId = collectionId // self.fetchCollectionDetails(collectionId: collectionId) } func fetchCollectionDetails(imageView:UIImageView, callback: @escaping (Bool,String,Collection?)->()) -> () { self.dataManager?.getCollectionDetails(collectionID: self.collectionId!, completion: { (responseDictionary, error) in if let responseDictionary = responseDictionary, let collectionId = responseDictionary["id"] as? Int, let collectionName = responseDictionary["name"] as? String { self.collection = Collection(id: collectionId, title: collectionName) if let imagePath = responseDictionary["poster_path"] as? String { self.collection?.imagePath = imagePath } self.collection?.overView = responseDictionary["overview"] as? String if let imagePath = self.collection?.imagePath { imageView.sd_setImage(with: URL(string: imageBaseURL + imagePath), placeholderImage: UIImage(named: "MovieIcon.png")) } self.collection?.posterImage = imageView.image guard let movieParts = responseDictionary["parts"] as? [Any] else { print("Collection : parts results empty ") callback(false,"Failed to fetch data. Please try later",nil) return } for movieData in movieParts{ if let movieData = movieData as? responseDictionary, let movieId = movieData["id"] as? Int, let movieName = movieData["title"] as? String { let movie = Movie(id: movieId, title: movieName) let avgVote = movieData["vote_average"] as? Float movie.avgVote = avgVote if let imagePath = movieData["poster_path"] as? String { movie.imagePath = imagePath } movie.overView = movieData["overview"] as? String movie.voteCount = movieData["vote_count"] as? Int self.movieList.append(movie) } } self.collection?.movieList.append(contentsOf: self.movieList) callback(true,"",self.collection) } else { callback(false,"Failed to fetch data. Please try later",nil) } }) } } //For collection view data source extension CollectionViewModel{ func numberOfItemsInSection(section : Int) -> Int { return (self.movieList.count) } func numberOfSectionsInCollectionView() -> Int { return kNumberOfSectionsInCollectionView } func setUpCollectionViewCell(indexPath : IndexPath, collectionView : UICollectionView) -> UICollectionViewCell { let cell: UICollectionViewCell let movie = self.movieList[indexPath.row] cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseidentifier, for: indexPath as IndexPath) as! MovieViewCell var rating: String = "" if let avgVote = movie.avgVote { rating = String(avgVote) } (cell as! MovieViewCell).setMovieData(name: (movie.movieName), rating: rating) if let imagePath = movie.imagePath { (cell as! MovieViewCell).posterImage.sd_setImage(with: URL(string: imageBaseURL + imagePath), placeholderImage: UIImage(named: "MovieIcon.png")) } return cell } } //For initialisation and navigation to detail view extension CollectionViewModel { func setSelectedCellIndexPath(indexPath : IndexPath){ selectedCellIndexPath = indexPath } func getMovieDetailViewModel() -> MovieDetailsViewModel { let movie = movieList[selectedCellIndexPath.row] let movieDetailsViewModel = MovieDetailsViewModel(selectedMovie: movie) return movieDetailsViewModel } }
true
8cb2b89cd5bd2f259d5d747bfa08c09ff4d0c739
Swift
Gurbo/DialogBox
/Example/DialogBox/DialogBoxSettings.swift
UTF-8
57,509
2.609375
3
[ "MIT" ]
permissive
// // DialogBoxSettings.swift // DialogBox // // Created by Dhawal on 20/08/17. // Copyright © 2017 Dhawal. All rights reserved. // import UIKit import DialogBox struct BoxAppearanceAlert { static var _1 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) return appearance } static var _2 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) return appearance } static var _3 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 70, height: 70) appearance.icon.image.name = "success" appearance.icon.margin = "0|-55|0|0" appearance.icon.position = BoxIconPosition.topCenter appearance.icon.backgroundColor = UIColor.white appearance.icon.padding = "5|5|5|5" appearance.icon.cornerRadius = 40 // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) return appearance } static var _4 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.padding = 0 appearance.layout.spacing = 0 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.white appearance.title.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.title.padding = "0|100|0|10" // Message appearance.message.margin = "20|0|20|0" appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 70, height: 70) appearance.icon.image.name = "successWhite" appearance.icon.margin = "0|-120|0|70" appearance.icon.position = BoxIconPosition.centerBelowTitle // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.containerMargin = "20|20|20|20" appearance.button.textColor = UIColor.darkGray appearance.button.backgroundColor = UIColor.init(red: 210.0/255.0, green: 210.0/255.0, blue: 210.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 20.0 return appearance } static var _5 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray // Message appearance.message.textColor = UIColor.darkGray appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.leftBesideMessage // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) return appearance } static var _6 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) return appearance } static var btnConfirmationNo : BoxButtonAppearance{ var appearance = BoxButtonAppearance() appearance.backgroundColor = UIColor.init(red: 210.0/255.0, green: 210.0/255.0, blue: 210.0/255.0, alpha: 1.0) appearance.textColor = UIColor.darkGray return appearance } static var btnConfirmationYes : BoxButtonAppearance{ var appearance = BoxButtonAppearance() appearance.backgroundColor = UIColor.init(red: 237.0/255.0, green: 86.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.textColor = UIColor.white return appearance } static var _7 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray // Message appearance.message.textColor = UIColor.darkGray // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.bottomPosition.layout = BoxButtonBottomPositionLayout.withoutSpacing return appearance } static var _9 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.padding = 0 appearance.layout.cornerRadius = 0.0 appearance.layout.width = 270.0 // Title appearance.title.padding = "0|10|0|10" appearance.title.textColor = UIColor.darkGray appearance.title.backgroundColor = UIColor.init(red: 220.0/255.0, green: 220.0/255.0, blue: 220.0/255.0, alpha: 1.0) // Message appearance.message.margin = "20|0|20|0" appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "update" appearance.icon.size = CGSize(width: 70, height: 70) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.borderWidth = 1.0 appearance.button.borderColor = UIColor.lightGray appearance.button.bottomPosition.layout = BoxButtonBottomPositionLayout.withoutSpacing appearance.button.bottomPosition.maximumNoOfButtonsInSingleRow = 1 return appearance } static var btnTitleBgNo : BoxButtonAppearance{ var appearance = BoxButtonAppearance() appearance.backgroundColor = UIColor.white appearance.textColor = UIColor.darkGray return appearance } static var btnTitleBgAppStore : BoxButtonAppearance{ var appearance = BoxButtonAppearance() appearance.backgroundColor = UIColor.init(red: 32.0/255.0, green: 128.0/255.0, blue: 175.0/255.0, alpha: 1.0) appearance.textColor = UIColor.white return appearance } static var _10 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 appearance.layout.backgroundColor = UIColor.init(red: 212.0/255.0, green: 72.0/255.0, blue: 59.0/255.0, alpha: 1.0) // Title appearance.title.padding = "0|30|0|10" appearance.title.textColor = UIColor.white appearance.title.font = UIFont.boldSystemFont(ofSize: 18.0) // Message appearance.message.margin = "20|0|20|0" appearance.message.textColor = UIColor.white appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "error" appearance.icon.size = CGSize(width: 70, height: 70) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.backgroundColor = UIColor.init(red: 163.0/255.0, green: 54.0/255.0, blue: 44.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 20.0 appearance.button.containerMargin = "0|10|0|10" // Close appearance.closeButton.show = true appearance.closeButton.font = UIFont.boldSystemFont(ofSize: 16.0) appearance.closeButton.title = "X" appearance.closeButton.textColor = UIColor.white appearance.closeButton.position = BoxCloseButtonPosition.cornerInside return appearance } static var _11 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray // Message appearance.message.textColor = UIColor.darkGray // Animation appearance.animation = BoxAnimationType.bounce // Close appearance.closeButton.show = true appearance.closeButton.imageName = "cancel" appearance.closeButton.position = BoxCloseButtonPosition.cornerOutside return appearance } static var _12 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.padding = 0.0 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textAlignment = NSTextAlignment.left appearance.title.textColor = UIColor.darkGray appearance.title.margin = "20|20|20|0" // Message appearance.message.textAlignment = NSTextAlignment.left appearance.message.textColor = UIColor.darkGray appearance.message.margin = "20|0|20|0" // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.bottomPosition.cornerRadius = 0 appearance.button.containerMargin = "120|0|0|10" appearance.button.bottomPosition.horizontalSpacing = 0.0 appearance.button.backgroundColor = UIColor.white appearance.button.textColor = UIColor.init(red: 237.0/255.0, green: 86.0/255.0, blue: 77.0/255.0, alpha: 1.0) return appearance } static var _13 : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.backgroundColor = UIColor.init(red: 99.0/255.0, green: 157.0/255.0, blue: 72.0/255.0, alpha: 1.0) appearance.layout.cornerRadius = 10.0 appearance.layout.width = 300.0 // Title appearance.title.textColor = UIColor.white appearance.title.font = UIFont.boldSystemFont(ofSize: 20.0) // Message appearance.message.textColor = UIColor.white appearance.message.font = UIFont.systemFont(ofSize: 17.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "email" appearance.icon.margin = "0|30|0|20" appearance.icon.position = BoxIconPosition.topCenter appearance.icon.size = CGSize(width: 116, height: 117) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.bottomPosition.cornerRadius = 20 appearance.button.backgroundColor = UIColor.init(red: 99.0/255.0, green: 157.0/255.0, blue: 72.0/255.0, alpha: 1.0) appearance.button.textColor = UIColor.white appearance.button.borderColor = UIColor.white appearance.button.borderWidth = 2.0 appearance.button.containerMargin = "70|20|70|40" return appearance } static var _14 : BoxAppearance { var appearance = BoxAppearance() appearance.autoDismiss = true appearance.position = BoxPosition.bottom // Layout appearance.layout.backgroundColor = UIColor.white appearance.layout.cornerRadius = 10.0 appearance.layout.width = 170.0 // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) appearance.containerBackground.tapToDismiss = true // Message appearance.message.textColor = UIColor.black appearance.message.font = UIFont.boldSystemFont(ofSize: 18.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "save" appearance.icon.position = BoxIconPosition.topCenter appearance.icon.size = CGSize(width: 70, height: 70) // Animation appearance.animation = BoxAnimationType.bounce return appearance } } struct BoxAppearanceNotification { static var _1 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.spacing = 10 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 appearance.layout.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.margin = "10|0|10|0" // Message appearance.message.textColor = UIColor.white appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.margin = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.slideFromTop return appearance } static var _2 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 64 appearance.autoDismiss = true // Layout appearance.layout.spacing = 10 appearance.layout.padding = 20 appearance.layout.cornerRadius = 0.0 appearance.layout.width = Float(UIScreen.main.bounds.size.width) appearance.layout.backgroundColor = UIColor.init(red: 225.0/255.0, green: 78.0/255.0, blue: 73.0/255.0, alpha: 1.0) // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.position = BoxIconPosition.leftFullHeight appearance.icon.image.name = "warning" appearance.icon.padding = "20|0|20|0" // Animation appearance.animation = BoxAnimationType.slideFromTop return appearance } static var _3 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 64 appearance.autoDismiss = true // Layout appearance.layout.spacing = 10 appearance.layout.padding = 20 appearance.layout.cornerRadius = 0.0 appearance.layout.width = Float(UIScreen.main.bounds.size.width) appearance.layout.backgroundColor = UIColor.init(red: 225.0/255.0, green: 78.0/255.0, blue: 73.0/255.0, alpha: 1.0) // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "warning" appearance.icon.padding = "20|0|20|0" appearance.icon.position = BoxIconPosition.leftFullHeight appearance.icon.separator.show = true appearance.icon.separator.borderWidth = 1.0 appearance.icon.separator.color = UIColor.white appearance.icon.separator.margin = 10.0 // Animation appearance.animation = BoxAnimationType.slideFromTop return appearance } static var _4 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.spacing = 10 appearance.layout.padding = 20 appearance.layout.cornerRadius = 10.0 appearance.layout.width = 300.0 appearance.layout.backgroundColor = UIColor.white appearance.layout.borderWidth = 2.0 appearance.layout.borderColor = UIColor.init(red: 142.0/255.0, green: 176.0/255.0, blue: 37.0/255.0, alpha: 1.0) // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.darkGray appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.position = BoxIconPosition.leftFullHeight appearance.icon.image.name = "successWhite" appearance.icon.padding = "20|0|20|0" appearance.icon.size = CGSize(width: 30, height: 30) appearance.icon.backgroundColor = UIColor.init(red: 142.0/255.0, green: 176.0/255.0, blue: 37.0/255.0, alpha: 1.0) // Animation appearance.animation = BoxAnimationType.slideFromTop return appearance } static var _5 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 20 // Layout appearance.layout.spacing = 5 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 300.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.darkGray appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.leftFullHeight appearance.icon.padding = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.slideFromTop // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) appearance.button.position = BoxButtonPosition.right return appearance } static var _6 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 20 // Layout appearance.layout.spacing = 5 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 300.0 appearance.layout.backgroundColor = UIColor.init(red: 225.0/255.0, green: 78.0/255.0, blue: 73.0/255.0, alpha: 1.0) // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.white appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "warning" appearance.icon.size = CGSize(width: 30, height: 30) appearance.icon.position = BoxIconPosition.leftFullHeight appearance.icon.padding = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.slideFromTop // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 178.0/255.0, green: 62.0/255.0, blue: 59.0/255.0, alpha: 1.0) appearance.button.borderColor = UIColor.white appearance.button.borderWidth = 1.0 appearance.button.position = BoxButtonPosition.right return appearance } static var _8 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 30 // Layout appearance.layout.spacing = 10 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.margin = "10|0|10|0" // Message appearance.message.textColor = UIColor.darkGray appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.margin = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.slideFromTop // Close appearance.closeButton.show = true appearance.closeButton.position = BoxCloseButtonPosition.cornerOutside appearance.closeButton.imageName = "cancel" return appearance } static var _7 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 20 // Layout appearance.layout.spacing = 10 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 appearance.layout.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.margin = "10|0|10|0" // Message appearance.message.textColor = UIColor.white appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.margin = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.slideFromTop // Close appearance.closeButton.show = true appearance.closeButton.position = BoxCloseButtonPosition.cornerInside appearance.closeButton.title = "x" appearance.closeButton.textColor = UIColor.white return appearance } } struct BoxAppearanceLoading { static var _1 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.enableShadow = false appearance.layout.width = 100.0 appearance.layout.backgroundColor = UIColor.clear // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _2 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.enableShadow = false appearance.layout.width = 100.0 appearance.layout.backgroundColor = UIColor.clear // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.loading.imageName = "loadingBlue" // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _3 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 20 appearance.layout.enableShadow = false appearance.layout.width = 80.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.loading.imageName = "loadingBlue" // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _4 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.spacing = 10 appearance.layout.enableShadow = false appearance.layout.width = 150.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.position = BoxIconPosition.topCenter appearance.icon.loading.imageName = "loadingPurple" // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _5 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.spacing = 10 appearance.layout.enableShadow = false appearance.layout.width = 150.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Title appearance.title.font = UIFont.systemFont(ofSize: 16.0) appearance.title.textColor = UIColor.darkGray // Icon appearance.icon.type = BoxIconType.loading appearance.icon.position = BoxIconPosition.centerBelowTitle appearance.icon.loading.imageName = "loadingPurple" // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _6 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.spacing = 0 appearance.layout.enableShadow = false appearance.layout.width = 150.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.position = BoxIconPosition.leftBesideMessage appearance.icon.loading.imageName = "loadingPurple" appearance.icon.size = CGSize(width: 20, height: 20) // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _7 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.spacing = 10 appearance.layout.enableShadow = false appearance.layout.width = 250.0 appearance.layout.backgroundColor = UIColor.white // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.position = BoxIconPosition.centerBelowTitle appearance.icon.loading.imageName = "loadingPurple" // Animation appearance.animation = BoxAnimationType.fade return appearance } static var _8 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.enableShadow = false appearance.layout.width = 300.0 appearance.layout.backgroundColor = UIColor.white // Title appearance.title.textAlignment = NSTextAlignment.left // Message appearance.message.textAlignment = NSTextAlignment.left // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 0.0, green: 0.0, blue: 0.0, alpha: 0.7) // Icon appearance.icon.type = BoxIconType.loading appearance.icon.position = BoxIconPosition.leftBesideMessage appearance.icon.loading.imageName = "loadingPurple" // Animation appearance.animation = BoxAnimationType.fade return appearance } } struct BoxAppearanceScreenMessages { static var _1 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.enableShadow = false appearance.layout.width = Float(UIScreen.main.bounds.size.width-40) appearance.layout.backgroundColor = UIColor.clear // Background appearance.containerBackground.tapToDismiss = true appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.white // Message appearance.message.font = UIFont.boldSystemFont(ofSize: 16.0) appearance.message.textColor = UIColor.darkGray // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "search" appearance.icon.size = CGSize(width: 100, height: 100) // Animation appearance.animation = BoxAnimationType.none return appearance } static var _2 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.enableShadow = false appearance.layout.width = Float(UIScreen.main.bounds.size.width-40) appearance.layout.backgroundColor = UIColor.clear // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.white // Message appearance.message.font = UIFont.boldSystemFont(ofSize: 16.0) appearance.message.textColor = UIColor.darkGray // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "wifi" appearance.icon.size = CGSize(width: 100, height: 100) // Animation appearance.animation = BoxAnimationType.none // Button appearance.button.containerMargin = "80|0|80|0" appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.bottomPosition.cornerRadius = 20.0 appearance.button.bottomPosition.maximumNoOfButtonsInSingleRow = 1 appearance.button.backgroundColor = UIColor.init(red: 0.0, green: 165.0/255.0, blue: 218.0/255.0, alpha: 1.0) return appearance } static var _3 : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 appearance.autoDismiss = true // Layout appearance.layout.padding = 10 appearance.layout.enableShadow = false appearance.layout.width = Float(UIScreen.main.bounds.size.width-40) appearance.layout.backgroundColor = UIColor.clear // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.white // Title appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.textColor = UIColor.darkGray // Icon appearance.icon.type = BoxIconType.image appearance.icon.image.name = "podcast" appearance.icon.size = CGSize(width: 100, height: 100) // Animation appearance.animation = BoxAnimationType.none // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.bottomPosition.cornerRadius = 20.0 appearance.button.bottomPosition.maximumNoOfButtonsInSingleRow = 1 appearance.button.textColor = UIColor.init(red: 127.0/255.0, green: 34.0/255.0, blue: 185.0/255.0, alpha: 1.0) appearance.button.backgroundColor = UIColor.clear appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 16.0) return appearance } static var _4 : BoxAppearance{ var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = Float(UIScreen.main.bounds.size.width - CGFloat(40.0)) appearance.layout.backgroundColor = UIColor.clear appearance.layout.enableShadow = false // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.textColor = UIColor.init(red: 23.0/255.0, green: 76.0/255.0, blue: 43.0/255.0, alpha: 1.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.textColor = UIColor.init(red: 23.0/255.0, green: 76.0/255.0, blue: 43.0/255.0, alpha: 1.0) appearance.message.margin = "0|0|0|20" // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 100, height: 100) appearance.icon.image.name = "successWhite" appearance.icon.position = BoxIconPosition.topCenter appearance.icon.margin = "0|0|0|80" // Animation appearance.animation = BoxAnimationType.none appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 100.0/255.0, green: 208.0/255.0, blue: 44.0/255.0, alpha: 1.0) // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.darkGray appearance.button.backgroundColor = UIColor.white appearance.button.bottomPosition.cornerRadius = 3.0 appearance.button.containerMargin = "50|0|50|0" return appearance } static var _5 : BoxAppearance{ var appearance = BoxAppearance() appearance.position = BoxPosition.top appearance.positionMargin = 0 // Layout appearance.layout.padding = 0 appearance.layout.cornerRadius = 5.0 appearance.layout.width = Float(UIScreen.main.bounds.size.width) appearance.layout.backgroundColor = UIColor.clear appearance.layout.enableShadow = false // Title appearance.title.textColor = UIColor.init(red: 10.0/255.0, green: 9.0/255.0, blue: 79.0/255.0, alpha: 1.0) appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.margin = "20|30|0|0" // Message appearance.message.textColor = UIColor.darkGray appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.margin = "20|0|0|20" // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 100, height: 100) appearance.icon.image.name = "successWhite" appearance.icon.position = BoxIconPosition.topCenter appearance.icon.backgroundColor = UIColor.init(red: 100.0/255.0, green: 208.0/255.0, blue: 44.0/255.0, alpha: 1.0) appearance.icon.padding = "\((Float(UIScreen.main.bounds.size.width) - 100)/2)|100|\((Float(UIScreen.main.bounds.size.width) - 100)/2)|100" // Animation appearance.animation = BoxAnimationType.none // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.white // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 177.0/255.0, green: 209.0/255.0, blue: 6.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 appearance.button.containerMargin = "70|40|70|0" return appearance } } struct BoxAppearanceAnimation { static var fade : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Animation appearance.animation = BoxAnimationType.fade // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var bounce : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 70, height: 70) appearance.icon.image.name = "success" appearance.icon.margin = "0|-55|0|0" appearance.icon.position = BoxIconPosition.topCenter // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var slideFromTop : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Animation appearance.animation = BoxAnimationType.slideFromTop // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var slideFromBottom : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Animation appearance.animation = BoxAnimationType.slideFromBottom // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var none : BoxAppearance { var appearance = BoxAppearance() appearance.position = BoxPosition.center appearance.positionMargin = 20 // Layout appearance.layout.spacing = 10 appearance.layout.padding = 10 appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 appearance.layout.backgroundColor = UIColor.init(red: 98.0/255.0, green: 193.0/255.0, blue: 104.0/255.0, alpha: 1.0) // Title appearance.title.textColor = UIColor.white appearance.title.textAlignment = NSTextAlignment.left appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) appearance.title.margin = "10|0|10|0" // Message appearance.message.textColor = UIColor.white appearance.message.textAlignment = NSTextAlignment.left appearance.message.font = UIFont.systemFont(ofSize: 16.0) appearance.message.margin = "10|0|10|0" // Animation appearance.animation = BoxAnimationType.none // Close appearance.closeButton.show = true appearance.closeButton.position = BoxCloseButtonPosition.cornerInside appearance.closeButton.title = "x" appearance.closeButton.textColor = UIColor.white return appearance } } struct BoxAppearanceBackground { static var darkBlur : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Background appearance.containerBackground.style = BoxBackgroundStyle.darkBlur // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var lightBlur : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Background appearance.containerBackground.style = BoxBackgroundStyle.lightBlur // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var extraLightBlur : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Background appearance.containerBackground.style = BoxBackgroundStyle.extraLightBlur // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var none : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Background appearance.containerBackground.style = BoxBackgroundStyle.none // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } static var custom : BoxAppearance { var appearance = BoxAppearance() // Layout appearance.layout.cornerRadius = 5.0 appearance.layout.width = 270.0 // Title appearance.title.textColor = UIColor.darkGray appearance.title.font = UIFont.boldSystemFont(ofSize: 17.0) // Message appearance.message.textColor = UIColor.darkGray appearance.message.font = UIFont.systemFont(ofSize: 16.0) // Icon appearance.icon.type = BoxIconType.image appearance.icon.size = CGSize(width: 50, height: 50) appearance.icon.image.name = "success" appearance.icon.position = BoxIconPosition.centerBelowTitle // Background appearance.containerBackground.style = BoxBackgroundStyle.customColor appearance.containerBackground.color = UIColor.init(red: 1.0, green: 0.0, blue: 0.0, alpha: 0.4) // Animation appearance.animation = BoxAnimationType.bounce // Button appearance.button.position = BoxButtonPosition.bottom appearance.button.titleFont = UIFont.boldSystemFont(ofSize: 17.0) appearance.button.textColor = UIColor.white appearance.button.backgroundColor = UIColor.init(red: 103.0/255.0, green: 196.0/255.0, blue: 77.0/255.0, alpha: 1.0) appearance.button.bottomPosition.cornerRadius = 3.0 return appearance } }
true
56e5fac433633149ef2a4de2dd6c3229b03ba11f
Swift
tonnylitao/swift-vs-kotlin
/language-code/doc-swift/LANGUAGE GUIDE_Protocols_42_e75fe331a70cdd04c9370e9bceba05d8.swift
UTF-8
331
3.25
3
[]
no_license
struct Vector3D: Equatable { var x = 0.0, y = 0.0, z = 0.0 } let twoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0) let anotherTwoThreeFour = Vector3D(x: 2.0, y: 3.0, z: 4.0) if twoThreeFour == anotherTwoThreeFour { print("These two vectors are also equivalent.") } // Prints "These two vectors are also equivalent."
true
b5605d1fb682301aade8786041c6285e3d0bcd32
Swift
Wuskuj/VkNewsList
/VkNewsList/GalleryCollectionView.swift
UTF-8
1,431
2.78125
3
[]
no_license
// // GalleryCollectionView.swift // VkNewsList // // Created by Philip Bratov on 01.04.2021. // import Foundation import UIKit class GalleryCollectionView: UICollectionView { var photos = [FeedCellPhotoAttachmentViewModel]() init() { let layout = UICollectionViewFlowLayout() layout.scrollDirection = .horizontal super.init(frame: .zero, collectionViewLayout: layout) delegate = self dataSource = self backgroundColor = .darkGray register(GalleryCollectionViewCell.self, forCellWithReuseIdentifier: GalleryCollectionViewCell.reuseId) } func set(photos: [FeedCellPhotoAttachmentViewModel]) { self.photos = photos reloadData() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } extension GalleryCollectionView: UICollectionViewDelegate, UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return photos.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: GalleryCollectionViewCell.reuseId, for: indexPath) as! GalleryCollectionViewCell cell.set(imageUrl: photos[indexPath.row].photoUrlString) return cell } }
true
10f216c069d1e8ac8e489c19a08633a2aec6b52c
Swift
adrianOrtiz2/Movies-App
/Movies/Networking/Promises/Future.swift
UTF-8
2,917
3.421875
3
[]
no_license
// // Future.swift // Movies // // Created by Adrian Ortiz on 5/13/19. // Copyright © 2019 Adrian Ortiz. All rights reserved. // import UIKit class Future<Value> { typealias FutureResult = Result<Value, Error> var result: FutureResult? { // Observe whenever a result is assigned, and report it didSet { result.map(report) } } private lazy var callbacks = [(FutureResult) -> Void]() func observe(with callback: @escaping (FutureResult) -> Void) { callbacks.append(callback) // If a result has already been set, call the callback directly result.map(callback) } private func report(result: FutureResult) { for callback in callbacks { callback(result) } } } // MARK: - Chaining extension Future { private func chained<NextValue>(with closure: @escaping (FutureResult) throws -> Future<NextValue>) -> Future<NextValue> { //Promise wrapper let promise = Promise<NextValue>() // Observe the current future observe { result in switch result { case .success(let value): do { // Attempt to construct a new future given the value from the first one let future = try closure(.success(value)) //Observe the neasted futuare and once is completed resolve wrapper future future.observe(with: { result in switch result { case .success(let value): promise.resolve(with: value) case .failure(let error): promise.reject(with: error) } }) } catch { promise.reject(with: error) } break case .failure(let error): promise.reject(with: error) } } return promise } } // MARK: - Transforms extension Future { private func transformed<NextValue>(with closure: @escaping (FutureResult) throws -> NextValue) -> Future<NextValue> { return chained(with: { value in return try Promise(value: closure(value)) }) } } // MARK: - Decode extension Future where Value == Data { func decoded<NextValue: Decodable>() -> Future<NextValue> { return transformed { try JSONDecoder().decode(NextValue.self, from: $0.get()) } } } extension Future where Value == NSData { func decodeImage() -> Future<UIImage> { return transformed { guard let image = try UIImage(data: Data(referencing: $0.get())) else { throw EndpointError.invalidURL } return image } } }
true
13ec4154b4281941e14a7835ca274c3f54403e38
Swift
swiftmocks/SwiftMocks
/TestFrameworks/MocksFixtures/Source/Fixtures.swift
UTF-8
5,677
2.75
3
[ "Apache-2.0" ]
permissive
// This source file is part of SwiftInternals open source project. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // // Copyright © 2019-2020, Sergiy Drapiko // Copyright © 2020, SwiftMocks project contributors // contains all types with internal and public visibility, needed for tests import Foundation func voidFunction() {} func simpleFunction(_ param: Double) -> Int { 0 } func voidThrowingFunction() throws {} func simpleThrowingFunction(_ param: Double) throws -> Int { 0 } func functionWithUnsupportedReturnType() -> Float80 { 0.0 } func functionWithInOutParameters(_ param1: inout String, _ param2: inout SomeClass, _ param3: inout SomeStruct) -> (String, SomeClass, SomeStruct) { (param1, param2, param3) } var someGlobalVar: Int = 0 { didSet {} } struct EmptyStruct {} class EmptyClass {} class SomeClass { var computedVar: String { "" } var varWithDidSet = [String]() { didSet {} } static var someStaticVar: String { "" } func method(string: String) -> Int { 0 } func throwingMethod(string: String) throws -> Int { 0 } class func classMethod(_ param1: Double, _ param2: String) -> Int { 0 } class func throwingClassMethod(_ param1: Double, _ param2: String) throws -> Int { 0 } } struct SomeStruct: Equatable { init(varWithDidSet: [String] = []) { self.varWithDidSet = varWithDidSet } var computedVar: String { "" } var varWithDidSet = [String]() { didSet {} } static var someStaticVar: String { "" } func method(_ param1: Double, _ param2: String) -> String { "" } func throwingMethod(_ param1: Double, _ param2: String) throws -> String { "" } static func staticMethod(_ param1: Double, _ param2: String) -> [String: Int] { [:] } static func throwingStaticMethod(_ param1: Double, _ param2: String) throws -> [String: Int] { [:] } } struct NonEquatableStructWithAMethod { func method() -> Int { 0 } } class SomeChildClass: SomeClass {} protocol EmptyProtocol {} protocol AnotherEmptyProtocol {} protocol EmptyProtocolWithClassConstraint: class {} protocol EmptyChildProtocol: EmptyProtocol {} protocol EmptyErrorProtocol: Error { } @objc protocol EmptyObjCProtocol {} protocol ProtocolWithAMethod { func method() -> Int } protocol ProtocolWithFiveMethods { func method_0() func method_1() func method_2() func method_3() func method_4() } protocol ProtocolWithDefaultImplementation: AnyObject { func method(_ param: Int) -> Double } extension ProtocolWithDefaultImplementation { func method(_ param: Int) -> Double { 0.0 } func nonRequirementMethod(_ param: String) -> Int { 0 } var nonRequirementVar: Int { 0 } } protocol ProtocolWithAssociatedTypes { associatedtype T func foo() -> Self } protocol RealisticallyLookingProtocol { var someVar: String { get set } func method(param: Double) -> [String: [Int]] static func staticMethod(_ param: Int) -> [String] } struct ModifiableStruct { var prop: String } protocol ProtocolWithModify { var modifiableStructProp: ModifiableStruct { get set } var modifiableTupleProp: (String, [Int]) { get set } } protocol ProtocolWithSubscript { subscript(index: Int) -> ModifiableStruct { get set } subscript(_ index1: Int, _ index2: String) -> ModifiableStruct { get set } } protocol BaseProtocolForRealisticallyLookingProtocol { var someVar: String { get set } func method(param: Double) -> Character static func staticMethod(_ param: Int) -> [String] static var staticVar: BaseProtocolForRealisticallyLookingProtocol { get set } var someVarToOverride: Double { get set } func methodToOverride(_ param: Int) -> EmptyClass static func staticMethodToOverride(_ param: inout EmptyClass) -> Int static var staticVarToOverride: BaseProtocolForRealisticallyLookingProtocol { get set } } protocol RealisticallyLookingProtocolWithABaseProtocol: BaseProtocolForRealisticallyLookingProtocol { var someVarToOverride: Double { get set } func methodToOverride(_ param: Int) -> EmptyClass static func staticMethodToOverride(_ param: inout EmptyClass) -> Int static var staticVarToOverride: BaseProtocolForRealisticallyLookingProtocol { get set } } protocol ProtocolWithTwoBaseProtocols: RealisticallyLookingProtocolWithABaseProtocol, ProtocolWithAMethod { func method(_ param: String) -> [String] } class BaseClassForRealisticallyLookingProtocol {} protocol RealisticallyLookingProtocolWithABaseClass: BaseClassForRealisticallyLookingProtocol, EmptyChildProtocol { var foo: Int { get } func method() static func classMethod() } class RealisticallyLoookingClass: BaseClassForRealisticallyLookingProtocol, RealisticallyLookingProtocolWithABaseClass { let foo: Int = 123456 func method() {} static func classMethod() {} } class GenericParentClass<T> {} protocol ProtocolWithGenericMethod { func method<T>(param: T) } protocol ProtocolWithSelfConformance { func method() -> Self }
true
a86458505e75a87cc44328bef25955af3da0ed1a
Swift
saurabh091/Swift-CleanArchitecture
/Data/Sources/Data/CacheInterface.swift
UTF-8
642
2.65625
3
[]
no_license
// // CacheInterface.swift // Data // // Created by Cassius Pacheco on 7/7/18. // Copyright © 2018 Cassius Pacheco. All rights reserved. // import Foundation public protocol CacheInterface { func removeValue(for key: String) func save<Value>(_ value: Value?, for key: String) func value<Value>(for key: String) -> Value? func bool(for key: String) -> Bool func saveEncoded<Value: Codable>(_ value: Value?, for key: String) func decodedValue<Value: Codable>(for key: String) -> Value? } public extension CacheInterface { static var appGroup: String { return "group.com.cassiuspacheco.Swift-CleanArchitecture" } }
true
5e025f85d4bc3eb2bd4629d9f5e1b7c090c8e7e4
Swift
jkahl7/Week3githubClinet
/GETgithub/GETgithub/NetController.swift
UTF-8
9,442
2.546875
3
[]
no_license
// // NetController.swift // GETgithub // // Created by Josh Kahl on 1/19/15. // Copyright (c) 2015 Josh Kahl. All rights reserved. // import UIKit class NetworkController { class var sharedNetworkController:NetworkController { struct Static { static let instance:NetworkController = NetworkController() } return Static.instance } var urlSession : NSURLSession var accessToken : String? let imageQueue = NSOperationQueue() let clientID = "e3ecc12cc38533806169" let clientSecret = "60394bb88b65cf8df87088c6556b604ca5c4cf46" let accessTokenKey = "accessTokenKey" init () { //Returns a session configuration that uses no persistent storage for caches, cookies, or credentials. let ephemeralConfiguration = NSURLSessionConfiguration.ephemeralSessionConfiguration() self.urlSession = NSURLSession(configuration: ephemeralConfiguration) if let keyCheck = NSUserDefaults.standardUserDefaults().objectForKey("accessTokenKey") as? String { self.accessToken = keyCheck } } /********************************************************************************************* *** MARK: requestAccessToken *** *********************************************************************************************/ func requestAccessToken() { let url = NSURL(string:"https://github.com/login/oauth/authorize?client_id=\(self.clientID)&scope=user,repo,notifications") UIApplication.sharedApplication().openURL(url!) } /********************************************************************************************* *** MARK: handleCallbackURL *** *********************************************************************************************/ //this method will be called within the appDelegate / func handleCallbackURL(url: NSURL) { // this is the code recieved from github upon the initial request for access let code = url.query // get the POST url from github - let baseURL = NSURL(string:"https://github.com/login/oauth/access_token?\(code!)&client_id=\(self.clientID)&client_secret=\(self.clientSecret)") let requestPOST = NSMutableURLRequest(URL: baseURL!) requestPOST.HTTPMethod = "POST" let dataTask = self.urlSession.dataTaskWithRequest(requestPOST, completionHandler: { (data, response, error) -> Void in if (error == nil) { if let urlResponse = response as? NSHTTPURLResponse { switch urlResponse.statusCode { case 200...299: println("\(urlResponse.statusCode)") // the data github is returning is not JSON - TODO: there is a way to request JSON let tokenRecieved = NSString(data: data, encoding: NSASCIIStringEncoding) //now need to parse the response and pull out the token let tokenComponent = tokenRecieved?.componentsSeparatedByString("&").first as String let token = tokenComponent.componentsSeparatedByString("=").last //store this using NSUserDefault - in init constructor - check if this key has a value and assgin it to the accessToken NSUserDefaults.standardUserDefaults().setObject(token, forKey: self.accessTokenKey) NSUserDefaults.standardUserDefaults().synchronize() case 300...499: println("\(urlResponse.statusCode)") case 500...599: println("\(urlResponse.statusCode)") default: println("default case triggered - not good") } } } }) dataTask.resume() } /********************************************************************************************* *** MARK: RepoForSearchTerm *** *********************************************************************************************/ //search repo for searchTerm - callback returns a populated array of Repo structs or an error func fetchRepoForSearchTerm(searchTerm:String?, callback:(repo:[Repo]?, error:String?) -> (Void)) { //dataTask initilizes the dataTaskWithURL method in if let formatedSearchRequest = searchTerm?.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil) { let url = NSURL(string: "https://api.github.com/search/repositories?q=\(formatedSearchRequest)") let urlRequest = NSMutableURLRequest(URL: url!) urlRequest.setValue("token \(self.accessToken!)", forHTTPHeaderField: "Authorization") let dataTask = self.urlSession.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in if(error == nil) // cast response into NSHTTPURLResponse to get source codes { if let urlResponse = response as? NSHTTPURLResponse { switch urlResponse.statusCode { case 200...299: var error : NSError? if let rawJSONData = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String:AnyObject] { if(error == nil) { var repo = [Repo]() if let totalCount = rawJSONData["total_count"] as? Int { if let jsonArray = rawJSONData["items"] as? [[String:AnyObject]] { for item in jsonArray { let info = Repo(jsonDictionary: item, totalCount: totalCount) repo.append(info) } NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in callback(repo: repo, error: nil) }) } } } } case 300...599: println("\(urlResponse.statusCode)") default: println("\(urlResponse.statusCode)") } } } }) dataTask.resume() } NSOperationQueue.mainQueue().addOperationWithBlock { () -> Void in callback(repo: nil, error: "") } } /********************************************************************************************* *** MARK: UserInfo *** *********************************************************************************************/ func fetchUserInfo(userName:String?, callback:(user:[User]?, error:String?) -> (Void)) { // checks if userName is not empty - i think - and removes any spaces - maybe...... if let userString = userName?.stringByReplacingOccurrencesOfString(" ", withString: "+", options: NSStringCompareOptions.LiteralSearch, range: nil) { //get api location url from github /search/users let userSearchUrl = NSURL(string:"https://api.github.com/search/users?q=\(userString)") let urlRequest = NSMutableURLRequest(URL: userSearchUrl!) urlRequest.setValue("token \(self.accessToken!)", forHTTPHeaderField: "Authorization") let dataTask = self.urlSession.dataTaskWithRequest(urlRequest, completionHandler: { (data, response, error) -> Void in if(error == nil) { if let urlResponse = response as? NSHTTPURLResponse { switch urlResponse.statusCode { case 200...299: var error:NSError? if let rawJSONData = NSJSONSerialization.JSONObjectWithData(data, options: nil, error: &error) as? [String:AnyObject] { if (error == nil) { var users = [User]() if let jsonDictionary = rawJSONData["items"] as? [[String:AnyObject]] { for dictionary in jsonDictionary { let info = User(jsonDictionary: dictionary) users.append(info) } NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in callback(user: users, error: nil) }) } } } default: println("\(urlResponse.statusCode)") } } } }) dataTask.resume() } } /********************************************************************************************* *** MARK: UserImageFetch *** *********************************************************************************************/ func fetchUserImage(userImageURL:NSURL, index:NSIndexPath, completionHandler: (userImage:UIImage?, storedIndex: Int, errorReport:String?) -> (Void)) { self.imageQueue.addOperationWithBlock { () -> Void in let imageData = NSData(contentsOfURL: userImageURL)! let image = UIImage(data: imageData) let indexKeeper = index.row NSOperationQueue.mainQueue().addOperationWithBlock({ () -> Void in completionHandler(userImage: image, storedIndex: indexKeeper, errorReport: nil) }) } } }
true
fff9a997bf8f18232fe53c9e6ff1eba5dffba5a7
Swift
shuyangxiaobao/DesignPatterns
/9.组合模式/geqiangbao_20201127_Component_swift/geqiangbao_20201127_Component_swift/案例二:改进案例/ComponentProtocol2.swift
UTF-8
611
3.125
3
[]
no_license
// // ComponentProtocol2.swift // geqiangbao_20201127_Component_swift // // Created by xiaobao on 2020/11/27. // import Foundation //根节点有几个特点需要注意(父节点根据你的设计决定) protocol ComponentProtocol2 { //特点一:节点名字 var name:String{get} //特点二:子节点(数组) var components:Array<ComponentProtocol2>{get} //特点三:业务逻辑 func doSomthing() func addChild(child:ComponentProtocol2) func removeChild(child:ComponentProtocol2) func getChild(index:Int) -> ComponentProtocol2 func clear() }
true
81f05c8dfd5f59a4cbc41e62fcb9e79340e5b914
Swift
inancerr/DemoApp
/Packages/Utility/Sources/Utility/Extensions/UIStackView+Extensions.swift
UTF-8
877
2.765625
3
[]
no_license
// // File.swift // // // Created by İnanç Er on 7.05.2021. // import class UIKit.UIStackView import class UIKit.UIView import struct UIKit.CGFloat public func vStack( distribution: UIStackView.Distribution = .fill, alignment: UIStackView.Alignment = .fill, space: CGFloat = 0, isBaselineRelativeArrangement: Bool = false, isLayoutMarginsRelativeArrangement: Bool = false ) -> (UIView...) -> UIStackView { { (views: UIView...) in let stackView = UIStackView(arrangedSubviews: views) stackView.axis = .vertical stackView.spacing = space stackView.alignment = alignment stackView.distribution = distribution stackView.isBaselineRelativeArrangement = isBaselineRelativeArrangement stackView.isLayoutMarginsRelativeArrangement = isLayoutMarginsRelativeArrangement return stackView } }
true
318c0e08e3a2d66037b23b7c59e0ae24c5fcef47
Swift
EnderXenocida/TestBBC
/BBC/BBC/Classes/Interfaces/News/NewsViewModel.swift
UTF-8
812
2.6875
3
[]
no_license
// // NewsViewModel.swift // BBC // // Created by GlobalTMS on 21/02/2019. // Copyright © 2019 Adrián Egea. All rights reserved. // import Foundation class NewsViewModel: NewsViewModelProtocol { var refreshClosure: () -> Void = {} var news: [NewsModel] = [] { didSet { refreshClosure() } } func getNews(_ onFailure: @escaping () -> Void) { NewsRepository().getNews({ [weak self] (newsList) in self?.news = newsList }, onFailure: onFailure) } func getNew(_ row: Int) -> NewsModel? { return news[row] } func getNewsCount() -> Int { return news.count } func setRefreshClosure(_ refreshClosure: @escaping () -> Void) { self.refreshClosure = refreshClosure } }
true
7a8b2e0642dd95cabd57d78100483e6b6250661f
Swift
RobbieZhuang/WWDC2018
/MagicMagic.playground/Sources/ColorExtensions.swift
UTF-8
1,377
2.796875
3
[]
no_license
// // SKTextureGradient.swift // Linear gradient texture // Based on: https://gist.github.com/Tantas/7fc01803d6b559da48d6, https://gist.github.com/craiggrummitt/ad855e358004b5480960 // // Created by Maxim on 1/1/16. // Copyright © 2016 Maxim Bilan. All rights reserved. // import SpriteKit public extension SKTexture { convenience init(color1: CIColor, color2: CIColor, startPoint: CGPoint, endPoint: CGPoint) { let size = CGSize(width: abs(startPoint.x-endPoint.x+1), height: abs(startPoint.y-endPoint.y+1)) let context = CIContext(options: nil) let filter = CIFilter(name: "CILinearGradient") var startVector: CIVector var endVector: CIVector filter!.setDefaults() startVector = CIVector(x: startPoint.x, y: startPoint.y) endVector = CIVector(x: endPoint.x, y: endPoint.y) // print("Memes") // print(startVector) // print(endVector) // filter!.setValue(startVector, forKey: "inputPoint0") filter!.setValue(endVector, forKey: "inputPoint1") filter!.setValue(color1, forKey: "inputColor0") filter!.setValue(color2, forKey: "inputColor1") let image = context.createCGImage(filter!.outputImage!, from: CGRect(x: 0, y: 0, width: size.width, height: size.height)) self.init(cgImage: image!) } }
true
63814458930cab4692273c81c6e83daac4fb8b0f
Swift
MelD8BitGamer/Podcast
/Podcast/Controllers/ViewController.swift
UTF-8
3,396
3.03125
3
[]
no_license
// // ViewController.swift // Podcast // // Created by Melinda Diaz on 12/17/19. // Copyright © 2019 Melinda Diaz. All rights reserved. // //TODO: you cannot use spaces in the search, the ALERT shows up when you type space and/or special characters. use .addingPercentEncoding with .urlHostAllowed in the with AllowedCharacters: import UIKit class ViewController: UIViewController { //the user types something eg. "R" , the userQuery is set to whatever the user inputs into the searchbar. the getPodcasts() queries the API based on the userQuery. Then it will bring up everything thats has R in it. then you set your podcastRef(variable reference) = equal to the data that the escaping closure has captured var podcastRef = [Podcast]() { didSet { DispatchQueue.main.async { self.podcastTableView.reloadData() } } } var userQuery = "" { didSet { APIClient.getPodcasts(for: userQuery) { [weak self] (result) in switch result { //we need case .failure(let appError)://dispatchqueue excutes on the main thread or background thread DispatchQueue.main.async {//anything that is a property or a method use SELF in DispatchQueue self?.showAlert(title: "Data Failure", message: "Unable to retrieve that podcast, Please do not use special characters, \(appError)")//self.so not in the 3d person } case .success(let data): self?.podcastRef = data } } } } @IBOutlet weak var podcastTableView: UITableView! @IBOutlet weak var podcastSearch: UISearchBar! override func viewDidLoad() { super.viewDidLoad() podcastTableView.dataSource = self podcastSearch.delegate = self podcastTableView.delegate = self } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { guard let indexPath = podcastTableView.indexPathForSelectedRow, let eachCellToDVC = segue.destination as? DetailViewController else { fatalError("could not segue")} let cell = podcastRef[indexPath.row] eachCellToDVC.modelReference = cell } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return podcastRef.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { guard let cell = podcastTableView.dequeueReusableCell(withIdentifier: "podcastCell", for: indexPath) as? PodcastTableViewCell else { fatalError("could not get data")} cell.podcastLabel.text = podcastRef[indexPath.row].collectionName cell.podcastNameLabel.text = podcastRef[indexPath.row].trackName //in order to access the enumeration's associated values is by using a switch statement return cell } } extension ViewController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { userQuery = searchText } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 100 } }
true
c6c1c1bbc49a71098d27a3f3eff5bf92893f5ce2
Swift
abdulshamim/TabBar
/TruckyCP/Controllers/BookingDetailsController.swift
UTF-8
2,864
2.71875
3
[]
no_license
// // BookingDetailsController.swift // TruckyCP // // Created by Abdul Shamim on 2/11/18. // Copyright © 2018 Abdul Shamim. All rights reserved. // import UIKit class BookingDetailsController: UIViewController { @IBOutlet weak var firstSelectedView: UIView! @IBOutlet weak var secondSelectedView: UIView! @IBOutlet weak var thirdSelectedView: UIView! @IBOutlet weak var fourthSelectedView: UIView! @IBOutlet weak var imageView: UIImageView! var touchCount = 0 override func viewDidLoad() { super.viewDidLoad() imageView.layer.cornerRadius = imageView.bounds.height/2 imageView.layer.masksToBounds = true navigationController?.setNavigationBarHidden(false, animated: true) self.tabBarController?.tabBar.isHidden = true } override func viewWillAppear(_ animated: Bool) { self.firstSelectedView.backgroundColor = .clear self.secondSelectedView.backgroundColor = .clear self.thirdSelectedView.backgroundColor = .clear self.fourthSelectedView.backgroundColor = .clear } override func viewWillDisappear(_ animated: Bool) { navigationController?.setNavigationBarHidden(true, animated: true) } @IBAction func firstButton(_ sender: UIButton) { print("\(sender.center.y)") let view = UIView() view.frame = CGRect(x: sender.center.x, y: sender.center.y, width: 80, height: 80) view.backgroundColor = .red view.layer.cornerRadius = view.bounds.height/2 view.layer.masksToBounds = true view.transform = CGAffineTransform(scaleX: 0.1, y: 0.1) UIView.animate(withDuration: 0.9, animations: { view.center = self.firstSelectedView.center view.transform = CGAffineTransform.identity self.view.addSubview(view) }) } @IBAction func buttonSecond(_ sender: UIButton) { let view = UIImageView() view.frame = imageView.frame view.backgroundColor = .red view.layer.cornerRadius = view.bounds.height/2 view.layer.masksToBounds = true view.image = imageView.screenshot() UIView.animate(withDuration: 0.8, animations: { self.touchCount += 1 if self.touchCount == 1 { view.center = self.firstSelectedView.center } else if self.touchCount == 2 { view.center = self.secondSelectedView.center } else if self.touchCount == 3 { view.center = self.thirdSelectedView.center } else if self.touchCount == 4 { view.center = self.fourthSelectedView.center } view.transform = CGAffineTransform(scaleX: 1.1, y: 1.1) self.view.addSubview(view) }) } }
true
3de713e6e5950717680da49466717aede19246ef
Swift
adamnemecek/HeartableGame
/Sources/HeartableGame/2d-ui/HRT2DControlKey.swift
UTF-8
509
2.53125
3
[]
no_license
// Copyright © 2019 Heartable LLC. All rights reserved. import Foundation public protocol HRT2DControlKey: HRT2DNodeKey { var defaultTextureName: String { get } var highlightedTextureName: String? { get } var selectedTextureName: String? { get } } public extension HRT2DControlKey where Self: RawRepresentable, Self.RawValue == String { var defaultTextureName: String { self.rawValue } var highlightedTextureName: String? { nil } var selectedTextureName: String? { nil } }
true
593acb22fc6d451c141c512ff9b7f64df1c7d0c4
Swift
irskep/PoweRL
/Shared/Scenes/GameScene.swift
UTF-8
3,333
2.546875
3
[]
no_license
// // GameScene.swift // LD39 // // Created by Steve Johnson on 7/15/17. // Copyright © 2017 Steve Johnson. All rights reserved. // import SpriteKit extension SKScene { func label(named: String) -> SKLabelNode? { return self.childNode(withName: "//\(named)") as? SKLabelNode } } extension CGRect { var aspectRatioPortrait: CGFloat { return height / width } var aspectRatioLandscape: CGFloat { return width / height } } class GameScene: PixelatedScene { fileprivate var label : SKLabelNode? fileprivate var spinnyNode : SKShapeNode? class func create() -> GameScene { return GameScene(fileNamed: "GameScene")! } override func motionAccept() { self.view?.presentScene(MapScene.create(), transition: SKTransition.crossFade(withDuration: 0.5)) } override func motionIndicate(point: CGPoint) { guard let startNode = self.childNode(withName: "//start") as? SKLabelNode, let helpNode = self.childNode(withName: "//help") as? SKLabelNode else { return } let point = self.convert(point, to: children.first!) if startNode.frame.contains(point) { self.motionAccept() return } else if helpNode.frame.contains(point) { self.view?.presentScene(HelpScene.create(), transition: SKTransition.crossFade(withDuration: 0.5)) } } override func setup() { super.setup() scaleMode = .aspectFit if UserDefaults.pwr_isMusicEnabled { MusicPlayer.shared.prepare(track: "loading") MusicPlayer.shared.play() } let gameName = "Power-Q" self.label(named: "logo1")?.text = gameName self.label(named: "logo2")?.text = gameName (self.childNode(withName: "//robot") as? SKSpriteNode)?.texture = Assets16.get(.player) if HighScoreModel.shared.scores.count > 0 { let highScore = HighScoreModel.shared.scores.first ?? 0 (self.childNode(withName: "//score") as? SKLabelNode)?.text = "High Score: \(highScore)" } else { (self.childNode(withName: "//score") as? SKLabelNode)?.text = "" } if self.getSaveExists(id: "continuous"), let dict = self.loadSave(id: "continuous"), let mapState = MapState(dict: dict) { self.view?.presentScene(MapScene.create(mapState: mapState), transition: SKTransition.crossFade(withDuration: 0.5)) } } override func layoutForPortrait() { super.layoutForPortrait() let isExtraSkinny = (self.view?.bounds.aspectRatioPortrait ?? 0) > 1.8 if let logo1 = self.childNode(withName: "//logo1") { logo1.setScale(isExtraSkinny ? 0.25 : 0.35) logo1.position = CGPoint(x: 0, y: 200) } if let logo2 = self.childNode(withName: "//logo2") { logo2.setScale(isExtraSkinny ? 0.25 : 0.35) logo2.position = CGPoint(x: 8, y: 200 - 8) } if let robot = self.childNode(withName: "//robot") { robot.position = CGPoint(x: 0, y: 50) robot.setScale(0.5) } if let help = self.childNode(withName: "//help") { help.position = CGPoint(x: 0, y: -100) help.setScale(0.5) } if let start = self.childNode(withName: "//start") { start.position = CGPoint(x: 0, y: start.position.y) start.setScale(0.5) if let score = self.childNode(withName: "//score") as? SKLabelNode { score.position = start.position + CGPoint(x: 0, y: -40) score.setScale(0.7) } } } }
true
a39703d3d84ae193f37d71d71985a4862575acfe
Swift
ifyoung/face-track-camera_ios
/TrackCamera-GMV/Utils/Extensions.swift
UTF-8
12,381
2.828125
3
[ "MIT", "Apache-2.0" ]
permissive
import Foundation import UIKit import CoreVideo import CoreGraphics import AVFoundation extension UIColor { public convenience init?(hexString: String) { let r, g, b: CGFloat if hexString.hasPrefix("#") { // let start = hexString.index(hexString.startIndex, offsetBy: 1) // let hexColor = hexString.substring(from: start) let hexColor = hexString.substring(fromIndex: 1) if hexColor.count == 6 { let scanner = Scanner(string: hexColor) var hexNumber: UInt64 = 0 if scanner.scanHexInt64(&hexNumber) { r = CGFloat((hexNumber & 0xff0000) >> 16) / 255//16~24 g = CGFloat((hexNumber & 0x00ff00) >> 8) / 255//8~16 b = CGFloat(hexNumber & 0x0000ff) / 255// ~8 //a = CGFloat(hexNumber & 0x000000ff) / 255 self.init(red: r, green: g, blue: b, alpha: 1.0) return } } } return nil } } extension UIColor { func toHexString() -> String { var r:CGFloat = 0 var g:CGFloat = 0 var b:CGFloat = 0 var a:CGFloat = 0 getRed(&r, green: &g, blue: &b, alpha: &a) let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0 return String(format:"#%06x", rgb) } } extension UIColor { func lighter(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: abs(percentage) ) } func darker(by percentage:CGFloat=30.0) -> UIColor? { return self.adjust(by: -1 * abs(percentage) ) } func adjust(by percentage:CGFloat=30.0) -> UIColor? { var r:CGFloat=0, g:CGFloat=0, b:CGFloat=0, a:CGFloat=0; if(self.getRed(&r, green: &g, blue: &b, alpha: &a)){ return UIColor(red: min(r + percentage/100, 1.0), green: min(g + percentage/100, 1.0), blue: min(b + percentage/100, 1.0), alpha: 1.0) }else{ return nil } } } extension CGFloat{ func fixColor()->CGFloat{ return CGFloat(Global.adjustColor(c: Int(self))) } } extension Int{ func fixColor()->CGFloat{ return CGFloat(Global.adjustColor(c: Int(self))) } } // extension CGImage{ // func pixelBuffer(forImage image:CGImage) -> CVPixelBuffer?{ // typealias CVImageBuffer = CVBuffer func getPixelBuffer(osType:OSType = kCVPixelFormatType_32BGRA) -> CVPixelBuffer?{ // CVBufferRef let frameSize = CGSize(width: self.width, height: self.height) var pixelBuffer:CVPixelBuffer? = nil let status = CVPixelBufferCreate(kCFAllocatorDefault, Int(frameSize.width), Int(frameSize.height), osType , nil, &pixelBuffer) if status != kCVReturnSuccess { return nil } CVPixelBufferLockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags.init(rawValue: 0)) /* Lock the base address of the pixel buffer We must call the CVPixelBufferLockBaseAddress(_:_:) function before accessing pixel data with the CPU, and call the CVPixelBufferUnlockBaseAddress(_:_:) function afterward. If you include the readOnly value in the lockFlags parameter when locking the buffer, you must also include it when unlocking the buffer. */ let data = CVPixelBufferGetBaseAddress(pixelBuffer!) /* return the base address of the pixel buffer retrieving the base address for a pixel buffer requires that the buffer base address be locked using the CVPixelBufferLockBaseAddress(_:_:) function. */ let rgbColorSpace = CGColorSpaceCreateDeviceRGB() let bitmapInfo = CGBitmapInfo(rawValue: CGBitmapInfo.byteOrder32Little.rawValue | CGImageAlphaInfo.premultipliedFirst.rawValue) let context = CGContext(data: data, width: Int(frameSize.width), height: Int(frameSize.height), bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer!), space: rgbColorSpace, bitmapInfo: bitmapInfo.rawValue) /* Core Graphic is also known as Quartz2D. We can know the API is based on Core Graphic framwork, so the data types and the routines that operate on them use CGprefix */ context?.draw(self, in: CGRect(x: 0, y: 0, width: self.width, height: self.height)) CVPixelBufferUnlockBaseAddress(pixelBuffer!, CVPixelBufferLockFlags(rawValue: 0)) return pixelBuffer } func pixelBuffer(width: Int, height: Int, pixelFormatType: OSType, colorSpace: CGColorSpace, alphaInfo: CGImageAlphaInfo, orientation: CGImagePropertyOrientation) -> CVPixelBuffer? { // TODO: If the orientation is not .up, then rotate the CGImage. // See also: https://stackoverflow.com/a/40438893/ assert(orientation == .up) var maybePixelBuffer: CVPixelBuffer? let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] let status = CVPixelBufferCreate(kCFAllocatorDefault, width, height, pixelFormatType, attrs as CFDictionary, &maybePixelBuffer) guard status == kCVReturnSuccess, let pixelBuffer = maybePixelBuffer else { return nil } let flags = CVPixelBufferLockFlags(rawValue: 0) guard kCVReturnSuccess == CVPixelBufferLockBaseAddress(pixelBuffer, flags) else { return nil } defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, flags) } guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer), width: width, height: height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: colorSpace, bitmapInfo: alphaInfo.rawValue) else { return nil } context.draw(self, in: CGRect(x: 0, y: 0, width: width, height: height)) return pixelBuffer } func pixelBufferEx(pixelFormatType: OSType, colorSpace: CGColorSpace, alphaInfo: CGImageAlphaInfo, orientation: CGImagePropertyOrientation) -> CVPixelBuffer? { // TODO: If the orientation is not .up, then rotate the CGImage. // See also: https://stackoverflow.com/a/40438893/ assert(orientation == .up) var maybePixelBuffer: CVPixelBuffer? let attrs = [kCVPixelBufferCGImageCompatibilityKey: kCFBooleanTrue, kCVPixelBufferCGBitmapContextCompatibilityKey: kCFBooleanTrue] let status = CVPixelBufferCreate(kCFAllocatorDefault, self.width, self.height, pixelFormatType, attrs as CFDictionary, &maybePixelBuffer) guard status == kCVReturnSuccess, let pixelBuffer = maybePixelBuffer else { return nil } let flags = CVPixelBufferLockFlags(rawValue: 0) guard kCVReturnSuccess == CVPixelBufferLockBaseAddress(pixelBuffer, flags) else { return nil } defer { CVPixelBufferUnlockBaseAddress(pixelBuffer, flags) } guard let context = CGContext(data: CVPixelBufferGetBaseAddress(pixelBuffer), width: self.width, height: self.height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pixelBuffer), space: colorSpace, bitmapInfo: alphaInfo.rawValue) else { return nil } context.draw(self, in: CGRect(x: 0, y: 0, width: self.width, height: self.height)) return pixelBuffer } } extension CMSampleBuffer { // Converts a CMSampleBuffer to a UIImage // // Return: UIImage from CMSampleBuffer func toUIImage() -> UIImage? { if let pixelBuffer = CMSampleBufferGetImageBuffer(self) { let ciImage = CIImage(cvPixelBuffer: pixelBuffer) let context = CIContext() let imageRect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer)) if let image = context.createCGImage(ciImage, from: imageRect) { return UIImage(cgImage: image, scale: 1, orientation: .right) } } return nil } // Converts a CMSampleBuffer to a CGImage // // Return: CGImage from CMSampleBuffer func toCGImage() -> CGImage? { if let pixelBuffer = CMSampleBufferGetImageBuffer(self) { let ciImage = CIImage(cvPixelBuffer: pixelBuffer) let context = CIContext() let imageRect = CGRect(x: 0, y: 0, width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer)) if let image = context.createCGImage(ciImage, from: imageRect) { return image } } return nil } // Converts a CMSampleBuffer to a CIImage // // Return: CIImage from CMSampleBuffer func toCIImage() -> CIImage? { if let pixelBuffer = CMSampleBufferGetImageBuffer(self) { return CIImage(cvPixelBuffer: pixelBuffer) } else { return nil } } } extension UIView{ // iOS清除UIDatePicker和UIPickerView中间Row上面的分割线 // //———————————————— //版权声明:本文为CSDN博主「维庆」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。 //原文链接:https://blog.csdn.net/IOS_dashen/article/details/50214407 //取出高度小于5的线,0.5 func clearSeparatorWithView(){ for subView in self.subviews { if(subView.frame.size.height < 2){ subView.isHidden = true } } } } /** @abstract UIWindow hierarchy category. */ /**获取窗体视图控制器相关拓展*/ public extension UIWindow { /** @return Returns the current Top Most ViewController in hierarchy. */ func topMostController()->UIViewController? { var topController = rootViewController while let presentedController = topController?.presentedViewController { topController = presentedController } return topController } /** @return Returns the topViewController in stack of topMostController. */ func currentViewController()->UIViewController? { var currentViewController = topMostController() while currentViewController != nil && currentViewController is UINavigationController && (currentViewController as! UINavigationController).topViewController != nil { currentViewController = (currentViewController as! UINavigationController).topViewController } return currentViewController } }
true
4c0e3dd32d1d46de8808c25c94b1ec12c1d005cf
Swift
YutoMizutani/OperantKit
/Examples/CLI/sandbox/Sources/sandbox/Enums/Experiment.swift
UTF-8
1,637
2.921875
3
[ "MIT" ]
permissive
// // Experiment.swift // CLI // // Created by Yuto Mizutani on 2018/11/13. // import OperantKit enum Experiment: Int, CaseIterable { case fixedRatio = 1 case fixedInterval case fixedTime } extension Experiment { func run() { switch self { case .fixedRatio: ExperimentFR.run() case .fixedInterval: ExperimentFI.run() case .fixedTime: ExperimentFT.run() } } private var scheduleType: ScheduleType { switch self { case .fixedRatio: return .fixedRatio case .fixedInterval: return .fixedInterval case .fixedTime: return .fixedTime } } var shortName: String { return self.scheduleType.shortName } var longName: String { return self.scheduleType.longName } static func availables() -> String { let prefix = """ +--------+-------------------+ | Available experiments | +--------+-------------------+ | Number | Experiment Title | +--------+-------------------+\n """ var content = "" Experiment.allCases.forEach { content += """ | \($0.rawValue)\(String(repeating: " ", count: 6 - "\($0.rawValue)".count)) | \($0.shortName)\(String(repeating: " ", count: 16 - "\($0.shortName)".count)) |\n """ } let suffix = """ | | | | 0 | cancel | +--------+-------------------+ """ return prefix + content + suffix } }
true
78fc9c33df6f13a1287a11a0fd8f8079d34cf808
Swift
jameshurst/CombineWaiting
/Sources/CombineWaiting/WaitResultError.swift
UTF-8
290
2.625
3
[ "MIT", "LicenseRef-scancode-unknown-license-reference" ]
permissive
/// Errors that can occur during wait result operations. public enum WaitResultError: Error { /// A failure was expected but a partial or complete result was found instead. case noFailure /// An unexpected number of values was produced. case unexpectedNumberOfValues(Int) }
true
7eae75897d53c0baa53fb8055e2ccf818eec65c0
Swift
sombali/RomanWalkApp
/RomanWalk/RomanWalk/ViewController/MapViewController/MapViewControllerDelegate.swift
UTF-8
1,626
2.609375
3
[ "Apache-2.0" ]
permissive
// // MapViewControllerDelegate.swift // RomanWalk // // Created by Somogyi Balázs on 2020. 04. 12.. // Copyright © 2020. Somogyi Balázs. All rights reserved. // import Foundation import MapKit class MapViewControllerDelegate: NSObject, MKMapViewDelegate { func mapView(_ mapView: MKMapView, annotationView view: MKAnnotationView, calloutAccessoryControlTapped control: UIControl) { guard let coordinate = view.annotation?.coordinate else { return } let geoCoder = CLGeocoder() let location = CLLocation(latitude: coordinate.latitude, longitude: coordinate.longitude) geoCoder.reverseGeocodeLocation(location) { (placemarks, error) in if let error = error { print("Error while reverse geocoding: \(error.localizedDescription)") } guard let placemarks = placemarks, placemarks.count != 0 else { return } let clPlacemark = placemarks.first! let placemark = MKPlacemark(placemark: clPlacemark) let mapItem = MKMapItem(placemark: placemark) mapItem.name = view.annotation?.title! var mapItems = [MKMapItem]() mapItems.append(MKMapItem.forCurrentLocation()) mapItems.append(mapItem) let launchOptions: [String: Any] = [ MKLaunchOptionsMapTypeKey: MKMapType.standard.rawValue, MKLaunchOptionsDirectionsModeKey: MKLaunchOptionsDirectionsModeDefault ] MKMapItem.openMaps(with: mapItems, launchOptions: launchOptions) } } }
true
5d3892ec70bc3a0c8d88221325cf9fe780b4324c
Swift
phamtuandev/MVP-Template-iOS
/mvp-template-ios/Common/Base/BaseVC.swift
UTF-8
1,534
2.53125
3
[ "MIT" ]
permissive
// // Created by eugene on 12.08.18. // Copyright (c) 2018 omisoft. All rights reserved. // import Foundation import UIKit class BaseVC<P>: UIViewController, RoutableScreen { var context: RouteContext? var presenter: P? var router: Router { return Router(viewController: self) } override func viewDidLoad() { super.viewDidLoad() setupStyle() initPresenter(with: context) } func initPresenter(with context: RouteContext?) { fatalError("Subclasses must implement initPresenter()") } func setupStyle() { setNeedsStatusBarAppearanceUpdate() } override var preferredStatusBarStyle : UIStatusBarStyle { return .lightContent } } extension BaseVC: MvpView { func openScreen(_ screen: Screen, fromStoryboard storyboard: Storyboard, withContext context: RouteContext? = nil) { Router(viewController: self) .openScreen(screen, fromStoryboard: storyboard, isChildScreen: false, withContext: context) } func openChildScreen(_ screen: Screen, fromStoryboard storyboard: Storyboard, withContext context: RouteContext? = nil) { Router(viewController: self) .openScreen(screen, fromStoryboard: storyboard, isChildScreen: true, withContext: context) } func backToPrevScreen(with context: RouteContext? = nil) { Router(viewController: self).backToPrevScreen(with: context) } }
true
dd2027f563f0f9f43ca4357b3a1c3b83516ec905
Swift
DisasterHacks/SupportChain-iOS
/disaster_ios/samplr/APIKit/APIKitSampleController.swift
UTF-8
1,318
3.125
3
[]
no_license
// // APIKitSampleController.swift // disaster_ios // // Created by WKC on 2017/01/20. // Copyright © 2017年 WKC. All rights reserved. // import Foundation import APIKit protocol PersonRequest:Request{ } extension PersonRequest{ var baseURL:URL{ return URL(string:"http://153.120.62.197/cruster/person.php")! } } struct PersonAPI{ typealias Parameters = [String:Any?] } //エンドポイント単位の実装 extension PersonAPI{ indirect enum PersonEnum:PersonRequest{ case all() case get(id:Int) var path: String { switch self { case .all: return "/all" case .get(let id): return "" } } var method: HTTPMethod { switch self { case .all: return .get case .get: return .get } } var parameters: Any? { switch self { case .all: return [:] case .get: return [:] } } func response(from object: Any, urlResponse: HTTPURLResponse) throws -> Person { //return try response(from: object, urlResponse: urlResponse) print("object=>\(object)") return try! Person.decodeValue(object) } } }
true
09f3d41e943d36828cc1c7b252bc141ca49a906e
Swift
zyzhangyu/ZYSwiftUI
/SwiftUI4/SwiftUI4/CalculatorButtonRow.swift
UTF-8
958
3.109375
3
[]
no_license
// // CalculatorButtonRow.swift // SwiftUI4 // // Created by developer on 2020/9/16. // Copyright © 2020 developer. All rights reserved. // import SwiftUI struct CalculatorButtonRow: View { let row : [CalculatorButtonItem] @EnvironmentObject var model:CalculatorModel var body: some View { HStack { ForEach(row, id:\.self){ item in CalculatorButton( title: item.title, size: item.size, backgroundColorName: item.backgroundColorName) { print("Button: \(item.title)") self.model.apply(item) } } } } } //struct CalculatorButtonRow_Previews: PreviewProvider { // static var previews: some View { // CalculatorButtonRow.init(row: [ // .digit(1), .digit(2), .digit(3), .op(.plus) // ], brain: brain) // // } //}
true
9ea4cd580db32c99f369be80b70bd3611a77f243
Swift
Pierre46/DisneyComics
/Disney/Managers/ComicsManager.swift
UTF-8
908
2.890625
3
[]
no_license
// // ComicsManager.swift // Disney // // Created by Pierre Moreau on 7/25/21. // import UIKit class ComicsManager { var service = MarvelService() func retreiveComic(id: Int, successCompletion: @escaping (Comic) -> (), errorCompletion: @escaping (MarvelError) -> ()) { service.retreiveContent(path: "comics/\(id)", successCompletion: { (response: ComicResponse) in guard let comic = response.data.results.first else { errorCompletion(.generic) return } successCompletion(comic) }, errorCompletion: errorCompletion) } } private struct ComicResponse: Decodable { var data: DataResponse } private struct DataResponse: Decodable { var results: [Comic] }
true
b629a9243c8f48518953f5fbf9978f2c48cd9d8d
Swift
segabor/swift-sh
/Sources/Script.swift
UTF-8
3,518
2.671875
3
[ "Unlicense" ]
permissive
import Foundation public class Script { let name: String let deps: [ImportSpecification] let script: String var path: Path { #if os(macOS) return Path.home/"Library/Developer/swift-sh.cache"/name #else if let path = ProcessInfo.processInfo.environment["XDG_CACHE_HOME"] { return Path.root/path/"swift-sh" } else { return Path.home/".cache/swift-sh" } #endif } public init(name: String, contents: [String], dependencies: [ImportSpecification]) { self.name = name script = contents.joined(separator: "\n") deps = dependencies } var shouldWriteFiles: Bool { return (try? String(contentsOf: path/"main.swift")) != script } func write() throws { //TODO we only support Swift 4.2 basically //TODO dependency module names can be anything so we need to parse Package.swifts for all deps to get module lists var importNames: String { return deps.map { """ "\($0.importName)" """ }.joined(separator: ", ") } try path.mkpath() try """ // swift-tools-version:4.2 import PackageDescription let pkg = Package(name: "\(name)") pkg.products = [ .executable(name: "\(name)", targets: ["\(name)"]) ] pkg.dependencies = [ \(deps.map{ $0.packageLine }.joined(separator: ",\n ")) ] pkg.targets = [ .target(name: "\(name)", dependencies: [ \(importNames) ], path: ".", sources: ["main.swift"]) ] """.write(to: path/"Package.swift") try script.write(to: path/"main.swift") } public func run() throws { if shouldWriteFiles { // don‘t write `main.swift` if would be identical // ∵ prevents swift-build recognizing a null-build // ie. prevents unecessary rebuild of our script try write() } let task = Process() task.launchPath = "/usr/bin/swift" task.arguments = ["run"] task.currentDirectoryPath = path.string try task.go() task.waitUntilExit() } } private extension ImportSpecification { var packageLine: String { var requirement: String { switch constraint { case .upToNextMajor(from: let v): return """ .upToNextMajor(from: "\(v)") """ case .exact(let v): return ".exactItem(Version(\(v.major),\(v.minor),\(v.patch)))" case .ref(let ref): return """ .revision("\(ref)") """ } } let urlstr: String if let url = URL(string: dependencyName), url.scheme != nil { urlstr = dependencyName } else { urlstr = "https://github.com/\(dependencyName).git" } return """ .package(url: "\(urlstr)", \(requirement)) """ } } private extension Process { func go() throws { #if os(Linux) // I don’t get why `run` is not available, the GitHub sources have it launch() #else if #available(OSX 10.13, *) { try run() } else { launch() } #endif } }
true
091c7ab544bc3a641261419a809ce2a9876ae9a0
Swift
jlheriniaina/BreakPoint
/BreakPoint/Model/User.swift
UTF-8
589
2.859375
3
[]
no_license
// // User.swift // BreakPoint // // Created by lucas on 21/01/2019. // Copyright © 2019 lucas. All rights reserved. // import Foundation import UIKit class User { private var _id: String! private var _emeil: String! private var _avatar: UIImage! var avatar : UIImage { return _avatar } var id: String { return _id } var email: String { return _emeil } init(id: String, email: String, avatar: UIImage) { self._id = id self._emeil = email self._avatar = avatar } }
true
ad2efa00e941f8deb7032d76ce402b0aab963ab8
Swift
hungle-wumbo/iOS_Started_Kit
/Sources/Scenes/Home/HomeAssembler.swift
UTF-8
1,356
2.546875
3
[ "MIT" ]
permissive
// // HomeAssembler.swift // My Project // // Created by Manh Pham on 3/12/20. // Copyright © 2020 Fujitech. All rights reserved. // import UIKit protocol HomeAssembler { func resolve(navigationController: BaseNavigationController) -> HomeViewController func resolve(navigationController: BaseNavigationController) -> HomeViewModel func resolve(navigationController: BaseNavigationController) -> HomeNavigatorType func resolve() -> HomeUseCaseType } extension HomeAssembler { func resolve(navigationController: BaseNavigationController) -> HomeViewController { let vc = HomeViewController.instantiate() let vm: HomeViewModel = resolve(navigationController: navigationController) vc.bindViewModel(to: vm) return vc } func resolve(navigationController: BaseNavigationController) -> HomeViewModel { return HomeViewModel( navigator: resolve(navigationController: navigationController), useCase: resolve() ) } } extension HomeAssembler where Self: DefaultAssembler { func resolve(navigationController: BaseNavigationController) -> HomeNavigatorType { return HomeNavigator(assembler: self, navigationController: navigationController) } func resolve() -> HomeUseCaseType { return HomeUseCase(repository: resolve()) } }
true
a46d48d46c125beff9d2079215b34f606b0111a7
Swift
Soneso/stellar-ios-mac-sdk
/stellarsdk/stellarsdkTests/kyc/GetCustomerResponseMock.swift
UTF-8
4,129
2.6875
3
[ "LicenseRef-scancode-generic-cla", "Apache-2.0" ]
permissive
// // File.swift // stellarsdk // // Created by Christian Rogobete on 31.05.23. // Copyright © 2023 Soneso. All rights reserved. // import Foundation class GetCustomerResponseMock: ResponsesMock { var address: String init(address:String) { self.address = address super.init() } override func requestMock() -> RequestMock { let handler: MockHandler = { [weak self] mock, request in let jwt = request.allHTTPHeaderFields?["Authorization"]; if jwt == "Bearer accepted_jwt" { mock.statusCode = 202 return self?.accepted } else if jwt == "Bearer some_info_jwt" { mock.statusCode = 200 return self?.someInfo } else if jwt == "Bearer 404_jwt" { mock.statusCode = 404 return self?.notFoundError } else if jwt == "Bearer 400_jwt" { mock.statusCode = 400 return self?.otherError } else { mock.statusCode = 401 // unauthorized } return nil } return RequestMock(host: address, path: "/customer", httpMethod: "GET", mockHandler: handler) } // The case when a customer has been successfully KYC'd and approved let accepted = """ { "id": "d1ce2f48-3ff1-495d-9240-7a50d806cfed", "status": "ACCEPTED", "provided_fields": { "first_name": { "description": "The customer's first name", "type": "string", "status": "ACCEPTED" }, "last_name": { "description": "The customer's last name", "type": "string", "status": "ACCEPTED" }, "email_address": { "description": "The customer's email address", "type": "string", "status": "ACCEPTED" } } } """ // The case when a customer has provided some but not all required information let someInfo = """ { "id": "d1ce2f48-3ff1-495d-9240-7a50d806cfed", "status": "NEEDS_INFO", "fields": { "mobile_number": { "description": "phone number of the customer", "type": "string" }, "email_address": { "description": "email address of the customer", "type": "string", "optional": true } }, "provided_fields": { "first_name": { "description": "The customer's first name", "type": "string", "status": "ACCEPTED" }, "last_name": { "description": "The customer's last name", "type": "string", "status": "ACCEPTED" } } } """ // The case when an anchor requires info about an unknown customer let unknownCustomer = """ { "id": "d1ce2f48-3ff1-495d-9240-7a50d806cfed", "status": "NEEDS_INFO", "fields": { "mobile_number": { "description": "phone number of the customer", "type": "string" }, "email_address": { "description": "email address of the customer", "type": "string", "optional": true } }, "provided_fields": { "first_name": { "description": "The customer's first name", "type": "string", "status": "ACCEPTED" }, "last_name": { "description": "The customer's last name", "type": "string", "status": "ACCEPTED" } } } """ let notFoundError = """ { "error": "customer not found for id: 7e285e7d-d984-412c-97bc-909d0e399fbf" } """ let otherError = """ { "error": "unrecognized 'type' value. see valid values in the /info response" } """ }
true
9bf8ac2a5f9168a06203b0dbda9f685e06457d98
Swift
nikolajjensen/SunCalc
/Sources/SunCalc/Utils/Vector.swift
UTF-8
7,983
3.21875
3
[ "Apache-2.0" ]
permissive
// // Vector.swift // Vector // // Copyright © 2021 Nikolaj Banke Jensen // // NOTICE: This file has been modified under compliance with the Apache 2.0 License // from the original work of Richard "Shred" Körber. This file has been modified // by translation from Java to Swift, including appropriate refactoring and adaptation. // // The original work can be found here: https://github.com/shred/commons-suncalc // // -------------------------------------------------------------------------------- // // Copyright (C) 2017 Richard "Shred" Körber // http://commons.shredzone.org // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. // import Foundation /// A three dimensional Vector. struct Vector: Equatable, CustomStringConvertible { /// The cartesian x coordinate. let x: Double /// The cartesian x coordinate. let y: Double /// The cartesian x coordinate. let z: Double /// The polar representation of the Vector. private var polar: Polar! /// Description of the Vector structure. public var description: String { return "(x=\(x), y=\(y), z=\(z))" } /// Constructs a new Vector of the given cartesian coordinates. /// - Parameters: /// - x: X coordinate. /// - y: Y coordinate. /// - x: Z coordinate. init(_ x: Double, _ y: Double, _ z: Double) { self.x = x self.y = y self.z = z self.polar = Polar(self) } /// Attempts to construct a new Vector of the given cartesian coordinates. /// - Parameters: /// - d: Array of coordinates, must have 3 elements. init(_ d: [Double]) throws { if d.count != 3 { throw SunCalcError.illegalArgumentError("Invalid vector length") } self.x = d[0] self.y = d[1] self.z = d[2] self.polar = Polar(self) } /// Creates a new Vector of the given polar coordinates, with a radial distance of 1. /// - Parameters: /// - φ: Azimuthal angle. /// - θ: Polar angle. /// - Returns: The created Vector. static func ofPolar(_ φ: Double, _ θ: Double) -> Vector { return ofPolar(φ, θ, 1.0) } /// Creates a new Vector of the given polar coordinates. /// - Parameters: /// - φ: Azimuthal angle. /// - θ: Polar angle. /// - r: Radial distance. /// - Returns: The created Vector. static func ofPolar(_ φ: Double, _ θ: Double, _ r: Double) -> Vector { let cosθ = cos(θ) var result: Vector = Vector( r * cos(φ) * cosθ, r * sin(φ) * cosθ, r * sin(θ)) result.polar.setPolar(φ, θ, r) return result } /// Returns the azimuthal angle angle (φ) in radians. mutating func getPhi() -> Double { return polar.getPhi() } /// Returns the polar angle (θ) in radians. mutating func getTheta() -> Double { return polar.getTheta() } /// Returns the radial distance (r). mutating func getR() -> Double { return polar.getR() } /// Returns a Vector that is the sum of this Vector and the given Vector. /// - Parameter vec: The Vector to add. /// - Returns: Resulting Vector. func add(_ vec: Vector) -> Vector { return Vector( x + vec.x, y + vec.y, z + vec.z) } /// Returns a Vector that is the difference of this Vector and the given Vector. /// - Parameter vec: The Vector to subtract. /// - Returns: Resulting Vector. func subtract(_ vec: Vector) -> Vector { return Vector( x - vec.x, y - vec.y, z - vec.z) } /// Returns a Vector that is the product of this Vector and the given Vector. /// - Parameter vec: The Vector to multiply. /// - Returns: Resulting Vector. func multiply(_ vec: Vector) -> Vector { return Vector( x * vec.x, y * vec.y, z * vec.z) } /// Returns a negtion of this Vector. /// - Returns: Resulting Vector. func negate() -> Vector { return Vector( -x, -y, -z) } /// Returns a Vector that is the cross product of this Vector and the given Vector. /// - Parameter vec: The Vector to multiply. /// - Returns: Resulting Vector. func cross(_ right: Vector) -> Vector { return Vector( y * right.z - z * right.y, z * right.x - x * right.z, x * right.y - y * right.x) } /// Returns the dot product of this Vector and the given Vector. /// - Parameter vec: The Vector to multiply. /// - Returns: Resulting dot product. func dot(_ right: Vector) -> Double { return x * right.x + y * right.y + z * right.z } /// Returns the norm of this Vector. /// - Returns: Norm of this vector. func norm() -> Double { return sqrt(dot(self)) } /// Checks if two Vectors are equal (have equal elements). static func == (lhs: Vector, rhs: Vector) -> Bool { return lhs.x == rhs.x && lhs.y == rhs.y && lhs.z == rhs.z } /// Helper class for lazily computing the polar coordinates in a Vector. private struct Polar { /// Azimuthal angle. private var φ: Double? /// Polar angle. private var θ: Double? /// Radial distance. private var r: Double? /// X coordinate of the accompanying Vector private let x: Double /// Y coordinate of the accompanying Vector private let y: Double /// Z coordinate of the accompanying Vector private let z: Double init(_ vector: Vector) { self.x = vector.x self.y = vector.y self.z = vector.z } /// Sets the polar coordinates. /// - Parameters: /// - φ: Azimuthal angle. /// - θ: Polar angle. /// - r: Radial distance. mutating func setPolar(_ φ: Double, _ θ: Double, _ r: Double) { self.φ = φ self.θ = θ self.r = r } /// Returns the azimuthal angle (φ) in radians. mutating func getPhi() -> Double { guard let φUnwrapped = φ else { if ExtendedMath.isZero(x) && ExtendedMath.isZero(y) { φ = 0.0 } else { φ = atan2(y, x) } if φ! < 0.0 { φ! += ExtendedMath.pi2 } return φ! } return φUnwrapped } /// Returns the polar angle (θ) in radians. mutating func getTheta() -> Double { guard let θUnwrapped = θ else { let pSqr = x * x + y * y if ExtendedMath.isZero(z) && ExtendedMath.isZero(pSqr) { θ = 0.0 } else { θ = atan2(z, sqrt(pSqr)) } return θ! } return θUnwrapped } /// Returns the radial distance. mutating func getR() -> Double { guard let rUnwrapped = r else { r = sqrt(x * x + y * y + z * z) return r! } return rUnwrapped } } }
true
284e58651ad5db2d4e7004de5d99e5a2ed737e3d
Swift
raphaelhanneken/lexerkit
/LexerKit/LexerKit/IntegerToken.swift
UTF-8
415
3.0625
3
[ "MIT" ]
permissive
// // IntegerToken.swift // LexerKit // // Created by Raphael Hanneken on 31/10/15. // Copyright © 2015 Raphael Hanneken. All rights reserved. // import Foundation public class IntegerToken : Token { internal var val: Int! public init?(number: String) { super.init(named: "Integer", forCharacters: number) guard let num = Int(number) else { return } self.val = num } }
true
71cdf84532e7be3d8b63f201acb4be67247041ab
Swift
mnobelsh/Husb
/Husb/Utils/Helpers/MessageKit/CustomViews/ImageViewerMessageView.swift
UTF-8
2,307
2.609375
3
[]
no_license
// // ImageViewerMessageView.swift // Husb // // Created by Muhammad Nobel Shidqi on 10/07/21. // import UIKit import SwiftMessages class ImageViewerMessageView: MessageView { // MARK: - SubViews lazy var customTitleLabel: UILabel = { let label = UILabel() label.text = "Challenge Title" label.font = UIFont.boldSystemFont(ofSize: 25) label.adjustsFontSizeToFitWidth = true label.minimumScaleFactor = 0.6 label.textColor = .pearlWhite label.numberOfLines = 0 return label }() lazy var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit imageView.layer.cornerRadius = 20 imageView.clipsToBounds = true return imageView }() override init(frame: CGRect) { super.init(frame: frame) self.setupUI() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func setupUI() { self.addSubview(self.customTitleLabel) self.addSubview(self.imageView) let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.onBackgroundViewDidTap(_:))) tapGesture.cancelsTouchesInView = false self.backgroundView.isUserInteractionEnabled = true self.backgroundView.addGestureRecognizer(tapGesture) self.imageView.snp.makeConstraints { make in make.leading.equalToSuperview().offset(35) make.trailing.equalToSuperview().offset(-35) make.centerY.equalToSuperview() make.height.equalToSuperview().multipliedBy(0.6) } self.customTitleLabel.snp.makeConstraints { make in make.leading.equalToSuperview().offset(35) make.trailing.equalToSuperview().offset(-35) make.bottom.equalTo(self.imageView.snp.top).offset(-5) make.height.equalTo(50) } } func fill(image: UIImage?, imageTitle: String) { self.customTitleLabel.text = imageTitle self.imageView.image = image } @objc private func onBackgroundViewDidTap(_ sender: UITapGestureRecognizer) { MessageKit.hide(id: self.id) } }
true
1b7052aa9d51e462d31b0a9e8c4c946c8074d356
Swift
serhii-prikhodko/instagram-like-feed
/instagram-like-feed-app/FeedModule/Presenter/PostCellPresenter.swift
UTF-8
1,294
2.890625
3
[]
no_license
// // PostCellPresenter.swift // instagram-like-feed-app // // Created by Serhiy Prikhodko on 27.06.2020. // Copyright © 2020 Serhiy Prikhodko. All rights reserved. // import Foundation protocol PostCellProtocol: class { func getImage(post: Post?) } protocol PostCellPresenterProtocol: class { init(view: PostCellProtocol, networkService: NetworkServiceProtocol, post: Post?) func getImage() } class PostCellPresenter: PostCellPresenterProtocol { weak var view: PostCellProtocol? private let networkService: NetworkServiceProtocol weak private var postCellDelegate: PostCellPresenterProtocol? var post: Post? var imageData: Data? required init(view: PostCellProtocol, networkService: NetworkServiceProtocol, post: Post?) { self.view = view self.networkService = networkService self.post = post self.getImage() } func getImage() { self.view?.getImage(post: self.post) if let post = post { self.networkService.fetchPostImage(post: post) { (data: Data?) in if let data = data { DispatchQueue.main.async { [weak self] in self?.imageData = data } } } } } }
true
f0d823c5ebe60bd2c90dc3a8fc32952313c38fef
Swift
ashfurrow/Unbox
/Unbox.swift
UTF-8
17,907
3.171875
3
[ "MIT" ]
permissive
/** * Unbox - the easy to use Swift JSON decoder * * For usage, see documentation of the classes/symbols listed in this file, as well * as the guide available at: github.com/johnsundell/unbox * * Copyright (c) 2015 John Sundell. Licensed under the MIT license, as follows: * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in all * copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. */ import Foundation /// Type alias defining what type of Dictionary that is Unboxable (valid JSON) public typealias UnboxableDictionary = [String : AnyObject] // MARK: - Main Unbox functions /** * Unbox (decode) a dictionary into a model * * @param dictionary The dictionary to decode. Must be a valid JSON dictionary. * @param context Any contextual object that should be available during unboxing. * * @discussion This function gets its return type from the context in which it's called. * If the context is ambigious, you need to supply it, like: * * `let unboxed: MyUnboxable? = Unbox(dictionary)` * * @return A model of type `T` or `nil` if an error was occured. If you wish to know more * about any error, use: `Unbox(dictionary, logErrors: true)` */ public func Unbox<T: Unboxable>(dictionary: UnboxableDictionary, context: AnyObject? = nil) -> T? { do { let unboxed: T = try UnboxOrThrow(dictionary, context: context) return unboxed } catch { return nil } } /** * Unbox (decode) a set of data into a model * * @param data The data to decode. Must be convertible into a valid JSON dictionary. * @param context Any contextual object that should be available during unboxing. * * @discussion See the documentation for the main Unbox(dictionary:) function above for more information. */ public func Unbox<T: Unboxable>(data: NSData, context: AnyObject? = nil) -> T? { do { let unboxed: T = try UnboxOrThrow(data, context: context) return unboxed } catch { return nil } } // MARK: - Unbox functions with error handling /** * Unbox (decode) a dictionary into a model, or throw an UnboxError if the operation failed * * @param dictionary The dictionary to decode. Must be a valid JSON dictionary. * @param context Any contextual object that should be available during unboxing. * * @discussion This function throws an UnboxError if the supplied dictionary couldn't be decoded * for any reason. See the documentation for the main Unbox() function above for more information. */ public func UnboxOrThrow<T: Unboxable>(dictionary: UnboxableDictionary, context: AnyObject? = nil) throws -> T { let unboxer = Unboxer(dictionary: dictionary, context: context) let unboxed = T(unboxer: unboxer) if let failureInfo = unboxer.failureInfo { if let failedValue: AnyObject = failureInfo.value { throw UnboxError.InvalidValue(failureInfo.key, "\(failedValue)") } throw UnboxError.MissingKey(failureInfo.key) } return unboxed } /** * Unbox (decode) a set of data into a model, or throw an UnboxError if the operation failed * * @param data The data to decode. Must be convertible into a valid JSON dictionary. * @param context Any contextual object that should be available during unboxing. * * @discussion This function throws an UnboxError if the supplied data couldn't be decoded for * any reason. See the documentation for the main Unbox() function above for more information. */ public func UnboxOrThrow<T: Unboxable>(data: NSData, context: AnyObject? = nil) throws -> T { if let dictionary = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? UnboxableDictionary { return try UnboxOrThrow(dictionary) } throw UnboxError.InvalidDictionary } // MARK: - Error type /// Enum describing errors that can occur during unboxing. Use the throwing functions to receive any errors. public enum UnboxError: ErrorType, CustomStringConvertible { public var description: String { let baseDescription = "[Unbox error] " switch self { case .MissingKey(let key): return baseDescription + "Missing key (\(key))" case .InvalidValue(let key, let valueDescription): return baseDescription + "Invalid value (\(valueDescription)) for key (\(key))" case .InvalidDictionary: return "Invalid dictionary" } } /// Thrown when a required key was missing in an unboxed dictionary. Contains the missing key. case MissingKey(String) /// Thrown when a required key contained an invalid value in an unboxed dictionary. Contains the invalid /// key and a description of the invalid data. case InvalidValue(String, String) /// Thrown when an unboxed dictionary was either missing or contained invalid data case InvalidDictionary } // MARK: - Protocols /// Protocol used to declare a model as being Unboxable, for use with the Unbox() function public protocol Unboxable { /// Initialize an instance of this model by unboxing a dictionary using an Unboxer init(unboxer: Unboxer) } /// Protocol used to enable a raw type for Unboxing. See default implementations further down. public protocol UnboxableRawType { /// The value to use for required properties if unboxing failed. This value will never be returned to the API user. static func fallbackValue() -> Self } /// Protocol used to declare a model as being Unboxable by using a transformer public protocol UnboxableByTransform { /// The transformer type to use. See UnboxTransformer for more information. typealias UnboxTransformerType: UnboxTransformer } /// Protocol for objects that can act as Unboxing transformers, turning an unboxed value into its final form public protocol UnboxTransformer { /// The raw unboxed type this transformer accepts as input typealias RawType /// The transformed type this transformer outputs typealias TransformedType /// Attempt to transformed an unboxed value, returning non-`nil` if successful static func transformUnboxedValue(unboxedValue: RawType) -> TransformedType? /// The value to use for required properties if unboxing or transformation failed. This value will never be returned to the API user. static func fallbackValue() -> TransformedType } // MARK: - Raw types /// Protocol making Bool an Unboxable raw type extension Bool: UnboxableRawType { public static func fallbackValue() -> Bool { return false } } /// Protocol making Int an Unboxable raw type extension Int: UnboxableRawType { public static func fallbackValue() -> Int { return 0 } } /// Protocol making Double an Unboxable raw type extension Double: UnboxableRawType { public static func fallbackValue() -> Double { return 0 } } /// Protocol making Float an Unboxable raw type extension Float: UnboxableRawType { public static func fallbackValue() -> Float { return 0 } } /// Protocol making String an Unboxable raw type extension String: UnboxableRawType { public static func fallbackValue() -> String { return "" } } // MARK: - Default transformers /// A transformer that is used to transform Strings into `NSURL` instances public class UnboxURLTransformer: UnboxTransformer { public typealias RawType = String public typealias TransformedType = NSURL public static func transformUnboxedValue(unboxedValue: RawType) -> TransformedType? { return NSURL(string: unboxedValue) } public static func fallbackValue() -> TransformedType { return NSURL() } } /// Protocol making NSURL Unboxable by transform extension NSURL: UnboxableByTransform { public typealias UnboxTransformerType = UnboxURLTransformer } // MARK: - Unboxer /** * Class used to Unbox (decode) values from a dictionary * * For each supported type, simply call `unbox(key)` and the correct type will be returned. If a required (non-optional) * value couldn't be unboxed, the Unboxer will be marked as failed, and a `nil` value will be returned from the `Unbox()` * function that triggered the Unboxer. * * An Unboxer may also be manually failed, by using the `failForKey()` or `failForInvalidValue(forKey:)` APIs. */ public class Unboxer { /// Whether the Unboxer has failed, and a `nil` value will be returned from the `Unbox()` function that triggered it. public var hasFailed: Bool { return self.failureInfo != nil } /// Any contextual object that was supplied when unboxing was started public let context: AnyObject? private var failureInfo: (key: String, value: AnyObject?)? private let dictionary: UnboxableDictionary // MARK: - Private initializer private init(dictionary: UnboxableDictionary, context: AnyObject?) { self.dictionary = dictionary self.context = context } // MARK: - Public API /// Unbox a required raw type public func unbox<T: UnboxableRawType>(key: String) -> T { return UnboxValueResolver<T>(self).resolveRequiredValueForKey(key, fallbackValue: T.fallbackValue()) } /// Unbox an optional raw type public func unbox<T: UnboxableRawType>(key: String) -> T? { return UnboxValueResolver<T>(self).resolveOptionalValueForKey(key) } /// Unbox a required Array public func unbox<T>(key: String) -> [T] { return UnboxValueResolver<[T]>(self).resolveRequiredValueForKey(key, fallbackValue: []) } /// Unbox an optional Array public func unbox<T>(key: String) -> [T]? { return UnboxValueResolver<[T]>(self).resolveOptionalValueForKey(key) } /// Unbox a required Dictionary public func unbox<T>(key: String) -> [String : T] { return UnboxValueResolver<[String : T]>(self).resolveRequiredValueForKey(key, fallbackValue: [:]) } /// Unbox an optional Dictionary public func unbox<T>(key: String) -> [String : T]? { return UnboxValueResolver<[String : T]>(self).resolveOptionalValueForKey(key) } /// Unbox a required nested Unboxable, by unboxing a Dictionary and then using a transform public func unbox<T: Unboxable>(key: String) -> T { return UnboxValueResolver<UnboxableDictionary>(self).resolveRequiredValueForKey(key, fallbackValue: T(unboxer: self), transform: { return Unbox($0, context: self.context) }) } /// Unbox an optional nested Unboxable, by unboxing a Dictionary and then using a transform public func unbox<T: Unboxable>(key: String) -> T? { return UnboxValueResolver<UnboxableDictionary>(self).resolveOptionalValueForKey(key, transform: { return Unbox($0, context: self.context) }) } /// Unbox a required Array of nested Unboxables, by unboxing an Array of Dictionaries and then using a transform public func unbox<T: Unboxable>(key: String) -> [T] { return UnboxValueResolver<[UnboxableDictionary]>(self).resolveRequiredValueForKey(key, fallbackValue: [], transform: { return self.transformUnboxableDictionaryArray($0, forKey: key, required: true) }) } /// Unbox an optional Array of nested Unboxables, by unboxing an Array of Dictionaries and then using a transform public func unbox<T: Unboxable>(key: String) -> [T]? { return UnboxValueResolver<[UnboxableDictionary]>(self).resolveOptionalValueForKey(key, transform: { return self.transformUnboxableDictionaryArray($0, forKey: key, required: false) }) } /// Unbox a required Dictionary of nested Unboxables, by unboxing an Dictionary of Dictionaries and then using a transform public func unbox<T: Unboxable>(key: String) -> [String : T] { return UnboxValueResolver<UnboxableDictionary>(self).resolveRequiredValueForKey(key, fallbackValue: [:], transform: { return self.transformUnboxableDictionaryDictionary($0, required: true) }) } /// Unbox an optional Dictionary of nested Unboxables, by unboxing an Dictionary of Dictionaries and then using a transform public func unbox<T: Unboxable>(key: String) -> [String : T]? { return UnboxValueResolver<UnboxableDictionary>(self).resolveOptionalValueForKey(key, transform: { return self.transformUnboxableDictionaryDictionary($0, required: false) }) } /// Unbox a required value that can be transformed into its final form. Usable for types that have an `UnboxTransformer` public func unbox<T: UnboxableByTransform where T == T.UnboxTransformerType.TransformedType>(key: String) -> T { return UnboxValueResolver<T.UnboxTransformerType.RawType>(self).resolveRequiredValueForKey(key, fallbackValue: T.UnboxTransformerType.fallbackValue(), transform: { return T.UnboxTransformerType.transformUnboxedValue($0) }) } /// Unbox an optional value that can be transformed into its final form. Usable for types that have an `UnboxTransformer` public func unbox<T: UnboxableByTransform where T == T.UnboxTransformerType.TransformedType>(key: String) -> T.UnboxTransformerType.TransformedType? { return UnboxValueResolver<T.UnboxTransformerType.RawType>(self).resolveOptionalValueForKey(key, transform: { return T.UnboxTransformerType.transformUnboxedValue($0) }) } /// Return a required contextual object of type `T` attached to this Unboxer, or cause the Unboxer to fail (using a dummy fallback value) public func requiredContextWithFallbackValue<T>(@autoclosure fallbackValue: () -> T) -> T { if let context = self.context as? T { return context } self.failForInvalidValue(self.context, forKey: "Unboxer.Context") return fallbackValue() } /// Make this Unboxer to fail for a certain key. This will cause the `Unbox()` function that triggered this Unboxer to return `nil`. public func failForKey(key: String) { self.failForInvalidValue(nil, forKey: key) } /// Make this Unboxer to fail for a certain key and invalid value. This will cause the `Unbox()` function that triggered this Unboxer to return `nil`. public func failForInvalidValue(invalidValue: AnyObject?, forKey key: String) { self.failureInfo = (key, invalidValue) } // MARK: - Private utilities private func transformUnboxableDictionaryArray<T: Unboxable>(dictionaries: [UnboxableDictionary], forKey key: String, required: Bool) -> [T]? { var transformed = [T]() for dictionary in dictionaries { if let unboxed: T = Unbox(dictionary, context: self.context) { transformed.append(unboxed) } else if required { self.failForInvalidValue(dictionaries, forKey: key) } } return transformed } private func transformUnboxableDictionaryDictionary<T: Unboxable>(dictionaries: UnboxableDictionary, required: Bool) -> [String : T]? { var transformed = [String : T]() for (key, dictionary) in dictionaries { if let unboxableDictionary = dictionary as? UnboxableDictionary { if let unboxed: T = Unbox(unboxableDictionary, context: self.context) { transformed[key] = unboxed continue } } if required { self.failForInvalidValue(dictionary, forKey: key) } } return transformed } } // MARK: - UnboxValueResolver private class UnboxValueResolver<T> { let unboxer: Unboxer init(_ unboxer: Unboxer) { self.unboxer = unboxer } func resolveRequiredValueForKey(key: String, @autoclosure fallbackValue: () -> T) -> T { return self.resolveRequiredValueForKey(key, fallbackValue: fallbackValue, transform: { return $0 }) } func resolveRequiredValueForKey<R>(key: String, @autoclosure fallbackValue: () -> R, transform: T -> R?) -> R { if let value = self.resolveOptionalValueForKey(key, transform: transform) { return value } self.unboxer.failForInvalidValue(self.unboxer.dictionary[key], forKey: key) return fallbackValue() } func resolveOptionalValueForKey(key: String) -> T? { return self.resolveOptionalValueForKey(key, transform: { return $0 }) } func resolveOptionalValueForKey<R>(key: String, transform: T -> R?) -> R? { if let value = self.unboxer.dictionary[key] as? T { if let transformed = transform(value) { return transformed } } return nil } }
true
82d586154c06c9dc5f3716ee2fe6302976a9b6b6
Swift
filimo/XenZuTestProject
/XenZuTestProject/View/MovieDetailView.swift
UTF-8
1,701
2.921875
3
[]
no_license
// // MovieDetailView.swift // XenZuTestProject // // Created by Viktor Kushnerov on 22.06.21. // import Resolver import SwiftUI struct MovieDetailView: View { let id: MovieItem.ID @InjectedObject var store: MovieDetailStore init(id: MovieItem.ID) { self.id = id store.fetchMovieDetail(id: id) } var body: some View { ScrollView { switch store.state { case .finished: EmptyView() case .idle: Text("Loading...") case .loading: Text("Loading...") case .loaded(let item): infoView(item: item) .padding() case .failed(let error): Text("\(error.localizedDescription)") } } .navigationBarTitleDisplayMode(.inline) } private func infoView(item: MovieDetail) -> some View { VStack { ContentView.posterView(posterPath: item.posterPath) .frame(width: 200, height: 300) HStack { VStack { HStack { Text("\(item.originalTitle)") .font(.headline) Spacer() } HStack { Text("\(item.releaseDate, formatter: DateFormatter.yearFormatter)") Spacer() } } } Text(item.overview) .padding(.top, 5) } } } struct MovieDetailView_Previews: PreviewProvider { static var previews: some View { MovieDetailView(id: 1111) } }
true
6daf1de295937de220af2b5cfc057b9b229c0760
Swift
DoubleXStudios/BlackJack
/BlackJack/BlackJackGame.swift
UTF-8
326
2.546875
3
[]
no_license
// // BlackJackGame.swift // BlackJack // // Created by Quincy McCarthy on 4/29/16. // Copyright © 2016 AppFactory. All rights reserved. // import Foundation enum StateX{ case Betting case Game case Payout } class BlackJackGameX{ var currentState: StateX = .Betting var currentBet: Int = 10 }
true
01253b46495ffdfc7bf2dfbbbf7e6ec16c22a50a
Swift
JEXcome/Weather-App
/Weather App/Main/MainInteractor.swift
UTF-8
856
2.703125
3
[]
no_license
// // MainInteractor.swift // Weather App // // Created by (-.-) on 19.07.2020. // Copyright © 2020 Eugene Zimin. All rights reserved. // import Foundation import RxSwift import RxCocoa class MainInteractor: NSObject { private let entity : Entity public var data : BehaviorRelay<[Locality]> { return entity.data } init(entity:Entity) { self.entity = entity super.init() } func appendLocality(_ locality : Locality) { entity.appendLocality(locality) } func prependLocality(_ locality : Locality) { entity.prependLocality(locality) } func removeLocality(at index: Int) { entity.removeLocality(at: index) } func locality(at index: Int) -> Locality { return entity.data.value[index] } }
true
62ed156bc33e94a58db000830ef77bfeba950661
Swift
tylerlong/RingCentralSwift
/Sources/RingCentral/Definitions/GetStateInfoResponse.swift
UTF-8
477
2.703125
3
[]
no_license
import Foundation public class GetStateInfoResponse: Codable { public init() { } /// Internal identifier of a state public var `id`: String? /// Canonical URI of a state public var `uri`: String? /// Information on a country the state belongs to public var `country`: GetCountryInfoState? /// Short code for a state (2-letter usually) public var `isoCode`: String? /// Official name of a state public var `name`: String? }
true
e05884531d2e5fa96ecfcb7b0d297dac67c124ef
Swift
adazhu365/rest-api
/ada/APIManger.swift
UTF-8
855
2.640625
3
[]
no_license
import UIKit import SwiftyJSON class APIManager: NSObject { let baseURL = "http://stardock.cs.virginia.edu/louslist/Courses/view/CS" static let sharedInstance = APIManager() func getPostWithId(postId: String, onSuccess: @escaping(JSON) -> Void, onFailure: @escaping(Error) -> Void){ let url : String = baseURL + String("/" + postId + "?json") let request: NSMutableURLRequest = NSMutableURLRequest(url: NSURL(string: url)! as URL) request.httpMethod = "GET" let session = URLSession.shared let task = session.dataTask(with: request as URLRequest, completionHandler: {data, response, error -> Void in if(error != nil){ onFailure(error!) } else{ let result = JSON(data: data!) onSuccess(result) } }) task.resume() } }
true
f5bf1615d5406779c80e44f7e77d465911961e87
Swift
losingwait/iOS
/LosingWait/API/MachineGroup.swift
UTF-8
472
2.765625
3
[ "MIT" ]
permissive
// // MachineGroup.swift // LosingWait // // Created by Salman Mithani on 3/27/19. // Copyright © 2019 Mike JS. Choi. All rights reserved. // struct MachineGroup: Displayable { let name: String let id: String var queue: [String]? init(response: [String : Any]) { id = response["_id"] as! String name = response["name"] as! String if let queue = response["queue"] as? [String] { self.queue = queue } } }
true
a86ead758acbc278143aee774cafc6bf9eddbbfc
Swift
JohnTJ/chord-finder
/Chord Finder/ViewController.swift
UTF-8
6,569
2.90625
3
[]
no_license
// // ViewController.swift // Chord Finder // // Created by John Jones on 7/20/18. // Copyright © 2018 John Jones. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var chordTitleLabel: UILabel! @IBOutlet weak var keysLabel: UILabel! @IBOutlet weak var chordDescription: UILabel! @IBOutlet weak var chordTextField: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. keys.append(c) keys.append(cSharp) keys.append(d) keys.append(eFlat) keys.append(e) keys.append(f) keys.append(fSharp) keys.append(g) keys.append(aFlat) keys.append(a) keys.append(bFlat) keys.append(b) print(c.getMajor()) createChordFinder() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } let chords = ["--", "major", "minor", "diminished", "augmented", "major 7th", "minor 7th", "dominant 7th", "major 6th", "minor 6th", "diminished 7th", "augmented 7th", "dom 7th b5th", "major 7th b3rd", "minor 7th b5th", "dom 7th sus 4th"] var keys = [Key]() let c = Key(named: "C", placedAt: 1) let cSharp = Key(named: "C#", placedAt: 2) let d = Key(named: "D", placedAt: 3) let eFlat = Key(named: "Eb", placedAt: 4) let e = Key(named: "E", placedAt: 5) let f = Key(named: "F", placedAt: 6) let fSharp = Key(named: "F#", placedAt: 7) let g = Key(named: "G", placedAt: 8) let aFlat = Key(named: "Ab", placedAt: 9) let a = Key(named: "A", placedAt: 10) let bFlat = Key(named: "Bb", placedAt: 11) let b = Key(named: "B", placedAt: 12) func createChordFinder() { let chordFinder = UIPickerView() chordFinder.delegate = self chordTextField.inputView = chordFinder createToolbar() //Custom chordFinder.backgroundColor = .white } func createToolbar() { let toolBar = UIToolbar() toolBar.sizeToFit() let doneButton = UIBarButtonItem(title: "Done", style: .plain, target: self, action: #selector(ViewController.dismissKeyboard)) toolBar.setItems([doneButton], animated: false) toolBar.isUserInteractionEnabled = true chordTextField.inputAccessoryView = toolBar } @objc func dismissKeyboard() { view.endEditing(true) } } extension ViewController: UIPickerViewDelegate, UIPickerViewDataSource { func numberOfComponents(in pickerView: UIPickerView) -> Int { return 2 } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { if component == 0 { return keys[row].getKeyName() } return chords[row] } func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { if component == 0 { return keys.count } return chords.count } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { let key = keys[pickerView.selectedRow(inComponent: 0)].getKeyName() let chord = chords[pickerView.selectedRow(inComponent: 1)] chordTextField.text = "\(key) \(chord)" if chord.elementsEqual("major") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMajor() chordDescription.text = Key.majorDescrip } else if chord.elementsEqual("minor") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMinor() chordDescription.text = Key.minorDescrip } else if chord.elementsEqual("diminished") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getDiminished() chordDescription.text = Key.diminishedDescrip } else if chord.elementsEqual("augmented") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getAugmented() chordDescription.text = Key.augmentedDescrip } else if chord.elementsEqual("major 7th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMajor7th() chordDescription.text = Key.major7thDescrip } else if chord.elementsEqual("minor 7th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMinor7th() chordDescription.text = Key.minor7thDescrip } else if chord.elementsEqual("dominant 7th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getDom7th() chordDescription.text = Key.dom7thDescrip } else if chord.elementsEqual("major 6th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMajor6th() chordDescription.text = Key.major6thDescrip } else if chord.elementsEqual("minor 6th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMinor6th() chordDescription.text = Key.minor6thDescrip } else if chord.elementsEqual("diminished 7th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getDim7th() chordDescription.text = Key.diminished7thDescrip } else if chord.elementsEqual("augmented 7th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getAug7th() chordDescription.text = Key.augmented7thDescrip } else if chord.elementsEqual("dom 7th b5th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getDom7thb5() chordDescription.text = Key.dom7thb5Descrip } else if chord.elementsEqual("major 7th b3rd") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMaj7thb3() chordDescription.text = Key.maj7thb3Descrip } else if chord.elementsEqual("minor 7th b5th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getMin7thb5() chordDescription.text = Key.min7thb5Descrip } else if chord.elementsEqual("dom 7th sus 4th") { keysLabel.text = keys[pickerView.selectedRow(inComponent: 0)].getDom7thSus4() chordDescription.text = Key.dom7thSus4Descrip } } }
true
e2de6b9282ed88d5b977835db646f690d44e2212
Swift
ddopik/SpidersAttend_ios
/SpidersAttend/base/model/NetworkBaseError.swift
UTF-8
1,250
3.046875
3
[]
no_license
// // NetworkBaseError.swift // SpidersAttend // // Created by ddopik on 6/24/19. // Copyright © 2019 Brandeda. All rights reserved. // import Foundation struct NetworkBaseError : Codable { let code : String? let data : NetworkBaseErrorData? let status : Bool? // need to add helper constructor to unable user to intialize NetworkBaseError manually enum CodingKeys: String, CodingKey { case code = "code" case data = "data" case status = "status" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) code = try values.decodeIfPresent(String.self, forKey: .code) data = try values.decodeIfPresent(NetworkBaseErrorData.self, forKey: .data) status = try values.decodeIfPresent(Bool.self, forKey: .status) } struct NetworkBaseErrorData : Codable { var msg : String? enum CodingKeys: String, CodingKey { case msg = "msg" } init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) msg = try values.decodeIfPresent(String.self, forKey: .msg) } } }
true
17c10cca9da5a048d02239d7f63e6890952ae23d
Swift
princealvinyusuf/VolunApp
/Voluntee/Controller/Recruiter/Posting/RecruitPostDateVC.swift
UTF-8
1,100
2.71875
3
[ "MIT" ]
permissive
// // RecruitPostDateVC.swift // Voluny // import UIKit class RecruitPostDateVC: UIViewController { @IBOutlet weak var datePicker: UIDatePicker! var selectedDate = "" override func viewDidLoad() { super.viewDidLoad() datePicker.minimumDate = Date() if selectedDate.count > 1{ let dateFormatter = DateFormatter() dateFormatter.dateFormat = "dd/MM/yyyy HH:mm" // We want American AM/PM style instead datePicker.date = dateFormatter.date(from: selectedDate)! } } @IBAction func doneTapped(_ sender: Any) { let formatter = DateFormatter() formatter.dateFormat = "dd/MM/yyyy HH:mm" // We want American AM/PM style instead let dateString = formatter.string(from: datePicker.date) NotificationCenter.default.post(name: Notification.Name("setDate"), object: dateString) dismiss(animated: true, completion: nil) } @IBAction func cancelTapped(_ sender: Any) { dismiss(animated: true, completion: nil) } }
true
c34874f24ae5f405dda34a9ed99a2ddef55cf370
Swift
arias111/MesanApplication
/MesanApplication/Modules/Authentication/AuthenticationSerivce/MoyaApi.swift
UTF-8
846
2.828125
3
[]
no_license
// // MoyaApi.swift // MesanApplication // // Created by galiev nail on 11.05.2021. // import Foundation import Moya enum MoyaApi { case signIn(email: String, password: String) } extension MoyaApi: TargetType { var headers: [String: String]? { return ["Content-Type": "application/json"] } var sampleData: Data { return Data() } var baseURL: URL { return URL(string: BaseUrl.url)! } var path: String { return "/signInToken" } var method: Moya.Method { return .post } var task: Task { switch self { case let .signIn(email, password): let userData = ["email": email, "password": password] return .requestParameters(parameters: userData, encoding: JSONEncoding.default) } } }
true
6e1c0c7bf93a7870adf52e6e1cced77876953690
Swift
Komal2905/ReUseComponent
/PullNotificationViewController.swift
UTF-8
3,682
2.5625
3
[]
no_license
// // PullNotificationViewController.swift // ReUseComponent // // Created by ProjectHeena on 8/9/16. // Copyright © 2016 ProjectHeena. All rights reserved. // import UIKit class PullNotificationViewController: UIViewController { @IBOutlet weak var NotificationScheduleDateTime: UILabel! let datePickerView : UIDatePicker = UIDatePicker() override func viewDidLoad() { super.viewDidLoad() setupNotificationSettings() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } @IBAction func showPullNotificationButtonPressed(sender: AnyObject) { let settings = UIApplication.sharedApplication().currentUserNotificationSettings() if settings!.types == .None { let ac = UIAlertController(title: "Can't schedule", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) return } let notification = UILocalNotification() notification.fireDate = NSDate(timeIntervalSinceNow: 5) notification.alertBody = "Hey you! Yeah you! Swipe to unlock!" notification.alertAction = "be awesome!" notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["CustomField1": "w00t"] UIApplication.sharedApplication().scheduleLocalNotification(notification) } func setupNotificationSettings() { // Specify the notification types. let settings = UIUserNotificationSettings(forTypes: [.Alert, .Badge], categories: nil) UIApplication.sharedApplication().registerUserNotificationSettings(settings) } @IBAction func chooseDateTimeButtonPressed(sender: AnyObject) { datePickerView.datePickerMode = UIDatePickerMode.DateAndTime datePickerView.addTarget(self, action:#selector(PullNotificationViewController.handleDatePicker(_:)), forControlEvents: UIControlEvents.ValueChanged) datePickerView.frame = CGRectMake(sender.frame.origin.x , sender.frame.origin.y + 100, sender.frame.size.width, 150) self.view.addSubview(datePickerView) } func handleDatePicker(sender: UIDatePicker) { datePickerView.removeFromSuperview() let dateFormatter = NSDateFormatter() dateFormatter.dateFormat = "dd MMM yyyy HH:mm" NotificationScheduleDateTime.text = dateFormatter.stringFromDate(sender.date) let settings = UIApplication.sharedApplication().currentUserNotificationSettings() if settings!.types == .None { let ac = UIAlertController(title: "Can't schedule", message: "Either we don't have permission to schedule notifications, or we haven't asked yet.", preferredStyle: .Alert) ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil)) presentViewController(ac, animated: true, completion: nil) return } let notification = UILocalNotification() notification.fireDate = sender.date notification.alertBody = "Shchedule Later Notification" notification.alertAction = "be awesome!" notification.soundName = UILocalNotificationDefaultSoundName notification.userInfo = ["CustomField1": "w00t"] UIApplication.sharedApplication().scheduleLocalNotification(notification) } }
true
5a2663c0d0e07a09f6d5666c27c6b4c3578a63d6
Swift
vladislav14141/Figma-Colors
/Figma Colors/Pages/Cells/FigmaColorCell.swift
UTF-8
1,197
3
3
[]
no_license
// // FigmaColorCell.swift // Figma Colors // // Created by Владислав Миронов on 08.04.2021. // import SwiftUI struct FigmaColorCell: View { @ObservedObject var colorItem: ColorItem var isMock = false init() { isMock = true let color = FigmaColor(r: Double(Int.random(in: 0...255)), g: Double(Int.random(in: 0...255)), b: Double(Int.random(in: 0...255)), a: 1) self.colorItem = ColorItem(figmaName: "Bla/bloBelka", light: color, dark: color) } init(colorItem: ColorItem) { self.colorItem = colorItem } var body: some View { VStack(alignment: .leading, spacing: 8) { VStack(spacing: 0) { if isMock { Color.secondaryBackground } else { FigmaColorCellItem(figmaColor: colorItem.light, scheme: .light) FigmaColorCellItem(figmaColor: colorItem.dark, scheme: .dark) } } .cornerRadius(16) .frame(height: 120) FigmaCellLabel(text: colorItem.shortName, isSelected: $colorItem.isSelected) } } }
true
fa66914f8878bf07504763e626b7c054cae3fec5
Swift
sciv-img/sciv
/Sources/Utils.swift
UTF-8
2,624
2.515625
3
[]
no_license
import AppKit import PathKit import Cpcre class GCDFileMonitor { private static let dq = DispatchQueue(label: "sx.kenji.sciv", attributes: .concurrent) private let file: Int32 private let dsfso: DispatchSourceFileSystemObject init?(_ dirOrFilePath: Path, _ callback: @escaping () -> Void, events: DispatchSource.FileSystemEvent = .all) { self.file = open(dirOrFilePath.string, O_EVTONLY) if self.file < 0 { return nil } self.dsfso = DispatchSource.makeFileSystemObjectSource( fileDescriptor: self.file, eventMask: events, queue: GCDFileMonitor.dq ) self.dsfso.setEventHandler(handler: callback) self.dsfso.setCancelHandler(handler: { close(self.file) }) self.dsfso.resume() } deinit { self.cancel() } func cancel() { self.dsfso.cancel() } } class Regex: Hashable, Equatable { let regex: OpaquePointer? let hash: Int // For Hashable init?(_ regex: String) { self.hash = regex.hashValue let error = UnsafeMutablePointer<UnsafePointer<Int8>?>.allocate(capacity: 1) let offset = UnsafeMutablePointer<Int32>.allocate(capacity: 1) defer { error.deallocate() error.deinitialize(count: 1) offset.deallocate() offset.deinitialize(count: 1) } self.regex = pcre_compile(regex, 0, error, offset, nil) if self.regex == nil { return nil } } deinit { pcre_free?(UnsafeMutableRawPointer(self.regex)) } func match(_ string: String) -> (Bool, [String]?) { let ovector = UnsafeMutablePointer<Int32>.allocate(capacity: 3 * 32) defer { ovector.deallocate() ovector.deinitialize(count: 1) } let matches = pcre_exec( self.regex, nil, string, Int32(string.count), 0, Cpcre.PCRE_PARTIAL, ovector, 3 * 32 ) if matches == Cpcre.PCRE_ERROR_PARTIAL { return (true, nil) } if matches < 0 { return (false, nil) } // TODO: Make this more generic? let si = string.startIndex let start = string.index(si, offsetBy: Int(ovector[2])) let end = string.index(si, offsetBy: Int(ovector[3])) return (true, [String(string[start..<end])]) } func hash(into hasher: inout Hasher) { hasher.combine(self.hash) } static func == (lhs: Regex, rhs: Regex) -> Bool { return lhs.hash == rhs.hash } }
true
6de53cca3bb3cd194a675dd2ce6c028b56be0369
Swift
ChantalDemissie/resumeApp
/resume/LanguagesViewController.swift
UTF-8
1,957
3.359375
3
[ "MIT" ]
permissive
import UIKit class Language { let name : String let icon : UIImage init(name : String, icon : String) { self.name = name self.icon = UIImage(named: icon)!.invertedColors()! } } class LanguagesViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let languages = [ Language(name: "Swift", icon: "icons8-swift-100"), Language(name: "Ruby", icon: "icons8-ruby-programming-language-100"), Language(name: "Ruby on Rails", icon: "rails"), Language(name: "React", icon: "icons8-react-native-100"), Language(name: "Javascript", icon: "icons8-javascript-100"), Language(name: "HTML", icon: "icons8-html-100"), Language(name: "CSS", icon: "icons8-css-100"), ] override func viewDidLoad() { super.viewDidLoad() tableView.dataSource = self } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return languages.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = UITableViewCell() let language : Language = languages[indexPath.row] cell.textLabel?.text = "\(language.name)" cell.imageView?.image = language.icon return cell } } extension UIImage { /// source: https://www.avanderlee.com/swift/dark-mode-support-ios/ /// Inverts the colors from the current image. Black turns white, white turns black etc. func invertedColors() -> UIImage? { guard let ciImage = CIImage(image: self) ?? ciImage, let filter = CIFilter(name: "CIColorInvert") else { return nil } filter.setValue(ciImage, forKey: kCIInputImageKey) guard let outputImage = filter.outputImage else { return nil } return UIImage(ciImage: outputImage) } }
true
c0914fcac14ba6c3f33f2a3d572209435f9a3db7
Swift
bluetowel99/Arrow
/Arrow/Core/ARBubbleStore.swift
UTF-8
2,201
2.515625
3
[]
no_license
import Foundation class ARBubbleStore { var networkSession = ARNetworkSession.shared var bubblesListVC: BubblesListVC? fileprivate var _bubbles: [ARBubble]? fileprivate var _activeBubble: ARBubble? var activeBubble: ARBubble? { get { guard let bubbles = _bubbles, !bubbles.isEmpty else { return nil } return _activeBubble ?? bubbles.first } set { _activeBubble = newValue } } func fetchUserBubbles(forceRefresh: Bool = false, completion: @escaping ([ARBubble]?) -> Void) { if forceRefresh == false, let bubbles = _bubbles { completion(bubbles) return } refreshBubbles { success in if success { completion(self._bubbles) } } } fileprivate func refreshBubbles(completion: @escaping (_ success: Bool) -> Void) { // Reset cached variable. let activeBubbleId = _activeBubble?.identifier _bubbles = nil _activeBubble = nil getAllBubblesList { bubbles, error in if let error = error { print("Error loading bubbles from server: \(error.localizedDescription)") completion(false) return } self._bubbles = bubbles for bubble in self._bubbles! { if(bubble.identifier == activeBubbleId) { self._activeBubble = bubble } } completion(true) } } } // MARK: - Networking extension ARBubbleStore { fileprivate func getAllBubblesList(callback: (([ARBubble]?, NSError?) -> Void)?) { let getAllBubblesReq = GetAllBubblesRequest(platform: ARPlatform.shared) let _ = networkSession.send(getAllBubblesReq) { result in switch result { case .success(let bubbles): callback?(bubbles, nil) case .failure(let error): callback?(nil, error as NSError) } } } }
true
f1fb02b2ff40c5b44369116058fccc4813eb3377
Swift
rootm/shoppingApp_ios
/shopping_app/LoginViewController.swift
UTF-8
2,376
2.75
3
[]
no_license
// // LoginViewController.swift // shopping_app // // Created by Muvindu on 9/26/19. // Copyright © 2019 Muvindu. All rights reserved. // import UIKit import Alamofire import SwiftyJSON class LoginViewController: UIViewController { @IBOutlet var userEmail: UITextField! @IBOutlet var userPass: UITextField! @IBOutlet var venderSwitch: UISwitch! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } @IBAction func loginUser(_ sender: Any) { if (!(userEmail.text?.isEmpty ?? true) && !(userPass.text?.isEmpty ?? true)){ loginAPI(user: userEmail.text!, password: userPass.text!) } } func loginAPI(user: String, password: String){ Alamofire.request("https://reqres.in/api/login", method: .post, parameters: ["email": user,"password": password] ) .responseJSON { response in guard response.result.isSuccess, let value = response.result.value else { print("Error while fetching tags: \(String(describing: response.result.error))") return } // 3 let response = JSON(value) if response["token"].exists() { print("response someKey exists") let ProductListView: ProductListViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProductListViewController") as! ProductListViewController if self.venderSwitch.isOn{ ProductListView.vendor = true } self.navigationController?.pushViewController(ProductListView,animated: true); print(response) }else{ print(response) } } } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepare(for segue: UIStoryboardSegue, sender: Any?) { // Get the new view controller using segue.destination. // Pass the selected object to the new view controller. } */ }
true
a34ec8d5da3b82f3d975194dc5f70377297bbb20
Swift
knauth/SizeOMatic
/Clothing App/ClothingSize.swift
UTF-8
450
2.953125
3
[]
no_license
// // ClothingSize.swift // Clothing App // // Created by Christopher Knauth on 5/15/17. // Copyright © 2017 Christopher Knauth. All rights reserved. // import Foundation public class ClothingSize { public var name: String public var chestSize: Double? public var waistSize: Double public init(name:String, chestSize: Double?, waistSize: Double){ self.name = name self.chestSize = chestSize self.waistSize = waistSize } }
true
2222c88b5bb685618846bce477244581e4a2cf67
Swift
EvryMalmo/SupportTool-IOS
/One Support Tool/SystemInformationViewController.swift
UTF-8
3,458
2.546875
3
[]
no_license
// // SystemInformationViewController.swift // One Support Tool // // Created by Admin on 2016-02-04. // Copyright © 2016 EVRY. All rights reserved. // import UIKit import SystemConfiguration import Foundation import NetworkExtension class SystemInformationViewController: UIViewController { @IBOutlet weak var batteryStatus: UITextField! @IBOutlet weak var osVersion: UITextField! @IBOutlet weak var device: UITextField! @IBOutlet weak var osName: UITextField! @IBOutlet weak var physicalMemory: UITextField! @IBOutlet weak var processorCount: UITextField! @IBOutlet weak var systemUptime: UITextField! @IBOutlet weak var IpAdress: UITextField! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. // Battery Information UIDevice.currentDevice().batteryMonitoringEnabled = true batteryStatus.text = String(Int(UIDevice.currentDevice().batteryLevel) * 100) + "%" // Device Information device.text = UIDevice.currentDevice().name // OS Information osName.text = UIDevice.currentDevice().systemName // OS Version osVersion.text = String(NSProcessInfo.processInfo().operatingSystemVersionString) // Memory Information physicalMemory.text = String(NSProcessInfo.processInfo().physicalMemory) // # Processors processorCount.text = String(NSProcessInfo.processInfo().processorCount) // System Uptime systemUptime.text = String(NSProcessInfo.processInfo().systemUptime) // Networks available IpAdress.text = getIFAddresses().first } func getIFAddresses() -> [String] { var addresses = [String]() // Get list of all interfaces on the local machine: var ifaddr : UnsafeMutablePointer<ifaddrs> = nil if getifaddrs(&ifaddr) == 0 { // For each interface ... for (var ptr = ifaddr; ptr != nil; ptr = ptr.memory.ifa_next) { let flags = Int32(ptr.memory.ifa_flags) var addr = ptr.memory.ifa_addr.memory // Check for running IPv4, IPv6 interfaces. Skip the loopback interface. if (flags & (IFF_UP|IFF_RUNNING|IFF_LOOPBACK)) == (IFF_UP|IFF_RUNNING) { if addr.sa_family == UInt8(AF_INET) || addr.sa_family == UInt8(AF_INET6) { // Convert interface address to a human readable string: var hostname = [CChar](count: Int(NI_MAXHOST), repeatedValue: 0) if (getnameinfo(&addr, socklen_t(addr.sa_len), &hostname, socklen_t(hostname.count), nil, socklen_t(0), NI_NUMERICHOST) == 0) { if let address = String.fromCString(hostname) { addresses.append(address) } } } } } freeifaddrs(ifaddr) } return addresses } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
true
45aa9a005d3d4b2955a4a8e56b83be08b933830a
Swift
netguru/CarLens-iOS
/CarLens/Source Files/Common/Extensions/UIViewControllerExtension.swift
UTF-8
931
2.9375
3
[ "Apache-2.0", "LicenseRef-scancode-unknown-license-reference" ]
permissive
// // UIViewControllerExtension.swift // CarLens // import UIKit.UIViewController extension UIViewController { /// Adds view controller as a child (calls all required methods automatically) /// /// - Parameters: /// - child: Controller to be added as child /// - container: Container to which child should be added func add(_ child: UIViewController, inside container: UIView) { addChild(child) container.addSubview(child.view) child.didMove(toParent: self) child.view.translatesAutoresizingMaskIntoConstraints = false child.view.constraintToSuperviewEdges() } /// Removes view controller from parent if added as child (calls all required methods automatically) func remove() { guard parent != nil else { return } willMove(toParent: nil) removeFromParent() view.removeFromSuperview() } }
true
3b80e6f8f548586f762ee0ca89dfa43102cc4ec7
Swift
wwcdmf/Development
/LootFox/LootFox/LootFox/CustomUI/UI Objects/UITextFieldLibrary.swift
UTF-8
3,494
2.640625
3
[ "MIT" ]
permissive
// // TextFieldView.swift // LootFox // // Created by Landon Carr on 6/26/18. // Copyright © 2018 Landon Carr. All rights reserved. // import Foundation import UIKit class TextFieldView: UITextField { private var padding = UIEdgeInsets(top: 0, left: 5, bottom: 0, right: 0) override func awakeFromNib() { // Place Holder ( Choose Color) let placeholder = NSAttributedString(string: self.placeholder!, attributes: [NSAttributedString.Key.foregroundColor: #colorLiteral(red: 0.8039215803, green: 0.8039215803, blue: 0.8039215803, alpha: 1)]) self.attributedPlaceholder = placeholder let border = CALayer() let width = CGFloat(1.0) border.borderColor = UIColor.lightGray.cgColor border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) border.borderWidth = width self.layer.addSublayer(border) self.layer.masksToBounds = true /// UITextField (Border Appearance) // let border = CALayer() // let width = CGFloat(5.0) // border.borderColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1) // // self.layer.cornerRadius = 10.0 // // border.frame = CGRect(x: 0, y: self.frame.size.height - width, width: self.frame.size.width, height: self.frame.size.height) //// TEST tEST TEST //// // let border = CALayer() // let width = CGFloat(1.0) // // self.layer.addSublayer(border) self.layer.cornerRadius = 10.0 // self.layer.shadowRadius = 2.0 // self.layer.shadowColor = #colorLiteral(red: 0.6000000238, green: 0.6000000238, blue: 0.6000000238, alpha: 1) // self.layer.borderWidth = width self.layer.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 0.2502140411) // // self.layer.borderColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) // self.layer.addSublayer(border) // border.borderWidth = width // self.layer.addSublayer(border) // self.layer.masksToBounds = true //// TEST tEST TEST //// super.awakeFromNib() } // UITextField (adds Image option to UITextField) override func leftViewRect(forBounds bounds: CGRect) -> CGRect { var textRect = super.leftViewRect(forBounds: bounds) textRect.origin.x += leftPadding return textRect } @IBInspectable var leftImage: UIImage? { didSet { updateView() } } @IBInspectable var leftPadding: CGFloat = 0 @IBInspectable var color: UIColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) { didSet { updateView() } } func updateView() { if let image = leftImage { leftViewMode = UITextField.ViewMode.always let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 50, height: 25)) imageView.contentMode = .scaleAspectFit imageView.image = image // Note: In order for your image to use the tint color, you have to select the image in the Assets.xcassets and change the "Render As" property to "Template Image". imageView.tintColor = color leftView = imageView } else { leftViewMode = UITextField.ViewMode.never leftView = nil } // Placeholder text color attributedPlaceholder = NSAttributedString(string: placeholder != nil ? placeholder! : "", attributes:[NSAttributedString.Key.foregroundColor: color]) } }
true
b49223480a64689a2ee66dafdbfa5b8217c1c8ba
Swift
Ayeonii/RxDataSourcesDemo
/RxDataSourcesDemo/RxDataSourcesDemo/Intermediate/ViewModel/IntermediateItemViewModel.swift
UTF-8
345
2.65625
3
[]
no_license
// // IntermediateItemViewModel.swift // RxDataSourcesDemo // // Created by 이아연 on 2021/05/17. // import Foundation struct IntermediateItemViewModel { var title : String var desc : String init(itemModel : IntermediateItemModel){ self.title = itemModel.itemTitle self.desc = itemModel.itemDesc } }
true
cb42e531031fd6b514e5263d7ee280a973a8b2ab
Swift
ringoid/client-ios
/Sources/Services/DB/Entities/ActionPhoto.swift
UTF-8
1,045
2.703125
3
[]
no_license
// // ActionPhoto.swift // ringoid // // Created by Victor Sukochev on 28/01/2019. // Copyright © 2019 Ringoid. All rights reserved. // import RealmSwift class ActionPhoto: DBServiceObject { @objc dynamic var id: String! @objc dynamic var path: String! @objc dynamic var pathType: Int = 0 @objc dynamic var isLiked: Bool = false } extension Photo { func actionInstance() -> ActionPhoto { let actionPhoto = ActionPhoto() actionPhoto.id = self.id actionPhoto.path = self.path actionPhoto.pathType = self.pathType actionPhoto.isLiked = self.isLiked actionPhoto.orderPosition = self.orderPosition return actionPhoto } } extension ActionPhoto { func filepath() -> FilePath { let type = FileType(rawValue: self.pathType)! return FilePath(filename: self.path, type: type) } func setFilepath(_ filepath: FilePath) { self.path = filepath.filename self.pathType = filepath.type.rawValue } }
true
2819aef821a0cebea0cb6d587e6cdfeac6ee1de9
Swift
AppBaker/Hotel-Manzana
/Hotel Manzana/Model/Regisrtation.swift
UTF-8
1,462
3.3125
3
[]
no_license
// // Regisrtation.swift // Hotel Manzana // // Created by Ivan Nikitin on 21/04/2019. // Copyright © 2019 Ivan Nikitin. All rights reserved. // import Foundation struct Registration { var firstName: String var lastNane: String var emailAdres: String var checkInDate: Date var checkOutDate: Date var numberOfAdults: Int var numberOfChildren: Int var roomType: RoomType var wifi: Bool } extension Registration { var totalCost: Double { let numberOfDays = checkOutDate.timeIntervalSince(checkInDate) / (60*60*24) var cost = numberOfDays * roomType.price if wifi { cost += numberOfDays * 9.99 } return cost } var allKeys: [String] { return [ "First name", "Last name", "E-mail", "Check in date", "Check out date", "Number of Adults", "Number of children", "Room Type", "Wi-Fi", ] } var allValues: [String] { let dateFormater = DateFormatter() dateFormater.timeStyle = .none dateFormater.dateStyle = .short return [ firstName, lastNane, emailAdres, dateFormater.string(from: checkInDate), dateFormater.string(from: checkOutDate), "\(numberOfAdults)", "\(numberOfChildren)", roomType.shortName, "\(wifi)" ] } }
true
fe6f54af687ee504e13faa7564ffe055d40ccec8
Swift
kerasking/VRMTextAnimator
/VRMTextAnimator/VRMTextAnimator.swift
UTF-8
6,031
2.546875
3
[]
no_license
// // VRMTextAnimator.swift // VRMTextAnimator // // Created by Bartosz Olszanowski on 13.04.2016. // Copyright © 2016 Vorm. All rights reserved. // import UIKit import CoreFoundation public protocol VRMTextAnimatorDelegate { func textAnimator(textAnimator: VRMTextAnimator, animationDidStart animation: CAAnimation) func textAnimator(textAnimator: VRMTextAnimator, animationDidStop animation: CAAnimation) } public class VRMTextAnimator: NSObject { // MARK: Properties public var fontName = "Avenir" public var fontSize : CGFloat = 50.0 public var textToAnimate = "Hello Swift!" public var textColor = UIColor.redColor().CGColor public var delegate : VRMTextAnimatorDelegate? private var animationLayer = CALayer() private var pathLayer : CAShapeLayer? private var referenceView : UIView // MARK: Initialization init(referenceView: UIView) { self.referenceView = referenceView super.init() defaultConfiguration() } deinit { clearLayer() } // MARK: Configuration private func defaultConfiguration() { animationLayer = CALayer() animationLayer.frame = referenceView.bounds referenceView.layer.addSublayer(animationLayer) setupPathLayerWithText(textToAnimate, fontName: fontName, fontSize: fontSize) } // MARK: Animations private func clearLayer() { if let _ = pathLayer { pathLayer?.removeFromSuperlayer() pathLayer = nil } } private func setupPathLayerWithText(text: String, fontName: String, fontSize: CGFloat) { clearLayer() let letters = CGPathCreateMutable() let font = CTFontCreateWithName(fontName, fontSize, nil) let attrString = NSAttributedString(string: text, attributes: [kCTFontAttributeName as String : font]) let line = CTLineCreateWithAttributedString(attrString) let runArray = CTLineGetGlyphRuns(line) for runIndex in 0..<CFArrayGetCount(runArray) { let run : CTRunRef = unsafeBitCast(CFArrayGetValueAtIndex(runArray, runIndex), CTRunRef.self) let dictRef : CFDictionaryRef = unsafeBitCast(CTRunGetAttributes(run), CFDictionaryRef.self) let dict : NSDictionary = dictRef as NSDictionary let runFont = dict[kCTFontAttributeName as String] as! CTFont for runGlyphIndex in 0..<CTRunGetGlyphCount(run) { let thisGlyphRange = CFRangeMake(runGlyphIndex, 1) var glyph = CGGlyph() var position = CGPointZero CTRunGetGlyphs(run, thisGlyphRange, &glyph) CTRunGetPositions(run, thisGlyphRange, &position) let letter = CTFontCreatePathForGlyph(runFont, glyph, nil) var t = CGAffineTransformMakeTranslation(position.x, position.y) CGPathAddPath(letters, &t, letter) } } let path = UIBezierPath() path.moveToPoint(CGPointZero) path.appendPath(UIBezierPath(CGPath: letters)) let pathLayer = CAShapeLayer() pathLayer.frame = animationLayer.bounds; pathLayer.bounds = CGPathGetBoundingBox(path.CGPath) pathLayer.geometryFlipped = true pathLayer.path = path.CGPath pathLayer.strokeColor = UIColor.blackColor().CGColor pathLayer.fillColor = textColor pathLayer.lineWidth = 1.0 pathLayer.lineJoin = kCALineJoinBevel self.animationLayer.addSublayer(pathLayer) self.pathLayer = pathLayer } public func startAnimation() { let duration = 4.0 pathLayer?.removeAllAnimations() setupPathLayerWithText(textToAnimate, fontName: fontName, fontSize: fontSize) let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = duration pathAnimation.fromValue = 0.0 pathAnimation.toValue = 1.0 pathAnimation.delegate = self pathLayer?.addAnimation(pathAnimation, forKey: "strokeEnd") let coloringDuration = 2.0 let colorAnimation = CAKeyframeAnimation(keyPath: "fillColor") colorAnimation.duration = duration + coloringDuration colorAnimation.values = [UIColor.clearColor().CGColor, UIColor.clearColor().CGColor, textColor] colorAnimation.keyTimes = [0, (duration/(duration + coloringDuration)), 1] pathLayer?.addAnimation(colorAnimation, forKey: "fillColor") } public func stopAnimation() { pathLayer?.removeAllAnimations() } public func clearAnimationText() { clearLayer() } public func prepareForAnimation() { pathLayer?.removeAllAnimations() setupPathLayerWithText(textToAnimate, fontName: fontName, fontSize: fontSize) let pathAnimation = CABasicAnimation(keyPath: "strokeEnd") pathAnimation.duration = 1.0 pathAnimation.fromValue = 0.0 pathAnimation.toValue = 1.0 pathAnimation.delegate = self pathLayer?.addAnimation(pathAnimation, forKey: "strokeEnd") pathLayer?.speed = 0 } public func updatePathStrokeWithValue(value: Float) { pathLayer?.timeOffset = CFTimeInterval(value) } // MARK: Animation delegate public override func animationDidStart(anim: CAAnimation) { self.delegate?.textAnimator(self, animationDidStart: anim) } public override func animationDidStop(anim: CAAnimation, finished flag: Bool) { self.delegate?.textAnimator(self, animationDidStop: anim) } }
true
b893a66c5b36f74bb78b9e3b6ad0b627f9a29a9d
Swift
Intrinsic-Audio/NoteLet
/NoteLet/PlayControlsViewController.swift
UTF-8
1,405
2.515625
3
[]
no_license
// // PlayControlsViewController.swift // NoteLet // // Created by Connor Taylor on 2/20/15. // Copyright (c) 2015 Intrinsic Audio. All rights reserved. // import UIKit class PlayControlsViewController: UIViewController { @IBOutlet var sliders: [EffectSlider]! @IBOutlet var toggles: [EffectButton]! override func viewDidLoad() { super.viewDidLoad() var messages = [""] var effects = ["chorus", "tremolo", "delay", "filter", "ringmod"] var index = 0 for button in toggles { button.effect = effects[index] index += 1 } index = 0 for slider in sliders { slider.effect = effects[index] index += 1 } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func toggleEffect(sender: EffectButton) { sender.sendMessage() } /* // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. } */ }
true
2f1d1fb360f6276c5cfc62a3c02a4897e9f10827
Swift
ollelind/Cashier
/Cashier/SubscriptionProductProvider.swift
UTF-8
2,291
2.6875
3
[]
no_license
// // SubscriptionProductProvider.swift // Cashier // // Created by Olof Lind on 2018-05-16. // Copyright © 2018 Olof Lind. All rights reserved. // import Foundation import StoreKit /* * Wrapper around SKProductRequest to fetch SKProducts from iTunes and map into SubscriptionProduct objects */ class SubscriptionProductProvider: NSObject { typealias SubscriptionProductsResponse = ((Error?, [SubscriptionProduct]?) -> Void)? fileprivate var productsFetchCompletion: SubscriptionProductsResponse fileprivate static var cachedSubscriptionProducts: [SubscriptionProduct]? override init() { super.init() } func fetchProducts(forProductIdentifiers identifiers: [String], completion: SubscriptionProductsResponse) { // First check if we've already fetched & cached the products, then there's no need to retrieve them again from iTunes if let cachedSubscriptions = SubscriptionProductProvider.cachedSubscriptionProducts { completion?(nil, cachedSubscriptions) return } // Save a reference to the completion closure as we need to invoke it after the iTunes product request callback productsFetchCompletion = completion let request = SKProductsRequest(productIdentifiers: Set(identifiers)) request.delegate = self request.start() } func resetCachedProducts() { SubscriptionProductProvider.cachedSubscriptionProducts = nil } fileprivate func handleProductResponse(_ response: [SKProduct]) { let subscriptionProducts = response.map { (iTunesProduct) -> SubscriptionProduct in return SubscriptionProduct(product: iTunesProduct) } SubscriptionProductProvider.cachedSubscriptionProducts = subscriptionProducts productsFetchCompletion?(nil, subscriptionProducts) } } extension SubscriptionProductProvider: SKProductsRequestDelegate { func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) { handleProductResponse(response.products) } func request(_ request: SKRequest, didFailWithError error: Error) { productsFetchCompletion?(error, nil) } }
true
0b8f8d1f8a5c2641e15ca52e5e45e98a1b978c28
Swift
tfleme/investmentSimulator
/InvestmentCalculator/InvestmentCalculator/Features/Simulator/Input/SimulatorInputView.swift
UTF-8
3,763
2.765625
3
[]
no_license
import UIKit import Components final class SimulatorInputView: UIView, ViewStackable, KeyboardAdjustable { // MARK: - Private properties private let scrollView = UIScrollView() private let contentView = UIView() // MARK: - Public properties let stackView = UIStackView() lazy var keyboardLayoutGuideBottomConstraint = scrollView.bottomAnchor.constraint( equalTo: safeAreaLayoutGuide.bottomAnchor) // MARK: - Public properties let button = Button() // MARK: - Initializers init() { super.init(frame: .zero) setupViewConfiguration() setupKeyboardNotifications() setupAccessibilityLabels() } required init?(coder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK: - ViewConfiguration extension SimulatorInputView: ViewConfigurable { func buildViewHierarchy() { addSubviews([scrollView]) scrollView.addSubviews([contentView]) contentView.addSubviews([stackView, button]) } func setupConstraints() { setupScrollViewConstraints() setupContentViewConstraints() setupStackViewConstraints() setupButtonConstraints() } func setupViews() { backgroundColor = .white setupStackView() } } // MARK: - Private methods - Constraints extension SimulatorInputView { private func setupScrollViewConstraints() { [ scrollView.leadingAnchor.constraint(equalTo: leadingAnchor), scrollView.trailingAnchor.constraint(equalTo: trailingAnchor), scrollView.topAnchor.constraint(equalTo: safeAreaLayoutGuide.topAnchor, constant: 24.0), keyboardLayoutGuideBottomConstraint ].activate() } private func setupContentViewConstraints() { [ contentView.leadingAnchor.constraint(equalTo: scrollView.leadingAnchor), contentView.trailingAnchor.constraint(equalTo: scrollView.trailingAnchor), contentView.topAnchor.constraint(equalTo: scrollView.topAnchor), contentView.bottomAnchor.constraint(equalTo: scrollView.bottomAnchor), contentView.widthAnchor.constraint(equalTo: scrollView.widthAnchor), contentView.heightAnchor.constraint(equalTo: scrollView.heightAnchor, priority: 250) ].activate() } private func setupStackViewConstraints() { [ stackView.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24.0), stackView.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24.0), stackView.topAnchor.constraint(equalTo: contentView.topAnchor) ].activate() } private func setupButtonConstraints() { [ button.topAnchor.constraint(greaterThanOrEqualTo: stackView.bottomAnchor, constant: 24.0), button.leadingAnchor.constraint(equalTo: contentView.leadingAnchor, constant: 24.0), button.trailingAnchor.constraint(equalTo: contentView.trailingAnchor, constant: -24.0), button.bottomAnchor.constraint(equalTo: contentView.safeAreaLayoutGuide.bottomAnchor, constant: -24.0) ].activate() } } // MARK: - Private methods - Setup extension SimulatorInputView { private func setupStackView() { stackView.axis = .vertical stackView.spacing = 40.0 stackView.distribution = .equalSpacing } } // MARK: - Private methods - Accessibility extension SimulatorInputView { private func setupAccessibilityLabels() { accessibilityLabel = "SimulatorInputView" button.accessibilityLabel = "SimulatorInputView.actionButton" button.isAccessibilityElement = true } }
true
041505121ca47412bd22de300557236b18fcd40d
Swift
techtronics/skyward-jump
/Skyward Jump/PlatformLayer.swift
UTF-8
1,144
2.921875
3
[]
no_license
// // PlatformLayerNode.swift // Skyward Jump // // Created by Petr Zvoníček on 25.03.15. // Copyright (c) 2015 NTNU. All rights reserved. // import SpriteKit class PlatformLayer: SKNode { init(world: World) { super.init() // create platforms to sprite for platform in world.platforms { let sprite = CloudSprite(pos: platform.position, width: platform.length, bounce: platform.bounce) self.addChild(sprite) } // create coins to sprite for coin in world.coins { let cSprite = CoinSprite(pos: coin.position) self.addChild(cSprite) } // create monsters to sprite for monster in world.monsters { let mSprite = MonsterSprite(pos: monster.position) mSprite.createMovement() self.addChild(mSprite) } //Floor, so the character doesn't get lost let floor = FloorSprite() self.addChild(floor) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
true
ffd209c899b2b9a8585404b40e8aee2f55b0be3a
Swift
janodev/BoardSpike
/Modules/Remote/Networking/Sources/Networking/Client/Resource.swift
UTF-8
1,434
3.203125
3
[]
no_license
import Foundation public struct Resource: ExpressibleByStringLiteral { public typealias StringLiteralType = String public enum HTTPMethod: String { case GET case POST case PUT case DELETE } let additionalHeaders: [String: String] let path: String let method: HTTPMethod let query: [String: String] let body: Data? public init(path: String, body: Data? = nil, additionalHeaders: [String: String] = [:], method: HTTPMethod = .GET, query: [String: String] = [:]) { self.path = path self.body = body self.additionalHeaders = additionalHeaders self.method = method self.query = query } public init?(path: String, body: [String: Any], additionalHeaders: [String: String] = [:], method: HTTPMethod = .GET, query: [String: String] = [:]) { guard let data = body.toJSONData() else { return nil } self.init(path: path, body: data, additionalHeaders: additionalHeaders, method: method, query: query) } // MARK: - ExpressibleByStringLiteral // This will let us use a string for path public init(stringLiteral value: StringLiteralType) { self.init(path: value) } }
true
c78af84855be0716360b15f18f94fad57d88e73d
Swift
Andy1994/LeetCodeSolution
/1022. Sum of Root To Leaf Binary Numbers.playground/Contents.swift
UTF-8
1,252
3.34375
3
[]
no_license
import UIKit public class TreeNode { public var val: Int public var left: TreeNode? public var right: TreeNode? public init(_ val: Int) { self.val = val self.left = nil self.right = nil } } class Solution { func sumRootToLeaf(_ root: TreeNode?) -> Int { return getLeafString(root, value: []).map { (num) in return binTodec(number: num) }.reduce(0, +) } func getLeafString(_ root: TreeNode?, value: [Int]) -> [String] { guard let root = root else { return [] } if root.left == nil && root.right == nil { return [(value + [root.val]).map{ String($0) }.joined()] } else { return getLeafString(root.left, value: value + [root.val]) + getLeafString(root.right, value: value + [root.val]) } } func binTodec(number num: String) -> Int { var sum: Int = 0 for c in num { let str = String(c) sum = sum * 2 + Int(str)! } return sum } } let node1 = TreeNode(1) let node2 = TreeNode(0) let node3 = TreeNode(0) let node4 = TreeNode(1) node1.left = node2 node2.left = node3 node2.right = node4 Solution().sumRootToLeaf(node1)
true
d2e7a25fb38699a2dcf52292428fe29022831a18
Swift
ThallesAraujo/SwiftCS193P
/Cassini/Cassini/ImageViewController.swift
UTF-8
3,263
3.140625
3
[]
no_license
// // ImageViewController.swift // Cassini // // Created by Thalles Araújo on 30/09/19. // Copyright © 2019 Thalles Araújo. All rights reserved. // import UIKit class ImageViewController: UIViewController, UIScrollViewDelegate { var imageURL: URL? { didSet { image = nil //Checa se já existe uma tela sendo apresentada if view.window != nil{ fetchImage() } } } private var image: UIImage? { get{ return imageView.image }set{ imageView.image = newValue imageView.sizeToFit() scrollView.contentSize = imageView.frame.size //spinner.stopAnimating() //Caso houvesse um spinner, esse seria o melhor lugar para este código, //pois não se desejaria que o spinner parasse caso o usuário voltasse uma tela //e uma nova imagem fosse requisitada (multithreading) } } @IBOutlet weak var scrollView: UIScrollView! { didSet{ //Habilitar zoom P1 scrollView.minimumZoomScale = 1/25 scrollView.maximumZoomScale = 1.0 scrollView.delegate = self scrollView.addSubview(imageView) } } var imageView = UIImageView() private func fetchImage(){ if let url = imageURL{ //Multithreading //Spinner -> ActivityIndicator //Iniciar spinning -> spinner.startAnimating() DispatchQueue.global(qos: .userInitiated).async{ [weak self] in let urlContents = try? Data(contentsOf: url) //código de interface deve ser feito na thread main DispatchQueue.main.async { if let imageData = urlContents, url == self?.imageURL{ self?.image = UIImage(data: imageData) } } } } } override func viewDidLoad() { super.viewDidLoad() if imageURL == nil{ imageURL = DemoURLs.placebo } } //Habilitar zoom P2 func viewForZooming(in scrollView: UIScrollView) -> UIView? { return imageView } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) if imageView.image == nil{ fetchImage() } } } //no prepare(forSegue), é possível utilizar: // var destination = segue.destination // if let navcon = destination as? UINavigationController{ // destination = navcon.visibleViewController ?? navcon //} //...para desemcapsular o ViewController embutido em um NavigationController //Esse código funciona mesmo quando não se tem um NavigationController //ou, pode-se criar uma extensão: extension UIViewController{ var contents: UIViewController{ //Uma extensão desse gênero também pode ser aproveitada para resgatar //a guia atual num TabViewController, por exemplo if let navcon = self as? UINavigationController{ return navcon.visibleViewController ?? self }else{ return self } } }
true
0f75092a4f9dcd3b000ccd467f6352cd232d6bbf
Swift
Magy-Elias/HackerRank
/Algorithms/Implementation/picking-numbers.swift
UTF-8
946
3.71875
4
[]
no_license
// https://www.hackerrank.com/challenges/picking-numbers import Foundation let n = Int(readLine()!)! let numbers = readLine()!.components(separatedBy: " ").map { Int($0)! } private func pickNumbers(from array: [Int]) -> [Int] { var result: [Int] = [] for index in array.indices { var numbers: [Int] = [array[index]] for secondIndex in array.indices { if index != secondIndex, abs(array[index] - array[secondIndex]) <= 1 { var numberFits = true for number in numbers { if abs(number - array[secondIndex]) > 1 { numberFits = false } } if numberFits { numbers.append(array[secondIndex]) } } } result = numbers.count > result.count ? numbers : result } return result } print(pickNumbers(from: numbers).count)
true
49a5f5674467388d3b39470e78d26d20cd21ad3a
Swift
auto234875/RealNews
/LicenseCell.swift
UTF-8
1,688
2.59375
3
[]
no_license
// // LicenseCell.swift // Real News // // Created by PC on 4/19/17. // Copyright © 2017 PC. All rights reserved. // import Foundation import UIKit class LicenseCell:UITableViewCell{ let name = UILabel() let content = UILabel() override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) backgroundColor = UIColor.clear contentView.backgroundColor = UIColor.clear separatorInset = UIEdgeInsetsMake(0, padding.totalTextHorizontal.rawValue, 0, padding.totalTextHorizontal.rawValue) name.lineBreakMode = NSLineBreakMode.byWordWrapping name.numberOfLines = 0 name.backgroundColor = UIColor.clear content.backgroundColor = UIColor.clear content.lineBreakMode = .byWordWrapping content.numberOfLines = 0 contentView.addSubview(name) contentView.addSubview(content) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override func layoutSubviews() { super.layoutSubviews() let size = CGSize(width: contentView.bounds.width - padding.totalTextHorizontal.rawValue*2, height: .greatestFiniteMagnitude) let nameSize = name.sizeThatFits(size) let contentSize = content.sizeThatFits(size) name.frame = CGRect(x: padding.totalTextHorizontal.rawValue, y: padding.totalTextHorizontal.rawValue, width: nameSize.width, height: nameSize.height) content.frame = CGRect(x: padding.totalTextHorizontal.rawValue, y: name.frame.maxY + padding.interLabel.rawValue, width: contentSize.width, height: contentSize.height) } }
true
60e795e530cb483b97ae650d5873397f2d8a0877
Swift
sagarmusale8/Hackernews
/HackerNews/Controllers/ViewController.swift
UTF-8
5,551
2.546875
3
[]
no_license
// // ViewController.swift // HackerNews // // Created by Sagar Musale on 14/05/16. // Copyright © 2016 Sagar Musale. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableViewTopStories: UITableView! let numberOfSectionForTopStories = 1 let defaultNumberOfRows = 0 var allTopStoriesIds = NSMutableArray() var topStoriesNews = NSMutableArray() let reusbaleIdForTopStoryCell = String(TopStoryTableViewCell) let pageCount = 25 static var count = 0 override func viewDidLoad() { super.viewDidLoad() getTopStoriesData() } @IBAction func actionOnRefresh(sender: AnyObject) { self.getTopStoriesData() } // MARK: Getting top stories items func getTopStoriesData() { loadDataFromCoreData() allTopStoriesIds.removeAllObjects() NetworkManager().makeRequestWithRequestType(ProjectConstant.URL_TOP_STORIES, requestType: ProjectConstant.REQUEST_GET, withParameters: NSMutableDictionary()) { (success, response, error) in if let responseArr = response as? NSMutableArray where success{ self.allTopStoriesIds.addObjectsFromArray(responseArr as [AnyObject]) self.fetchNewsDataForPage() } } } // MARK: Loading data from CoreData func loadDataFromCoreData(){ self.topStoriesNews.removeAllObjects() let newsItems = NewsDataHandler.getAllNews() if newsItems?.count > 0{ self.topStoriesNews.addObjectsFromArray(newsItems!) self.tableViewTopStories.reloadData() } } // MARK: Fetching news for page items func fetchNewsDataForPage() { let allIds = getAllIdsForStories() for index in 0...allTopStoriesIds.count-1{ if let itemId = allTopStoriesIds.objectAtIndex(index) as? Int { // Fetching data if only it is not saved if !allIds.containsObject(itemId){ let urlStr = ProjectConstant.URL_NEWS_DETAILS.stringByReplacingOccurrencesOfString(ProjectConstant.STR_ITEM_ID, withString: String(itemId)) ViewController.count += 1 NetworkManager().makeRequestWithRequestType(urlStr, requestType: ProjectConstant.REQUEST_GET, withParameters: NSMutableDictionary(), withCompletion: { (success, response, error) in if let responseVal = response as? NSDictionary where success{ if let newsItem = NewsDataHandler.saveNewsObject(responseVal){ self.topStoriesNews.addObject(newsItem) } } ViewController.count -= 1 // Loading data if 25 or all items fetchedytrert if (ViewController.count == 0) || (self.topStoriesNews.count % self.pageCount == 0){ self.loadDataFromCoreData() } }) } } } } // Getting all ids func getAllIdsForStories()->NSArray{ let allIds = NSMutableArray() for newsItem in topStoriesNews{ if let thisNews = newsItem as? News{ allIds.addObject(thisNews.id!) } } return allIds } // MARK: TableView DataSource and Delegate Methods func numberOfSectionsInTableView(tableView: UITableView) -> Int { return numberOfSectionForTopStories } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return topStoriesNews.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { if let cell = tableView.dequeueReusableCellWithIdentifier(reusbaleIdForTopStoryCell) as? TopStoryTableViewCell{ cell.setupUIProperties() if let news = topStoriesNews.objectAtIndex(indexPath.row) as? News{ if let title = news.title{ cell.lblHeading.text = title } if let score = news.score{ cell.btnScore.setTitle(String(score), forState: .Normal) } if let time = news.time{ cell.lblTimeString.text = NSDate.stringFromUnixTime(time) } if let writer = news.by{ cell.lblBy.text = "by " + writer } } return cell } return UITableViewCell() } func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return UITableViewAutomaticDimension } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == ProjectConstant.SEGUE_NEWS_DETAILS, let destination = segue.destinationViewController as? NewsDetailsViewController { if let cell = sender as? UITableViewCell, let indexPath = tableViewTopStories.indexPathForCell(cell) { if let newsItem = topStoriesNews[indexPath.row] as? News{ destination.newsItem = newsItem } } } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
true
2d8fb340cc0041e059450bafa803eb15661f2476
Swift
blude/BludeRampage
/Engine/Rotation.swift
UTF-8
1,382
3.9375
4
[]
no_license
// // Rotation.swift // Engine // // Created by Saulo Pratti on 06.05.20. // Copyright © 2020 Pratti Design. All rights reserved. // public struct Rotation { var m1, m2, m3, m4: Double } /** A 2x2 matrix contains 4 numbers, hence the four parameters. The `m[x]` naming is conventional, but unless you are well-versed with linear algebra those parameters won't mean a whole lot. Let's add an initializer with slightly more ergonomic parameters: This initializer takes the sine and cosine of a given angle and produces a matrix representing a rotation by that angle. We already said that we can't (easily) use the `sin` and `cos` functions inside the engine itself, but that's OK because we'll we be doing that part in the platform layer. */ public extension Rotation { init(sine: Double, cosine: Double) { self.init(m1: cosine, m2: -sine, m3: sine, m4: cosine) } } /** Finally, we'll add a function to apply the rotation to a vector. This feels most natural to write as an extension method on `Vector` itself, but we'll put that extension in the `Rotation.swift` file because it makes more sense from a grouping perspective. */ public extension Vector { func rotated(by rotation: Rotation) -> Vector { return Vector( x: x * rotation.m1 + y * rotation.m2, y: x * rotation.m3 + y * rotation.m4 ) } }
true
8bb8f626c22c9e428d815939795a11d77195b9c6
Swift
atehrani21/Nali
/IOS_CODE/Nali/Nali/NetworkInterface.swift
UTF-8
4,744
3.0625
3
[]
no_license
// // NetworkInterface.swift // Nali // // Created by Evan Knox on 2016-11-12. // Copyright © 2016 parchican. All rights reserved. // import Foundation import Alamofire import CoreLocation import MapKit import Foundation struct Position{ var x = Float() var y = Float() } struct User { var id = Int() var firstName = String() var lastName = String() var pos = Position() var userName = String() } class NetworkClient{ func createUser(usr: User){ //This function creates an account/Database record of a person using the first,last names, as well as id let parameters: Parameters = [ "first_name": usr.firstName, "last_name": usr.lastName, "user_name":usr.userName ] // All three of these calls are equivalent Alamofire.request("https://nali.herokuapp.com/addUser", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } } func updatePosition(usr: User){ //This function will update a users current position //Pass in a User struct with all fields full //This function creates an account/Database record of a person using the first,last names, as well as id let parameters: Parameters = [ "user_name": usr.userName, "x":usr.pos.x, "y":usr.pos.y ] // All three of these calls are equivalent Alamofire.request("https://nali.herokuapp.com/updatePosition", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } } func getFriendsPosition(friend:String) ->CLLocation{ //Given a user, get his friends location and return that back to him //This function will update a users current position //Pass in a User struct with all fields full //This function creates an account/Database record of a person using the first,last names, as well as id let parameters: Parameters = [ "user_name": friend, ] // All three of these calls are equivalent Alamofire.request("https://nali.herokuapp.com/requestFriend", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } var dummyLocation: CLLocation = CLLocation(latitude: 37.3307498, longitude: -122.03054302) return dummyLocation } func addFriend(user: User, userNm: String){ } func contactExists(contact:String)-> Bool{ //Given a user, get his friends location and return that back to him //This function will update a users current position //Pass in a User struct with all fields full //This function creates an account/Database record of a person using the first,last names, as well as id let parameters: Parameters = [ "user_name": contact, ] // All three of these calls are equivalent Alamofire.request("https://nali.herokuapp.com/checkFriendRequest", method: .post, parameters: parameters, encoding: JSONEncoding.default).responseJSON { response in print(response.request) // original URL request print(response.response) // HTTP URL response print(response.data) // server data print(response.result) // result of response serialization if let JSON = response.result.value { print("JSON: \(JSON)") } } return true } }
true
4d04d79a9e3acfc31817935aaac4ad82562c7e40
Swift
OliPaul/online_bank_ios
/OnlineBank/transaction/TransactionView.swift
UTF-8
854
2.8125
3
[]
no_license
// // TransactionView.swift // OnlineBank // // Created by Paul Olivier on 27/06/2021. // import SwiftUI struct TransactionView: View { @State private var transactions = [Transaction]() var body: some View { VStack { List(transactions) { transaction in TransactionRowView(transaction: transaction) } .onAppear() { GetTransactionsList().execute() { transactions in let transactionListReversed = transactions.reversed() let transactionList = Array(transactionListReversed) self.transactions = transactionList } } } } } struct TransactionView_Previews: PreviewProvider { static var previews: some View { TransactionView() } }
true
dc53846db25b9565ad118ff9ac1084b05714d5b5
Swift
JavierFo/SpaceApps_ScanningForLifeforms
/SpeciesFinder/SpeciesFinder/SpeciesAPIs.swift
UTF-8
1,264
2.6875
3
[]
no_license
// // SpeciesAPIs.swift // SpeciesFinder // // Created by Javier Ferrer Ortega on 04/10/20. // Copyright © 2020 BiohackersSpaceApps. All rights reserved. // import Foundation import UIKit func imageServer(latitude: [Float], longitude: [Float], completionHandler: @escaping () -> Void) { DispatchQueue.main.async { UIApplication.shared.isNetworkActivityIndicatorVisible = true } let session = URLSession.shared let eventsTrackerApiURL = "https://api.nasa.gov/planetary/earth/imagery?lon=100.75&lat=1.5&date=2014-02-01&api_key=DEMO_KEY" let url = URL(string: eventsTrackerApiURL)! let apiKey_ = "hAV1x26HuzQ0Cl6GK2vio4U9LVsM9nuckCSSgP2t" let request = URLRequest(url: url) let task = session.dataTask(with: request) { (data, response, error) -> Void in // let jsonDecoder = JSONDecoder() // if let data = data, let productList = try? jsonDecoder.decode([IngredientsList].self, from: data){ // completion(productList) // } else if let requestError = error { // print("Error fetching interesting photos: \(requestError)") // } else { // print("Unexpected error with the request") // } } task.resume() }
true
1a2e40ebac61aca63f6e6bf8c8fbc15ed9e1b3f2
Swift
martex07/AverageTravelIsNotForMe
/AverageTravelIsNotForMe/SecondView.swift
UTF-8
1,036
2.953125
3
[]
no_license
// // SecondView.swift // AverageTravelIsNotForMe // // Created by Marta Gołaszewska on 30.04.21. // import SwiftUI struct SecondView: View { var body: some View { ZStack{ Color(red: 0.74, green: 0.76, blue: 0.78) .ignoresSafeArea() VStack{ Image("travel") .resizable() .aspectRatio(contentMode: .fit) .clipShape(Circle()) Text("Average is not for me!") .font(Font.custom("Lobster-Regular", size: 40)) RoundedRectangle(cornerRadius: 30) .fill(Color.white) .frame(height: 50) .overlay(HStack{ Image("phone.fill") Text("+ 0157405048") .bold() }) } } } } struct SecondView_Previews: PreviewProvider { static var previews: some View { SecondView() } }
true
f92bedf54a4dc31acf8bac557646c8fbb3f4e6d7
Swift
Daniel1of1/Monyo
/Incubating Libraries - WIP/Monzo/Decoder/Decoder.swift
UTF-8
999
2.6875
3
[]
no_license
// // Decoder.swift // Monyo // // Created by Daniel Haight on 21/05/2019. // Copyright © 2019 Daniel Haight. All rights reserved. // import Foundation private let jsonDecoder = JSONDecoder() func decoder<T>(for type: T.Type) -> ((Data,URLResponse)) -> Result<T,Swift.Error> where T: Decodable { return { response in guard let httpResponse = response.1 as? HTTPURLResponse else { return .failure(MonzoError.unknown(response)) } switch httpResponse.statusCode { case 200: return Result{ try jsonDecoder.decode(T.self, from: response.0) } default: let res = Result{ try jsonDecoder.decode(ErrorResponse.self, from: response.0) } switch res { case .success(let errorResponse): return Result<T,Swift.Error>.failure(MonzoError.init(errorResponse)) case .failure: return Result<T,Swift.Error>.failure(MonzoError.unknown(response)) } } } }
true
217d961c161f459964554a5be2000d3cf5d0f77f
Swift
sengeiou/AR-pylos
/AR-pylos/Core/Server/ServerMessage/GameConfigServerPayload.swift
UTF-8
1,004
3
3
[ "MIT" ]
permissive
// // GameConfigServerPayload.swift // AR-pylos // // Created by Vitalii Poponov on 6/12/20. // Copyright © 2020 Vitalii Poponov. All rights reserved. // import Foundation class WrappedMapCell: Codable { var item: Ball? var child: WrappedMapCell? init(cell: MapCellProtocol) { self.item = cell.item as? Ball if let child = cell.child { self.child = WrappedMapCell(cell: child) } } subscript(z: Int) -> WrappedMapCell? { if z == 0 { return self } return child?[z - 1] } } struct GameConfigServerPayload: ServerMessagePayloadProtocol { var player: Player var map: [[WrappedMapCell]] var stashedItems: [Player: [Ball]] init(player: Player, map: [[MapCellProtocol]], stashedItems: [Player: [MapItemProtocol]]) { self.player = player self.map = map.map({ $0.map({ WrappedMapCell(cell: $0) })}) self.stashedItems = stashedItems as? [Player: [Ball]] ?? [:] } }
true
db710687f802d2d486a4dbba797809d748f4f5e3
Swift
carlosefonseca/MapApp
/Map/UIKitExtensions/UIImage+Average.swift
UTF-8
1,668
2.625
3
[]
no_license
// // UIImage+Average.swift // Map // // Created by carlos.fonseca on 22/03/2020. // Copyright © 2020 carlosefonseca. All rights reserved. // import UIKit extension UIImage { var averageColor: UIColor? { guard let inputImage = CIImage(image: self) else { return nil } let extentVector = CIVector(x: inputImage.extent.origin.x, y: inputImage.extent.origin.y, z: inputImage.extent.size.width, w: inputImage.extent.size.height) guard let filter = CIFilter(name: "CIAreaAverage", parameters: [kCIInputImageKey: inputImage, kCIInputExtentKey: extentVector]) else { return nil } guard let outputImage = filter.outputImage else { return nil } var bitmap = [UInt8](repeating: 0, count: 4) let context = CIContext() context.render(outputImage, toBitmap: &bitmap, rowBytes: 4, bounds: CGRect(x: 0, y: 0, width: 1, height: 1), format: .RGBA8, colorSpace: nil) return UIColor(red: CGFloat(bitmap[0]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[2]) / 255, alpha: CGFloat(bitmap[3]) / 255) } var averageColor2: UIColor? { UIGraphicsBeginImageContext(CGSize(width: 1, height: 1)) defer { UIGraphicsEndImageContext() } let ctx = UIGraphicsGetCurrentContext()! ctx.interpolationQuality = .medium self.draw(in: CGRect(x: 0, y: 0, width: 1, height: 1), blendMode: .copy, alpha: 1) let bitmap: [UInt8] = Array(UnsafeBufferPointer(start: ctx.data!.bindMemory(to: UInt8.self, capacity: 4), count: 4)) return UIColor(red: CGFloat(bitmap[2]) / 255, green: CGFloat(bitmap[1]) / 255, blue: CGFloat(bitmap[0]) / 255, alpha: 1) } }
true
cc80ca17ec68e81712445c16e68e9fe7ed45b7ae
Swift
Hues2/Apikemon
/PokemonCardsFirstTest/Models/SetsManager.swift
UTF-8
2,464
3.109375
3
[]
no_license
// // SetsManager.swift // PokemonCardsFirstTest // // Created by Greg Ross on 19/03/2021. // import UIKit struct SetsManager{ let apiUrl = "https://api.pokemontcg.io/v2/sets" //This method fetches all the sets from the API //Result is an escaping closure, which means that it waits for the function to finish //to "set" the result. func fetchSets(result : @escaping ([SetOfCards]?, Error?) -> Void){ //Create url if let url = URL(string: apiUrl){ //Create the URLRequest to use my API key var request = URLRequest(url: url) //Add my API key request.addValue(Props.apiKey, forHTTPHeaderField: "X-Api-Key") //Create the session let session = URLSession.shared //Create the task using the request let task = session.dataTask(with: request) { (data, response, error) in //If there is an error print it and cancel the closure if let e = error{ print(e) result(nil, error) return }else{ //If the data isn't nil, then call the parse JSON method if let safeData = data{ var listOfSets : [SetOfCards] = [] if let dataFromApi = parseSetJSON(safeData : safeData){ for set in dataFromApi.data{ let id = set.id let name = set.name let logo = set.images.logo let set = SetOfCards(id: id, name: name, logo: logo) listOfSets.append(set) } result(listOfSets, nil) }else{ result(nil, error) } }else{ result(nil, error) } } } task.resume() } } func parseSetJSON(safeData : Data) -> SetData?{ do{ let decoder = JSONDecoder() let decodedData = try decoder.decode(SetData.self, from: safeData) return decodedData }catch{ print(error) return nil } } }
true
1883f18e07b47bf8cd9414ea1617cf66af3a66cb
Swift
jitendrahome1/ByjuAssignment
/Byju'sAssignment/Controller/NewsDetailsViewController.swift
UTF-8
2,151
2.59375
3
[]
no_license
// // NewDetailsViewController.swift // ByjuAssignment // // Created by Jitendra Kumar Agarwal on 26/07/19. // Copyright © 2019 Jitendra Kumar Agarwal. All rights reserved. // import UIKit class NewsDetailsViewController: UIViewController { var newsDetailsModel: NewsHeadLines! @IBOutlet weak var tableNewsDetails: UITableView! override func viewDidLoad() { super.viewDidLoad() self.tableNewsDetails.rowHeight = UITableView.automaticDimension tableNewsDetails.addSubview(backButton) // Do any additional setup after loading the view. } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) navigationController?.setNavigationBarHidden(true, animated: animated) } lazy var backButton: UIButton = { var aButton: UIButton = UIButton(frame: CGRect(x: 13, y: 29, width: 35, height:35)) aButton.layer.cornerRadius = 0.5 * aButton.bounds.size.width aButton.clipsToBounds = true aButton.backgroundColor = UIColor.darkGray aButton.alpha = 0.3 aButton.addTarget(self, action:#selector(self.backAction), for: .touchUpInside) aButton.setImage(#imageLiteral(resourceName: "back"), for: .normal) return aButton }() } // MARK:- User Define extension NewsDetailsViewController { @objc func backAction(sender:UIButton) { self.navigationController?.popViewController(animated: true) } } // MARK:- Tableview Delagte and Datascource. extension NewsDetailsViewController: UITableViewDelegate, UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 1 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "NewsDetailsHeaderCell") as! NewsDetailsHeaderCell cell.datasource = newsDetailsModel as AnyObject return cell } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableView.automaticDimension } }
true
63e3f3b9460abe692d796d25df7aa0b8b824a9b9
Swift
Campus-Quora/Campus-Quora
/TheCampusApp/View Controllers/TextEditorViewController/CustomToolBar.swift
UTF-8
19,678
2.65625
3
[]
no_license
// // CustomToolBar.swift // TheCampusApp // // Created by Yogesh Kumar on 29/09/19. // Copyright © 2019 Harsh Motwani. All rights reserved. // import UIKit // MARK:- ToolBarButton class ToolBarButton: UIButton{ init(imageName: String) { super.init(frame: .zero) let size = CGSize(width: 24, height: 24) let image = UIImage(named: imageName)?.resizeImage(size: size).withRenderingMode(.alwaysTemplate) self.setImage(image, for: .normal) self.imageView?.contentMode = .top tintColor = selectedTheme.primaryTextColor } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } } // MARK:- Custom ToolBar class CustomToolBar: UIView{ override var intrinsicContentSize: CGSize{ return CGSize.zero } var leftItems = [UIButton]() var rightItems = [UIButton]() var edgeInsets: UIEdgeInsets? var toolSpacing: CGFloat? var bottomConstraint: NSLayoutConstraint! = nil var leadingConstraint: NSLayoutConstraint! = nil var backgroundView = UIView() var topBorder : UIView = { let view = UIView() view.backgroundColor = .gray return view }() func layout(){ // Layout Left Items self.backgroundColor = .clear addSubview(backgroundView) backgroundView.anchor(top: topAnchor, bottom: bottomAnchor, left: leadingAnchor, right: trailingAnchor, paddingTop: 10) var leftConstraint: NSLayoutXAxisAnchor if #available(iOS 11.0, *) { leftConstraint = self.safeAreaLayoutGuide.leadingAnchor } else { leftConstraint = self.leadingAnchor } var leftSpacing = self.edgeInsets?.left ?? 0 for tool in leftItems{ addSubview(tool) tool.anchor(top: backgroundView.topAnchor, bottom: bottomAnchor, paddingTop: edgeInsets?.top, paddingBottom: edgeInsets?.bottom) let toolLeftConstraint = tool.leadingAnchor.constraint(equalTo: leftConstraint, constant: leftSpacing) toolLeftConstraint.isActive = true if(leadingConstraint == nil){ leadingConstraint = toolLeftConstraint } leftConstraint = tool.trailingAnchor leftSpacing = toolSpacing ?? 0 } // Layout Right Items var rightConstraint: NSLayoutXAxisAnchor if #available(iOS 11.0, *) { rightConstraint = self.safeAreaLayoutGuide.trailingAnchor } else { rightConstraint = self.trailingAnchor } var rightSpacing = self.edgeInsets?.right for tool in rightItems{ addSubview(tool) tool.anchor(top: backgroundView.topAnchor, bottom: bottomAnchor, right: rightConstraint, paddingTop: edgeInsets?.top, paddingBottom: edgeInsets?.bottom, paddingRight: rightSpacing) rightConstraint = tool.leadingAnchor rightSpacing = toolSpacing } // Top Border addSubview(topBorder) topBorder.anchor(top: backgroundView.topAnchor, left: leadingAnchor, right: trailingAnchor, paddingTop: 0, paddingLeft: 0, paddingRight: 0, height: 1) } } // MARK:- Text Format Options class TextFormatOptionsView: UIView, UITextViewDelegate{ // MARK:- Button Types enum ButtonType: String{ case bold = "Bold" case italics = "Italics" case underlined = "Underlined" case unorderedList = "UnorderedList" case orderedList = "OrderedList" } // MARK:- Data Members var itemPadding: CGFloat = 10 let baseFontSize: CGFloat = 16 var unselectedColor: UIColor! = nil lazy var font = UIFont.systemFont(ofSize: baseFontSize) lazy var currentFont = font lazy var bulletString = NSAttributedString(string: "\u{2022} ", attributes: [.font: currentFont]) lazy var spaceBulletString = NSAttributedString(string: "\n\u{2022} ", attributes: [.font: currentFont]) static let backwardDirection = UITextDirection(rawValue: UITextStorageDirection.backward.rawValue) lazy var bulletPointParagraphStyle: NSMutableParagraphStyle = { let paragraph = NSMutableParagraphStyle() paragraph.headIndent = NSString(string: "\u{2022}").size(withAttributes: [.font: currentFont]).width return paragraph }() var isUnderlined = false var isUnorderedListActive = false{ didSet{ if(oldValue == isUnorderedListActive){ return } unorderedListButton.tintColor = isUnorderedListActive ? selectedAccentColor.primaryColor: selectedTheme.primaryTextColor } } var isOrderedListActive = false{ didSet{ if(oldValue == isOrderedListActive){ return } orderedListButton.tintColor = isOrderedListActive ? selectedAccentColor.primaryColor: selectedTheme.primaryTextColor orderedListItemNumber = 0 } } var orderedListItemNumber = 0 var dataSource: UITextView? // MARK:- UI Elements let boldButton = ToolBarButton(imageName: ButtonType.bold.rawValue) let italicsButton = ToolBarButton(imageName: ButtonType.italics.rawValue) let underlinedButton = ToolBarButton(imageName: ButtonType.underlined.rawValue) let orderedListButton = ToolBarButton(imageName: ButtonType.orderedList.rawValue) let unorderedListButton = ToolBarButton(imageName: ButtonType.unorderedList.rawValue) // MARK:- Setup Mehods func initialise(_ unselectedColor: UIColor){ layout() setupActions() setupColors(unselectedColor) } func layout(){ let scrollView = UIScrollView() scrollView.showsHorizontalScrollIndicator = false let stackView = UIStackView(arrangedSubviews: [boldButton, italicsButton, underlinedButton, orderedListButton, unorderedListButton]) stackView.axis = .horizontal stackView.distribution = .fillEqually let numberOfItems = stackView.arrangedSubviews.count let stackWidth: CGFloat = CGFloat((numberOfItems * 30)) + CGFloat(numberOfItems + 1) * itemPadding addSubview(scrollView) scrollView.addSubview(stackView) scrollView.anchor(top: topAnchor, left: leadingAnchor) scrollView.widthAnchor.constraint(equalTo: widthAnchor, multiplier: 1).isActive = true scrollView.heightAnchor.constraint(equalTo: heightAnchor, multiplier: 1).isActive = true stackView.anchor(top: scrollView.topAnchor, bottom: bottomAnchor, left: scrollView.leadingAnchor, right: scrollView.trailingAnchor, width: stackWidth) } func setupActions(){ boldButton.addTarget(self, action: #selector(handleBold), for: .touchUpInside) italicsButton.addTarget(self, action: #selector(handleItalics), for: .touchUpInside) underlinedButton.addTarget(self, action: #selector(handleUnderlined), for: .touchUpInside) orderedListButton.addTarget(self, action: #selector(handleOrderedList), for: .touchUpInside) unorderedListButton.addTarget(self, action: #selector(handleUnorderedList), for: .touchUpInside) } func setupColors(_ color: UIColor){ self.unselectedColor = color [boldButton,italicsButton,underlinedButton,orderedListButton,unorderedListButton].forEach { (button) in button.tintColor = color } } // MARK:- Button Handlers @objc func handleBold(){ guard let textView = dataSource else {return} let range = textView.selectedRange if(range.length == 0){ currentFont = currentFont.bold() textView.typingAttributes[.font] = currentFont return } textView.attributedText.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired) { (attributes, range, stop) in if let font = attributes[.font] as? UIFont{ textView.textStorage.addAttributes([NSAttributedString.Key.font: font.bold()], range: range) } } } @objc func handleItalics(){ guard let textView = dataSource else {return} let range = textView.selectedRange if(range.length == 0){ currentFont = currentFont.italic() textView.typingAttributes[.font] = currentFont return } textView.attributedText.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired) { (attributes, range, stop) in if let font = attributes[.font] as? UIFont{ textView.textStorage.addAttributes([NSAttributedString.Key.font: font.italic()], range: range) } } } @objc func handleUnderlined(){ guard let textView = dataSource else {return} let range = textView.selectedRange if(range.length == 0){ if(isUnderlined){ textView.typingAttributes.removeValue(forKey: .underlineStyle) } else{ textView.typingAttributes[.underlineStyle] = NSUnderlineStyle.single.rawValue } isUnderlined = !isUnderlined return } textView.attributedText.enumerateAttributes(in: range, options: .longestEffectiveRangeNotRequired) { (attributes, range, stop) in if let _ = attributes[.underlineStyle] as? NSUnderlineStyle.RawValue{ textView.textStorage.removeAttribute(.underlineStyle, range: range) } else{ textView.textStorage.addAttributes([.underlineStyle: NSUnderlineStyle.single.rawValue], range: range) } } } @objc func handleOrderedList(){ isOrderedListActive = !isOrderedListActive if(!isOrderedListActive){ removeOrderedList() return } if(isUnorderedListActive){ isUnorderedListActive = false removeUnorderedList() } orderedListHelper() } func orderedListHelper(){ guard let textView = dataSource else {return} let currentPosition = textView.selectedTextRange let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .line, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ var location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) var range = NSRange(location: location, length: 0) orderedListItemNumber += 1 var length = 3 if(orderedListItemNumber > 9){length += 1} if(orderedListItemNumber > 99){length += 1} if(orderedListItemNumber > 999){length += 1} if(location > 0){ var prevCharRange = NSRange(location: location, length: 1) var prevTextRange = textView.toTextRange(NSRange: prevCharRange) var character = textView.text(in: prevTextRange) if(character == "\n"){ let number = NSAttributedString(string: "\n\(orderedListItemNumber). ", attributes: [.font: currentFont]) textView.textStorage.replaceCharacters(in: prevCharRange , with: number) textView.offsetSelection(by: length) return } else{ prevCharRange = NSRange(location: location - 1, length: 1) prevTextRange = textView.toTextRange(NSRange: prevCharRange) character = textView.text(in: prevTextRange) if(character != "\n"){ // Fixes text wrapping issue let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .paragraph, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) range = NSRange(location: location, length: 0) } } } } let number = NSAttributedString(string: "\(orderedListItemNumber). ", attributes: [.font: currentFont]) textView.textStorage.replaceCharacters(in: range , with: number) textView.offsetSelection(by: length) } } func removeOrderedList(){ guard let textView = dataSource else {return} let currentPosition = textView.selectedTextRange let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .paragraph, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ let location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) var length = 3 if(orderedListItemNumber > 9){length += 1} if(orderedListItemNumber > 99){length += 1} if(orderedListItemNumber > 999){length += 1} let range = NSRange(location: location, length: length) let empty = NSAttributedString(string: "") let currentLoc = textView.selectedRange.location if(currentLoc < length){ length = currentLoc } else if(currentLoc + length > textView.textStorage.length){ length = textView.textStorage.length - textView.selectedRange.location } textView.textStorage.replaceCharacters(in: range , with: empty) textView.offsetSelection(by: -length) } } @objc func handleUnorderedList(){ isUnorderedListActive = !isUnorderedListActive if(!isUnorderedListActive){ removeUnorderedList() return } if(isOrderedListActive){ isOrderedListActive = false removeOrderedList() } unorderedListHelper() } func unorderedListHelper(){ guard let textView = dataSource else {return} let currentPosition = textView.selectedTextRange let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .line, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ var location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) var range = NSRange(location: location, length: 0) if(location > 0){ var prevCharRange = NSRange(location: location, length: 1) var prevTextRange = textView.toTextRange(NSRange: prevCharRange) let character = textView.text(in: prevTextRange) if(character == "\n"){ textView.textStorage.replaceCharacters(in: prevCharRange, with: spaceBulletString) textView.offsetSelection(by: 2) return } else{ prevCharRange = NSRange(location: location - 1, length: 1) prevTextRange = textView.toTextRange(NSRange: prevCharRange) let character = textView.text(in: prevTextRange) if(character != "\n"){ // Fixes text wrapping issue let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .paragraph, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) range = NSRange(location: location, length: 0) } } } } textView.textStorage.replaceCharacters(in: range , with: bulletString) textView.offsetSelection(by: 2) } } func removeUnorderedList(){ guard let textView = dataSource else {return} let currentPosition = textView.selectedTextRange let startOfLine = textView.tokenizer.position(from: currentPosition!.start, toBoundary: .paragraph, inDirection: TextFormatOptionsView.backwardDirection) if let startOfLine = startOfLine{ let location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) var length = 2 let range = NSRange(location: location, length: length) let empty = NSAttributedString(string: "") let currentLoc = textView.selectedRange.location if(currentLoc < length){ length = currentLoc } else if(currentLoc + length > textView.textStorage.length){ length = textView.textStorage.length - textView.selectedRange.location } textView.textStorage.replaceCharacters(in: range , with: empty) textView.offsetSelection(by: -length) } } // func increaseBulletLevel(_ level: Int){ // guard let textView = dataSource else {return} // let currentPosition = textView.selectedTextRange!.start // let textDirection = UITextDirection(rawValue: UITextStorageDirection.backward.rawValue) // let startOfLine = textView.tokenizer.position(from: currentPosition, toBoundary: .paragraph, inDirection: textDirection)! // let location = textView.offset(from: textView.beginningOfDocument, to: startOfLine) + (level - 1)*4 // let length = 2 // let range = NSRange(location: location, length: length) // textView.textStorage.deleteCharacters(in: range) // } // Delegate Functions func textViewDidChange(_ textView: UITextView){} func changeText(_ textView: UITextView, _ text: String, _ deletedText: String?, _ isDeleted: Bool)->Bool{ if(!isDeleted && isUnorderedListActive && text == "\n"){ textView.textStorage.insert(spaceBulletString, at: textView.selectedRange.location) textView.offsetSelection(by: 3) return false } if(!isDeleted && isOrderedListActive && text == "\n"){ orderedListItemNumber += 1 let number = NSAttributedString(string: "\n\(orderedListItemNumber). ", attributes: [.font: currentFont]) textView.textStorage.insert(number, at: textView.selectedRange.location) textView.offsetSelection(by: 4) return false } else if(isDeleted && deletedText! == "\u{2022}"){ isUnorderedListActive = false } return true } } extension UITextView{ func offsetSelection(by offset: Int){ if let range = selectedTextRange{ let newStart = position(from: range.start, offset: offset)! let newEnd = position(from: range.end, offset: offset)! self.selectedTextRange = textRange(from: newStart, to: newEnd) } } func toTextRange(NSRange range: NSRange)->UITextRange{ let newStart = position(from: beginningOfDocument, offset: range.location)! let newEnd = position(from: newStart, offset: range.length)! return textRange(from: newStart, to: newEnd)! } } // Issues:- // Additional Required Functionality:- // 1. Set the tintcolor of button based on attributes of text. Eg:- make tint blue when text is bold // 2. Add 3 levels of heading // Optional Features // 1. Add quote // 2. Add code
true
9eaa1598b4313f83710ca7a6aac949c7971f3609
Swift
dmitriyborodko/UrgentSnack
/UrgentSnack/UrgentSnack/Model/VenueDetails/BestPhotoRequest.swift
UTF-8
519
2.65625
3
[]
no_license
import UIKit struct BestPhotoRequest: FourSquareRequest { var photo: VenueDetails.BestPhoto func prepare(context: FourSquareContext) throws -> URLRequest { return try URL(string: photo.asString) .restoreNil { throw "incorrect photo prefix \(photo.asString)".mayDay } .replace { URLRequest(url: $0) } } func parse(data: Data) throws -> UIImage { try UIImage(data: data) .restoreNil { throw "invalid image data at \(photo.asString)".mayDay } } }
true
e9e15126cea60daa1df4f25b0309d67058aced29
Swift
redmilk/TrueFalseService
/OneMoreInstagramKFR/DataSource.swift
UTF-8
7,710
2.640625
3
[]
no_license
// // DataSource.swift // OneMoreInstagramKFR // // Created by Artem on 4/29/17. // Copyright © 2017 ApiqA. All rights reserved. // import Foundation import FirebaseStorage import FirebaseDatabase import UIKit.UIImage import UIKit.UIImageView import Kingfisher extension String { func toBool() -> Bool? { switch self { case "True", "true", "yes", "1": return true case "False", "false", "no", "0": return false default: return nil } } } // STACK struct Stack<Element> { var items = [Element]() mutating func push(_ item: Element) { items.append(item) } mutating func pop() -> Element { return items.removeLast() } } extension MutableCollection where Index == Int { /// Shuffle the elements of `self` in-place. mutating func shuffle() { // empty and single-element collections don't shuffle if count < 2 { return } for i in startIndex ..< endIndex - 1 { let j = Int(arc4random_uniform(UInt32(endIndex - i))) + i if i != j { swap(&self[i], &self[j]) } } } } extension Collection { /// Return a copy of `self` with its elements shuffled func shuffled() -> [Iterator.Element] { var list = Array(self) list.shuffle() return list } } /////////////////////////////////////////////// //*****************CLASS*********************// class DataSource { fileprivate var questionStack = Stack<TheQuestion>() fileprivate var questions = [TheQuestion]() fileprivate let downloader = ImageDownloader(name: "DOWNLOADER") fileprivate let cache = ImageCache(name: "CACHE") fileprivate var questionTypeDataBaseName = String() //*************************************// complition handler var onGetQuestionStackComplete: ((_ questionStack: Stack<TheQuestion>, _ questionArray: [TheQuestion]) -> Void)? //************************************// retrieving source var retrieveFrom: String = "mult_test" //************************************// init() { downloader.downloadTimeout = 30 cache.maxCachePeriodInSecond = -1 cache.maxDiskCacheSize = 0 AppDelegate.instance().showActivityIndicator() } func getQuestionsFromServerOrCache() { ref.child(retrieveFrom).queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in let retrieved = snapshot.value as! [String : AnyObject] print("TOTAL COUNT * = \(retrieved.count)") self.retrieveOrDownloadQuestions(totalCount: retrieved.count) }) ref.removeAllObservers() } fileprivate func retrieveOrDownloadQuestions(totalCount: Int) { print("TOTAL COUNT ** = \(totalCount)") var questionsCount = totalCount ref.child(retrieveFrom).queryOrderedByKey().observeSingleEvent(of: .value, with: { (snapshot) in self.questions.removeAll() let questions = snapshot.value as! [String : AnyObject] for(_, value) in questions { if let retrievedQuestion = value as? [String : Any] { if let questionHeader = retrievedQuestion["questionHeader"] as? String, let questionAnswer = retrievedQuestion["questionAnswer"] as? String, let pathToImage = retrievedQuestion["pathToImage"] as? String, let _ = retrievedQuestion["questionKey"] as? String { let urlToImage = URL(string: pathToImage)! /*** Try to retrieve from Cache ****/ self.cache.retrieveImage(forKey: pathToImage, options: nil, completionHandler: { (image_, cacheType) in if let image_ = image_ { print("EXIST in cache.") /*** if image in Cach make new TheQuestion object ****/ let question = TheQuestion(image_, questionHeader, questionAnswer) self.questions.append(question) self.questionStack.push(question) questionsCount > 2 ? questionsCount -= 1 : self.cacheRetrieveComplete() } else { /*** No Cached ****/ print("NOT exist in cache.") /*** if no in Cache we download ****/ self.downloader.downloadImage(with: urlToImage, options: nil, progressBlock: nil, completionHandler: { (image, error, url, originalData) in if error != nil { print(error!.localizedDescription) self.noInternetConnectionError() /***/ //MARK: - !<esli zagruzit ne udalos to...>! } /*** if image download suceed cache it and make new TheQuestion object ****/ if let image = image { print("NEW IMAGE DOWNLOADED") self.cache.store(image, forKey: pathToImage) let question = TheQuestion(image, questionHeader, questionAnswer) self.questions.append(question) self.questionStack.push(question) //questionCount > 1 because there is default non-question value in database questionsCount > 2 ? questionsCount -= 1 : self.downLoadComplete() } }) } }) } } } }) ref.removeAllObservers() } fileprivate func getQuestionsArray() -> [TheQuestion] { return self.questions } fileprivate func getShuffledQuestionsArray() -> [TheQuestion] { return questions.shuffled() } fileprivate func getShuffledQuestionStack() -> Stack<TheQuestion>? { let shuffledArray = getShuffledQuestionsArray() var stack = Stack<TheQuestion>() for question in shuffledArray { stack.push(question) } return stack.items.count > 0 ? stack : nil } fileprivate func noInternetConnectionError() { } fileprivate func downLoadComplete() { print("Download Questions DONE") if onGetQuestionStackComplete != nil { onGetQuestionStackComplete!(questionStack, questions) } AppDelegate.instance().dismissActivityIndicator() } fileprivate func cacheRetrieveComplete() { print("Retrieve Questions DONE") if onGetQuestionStackComplete != nil { onGetQuestionStackComplete!(questionStack, questions) } AppDelegate.instance().dismissActivityIndicator() } /*** PUBLIC ***/// MARK: -PUBLIC func getQuestionStack() -> Stack<TheQuestion> { return self.questionStack } func debugPrintShuffledQuestionArray() { let questionArray = getShuffledQuestionsArray() for question in questionArray { print(question.image.debugDescription + ":::" + question.questionTitle + ":::") } } }
true
4f3c0adcaac1fd5cb86291736b0ccaba9fad886a
Swift
cwJohnPark/algorithm-study-swift
/Math/PowerOfThree.playground/Contents.swift
UTF-8
529
3.46875
3
[]
no_license
func isPowerOfThree(_ n: Int) -> Bool { if n == 1 { return true } return isPowerOfThreeHelper(n, 3) } func isPowerOfThreeHelper(_ n: Int, _ power: Int) -> Bool { if n == power { return true } if n < power { return false } return isPowerOfThreeHelper(n, power * 3) } print(isPowerOfThree(1)) // true print(isPowerOfThree(27)) // true print(isPowerOfThree(0)) // false print(isPowerOfThree(9)) // true print(isPowerOfThree(45)) // false print(isPowerOfThree(-45)) // false print(isPowerOfThree(-27)) // false
true
a2e15e6d66530ecfbbfed7be2800d3f35c38ee89
Swift
JamesF0790/ThumbcrampStats
/ThumbcrampStats/Model/Episode.swift
UTF-8
1,553
3.21875
3
[]
no_license
import Foundation struct Episode: Codable { var number: Int // This can be gotten by the count or adding 1 to the index var date: Date var reviews: [Review] var scoreModifier: Float? var baseScore: Float { get { var score: Float = 0 for x in reviews { score += x.score } return score } } var score: Float { get { let score = baseScore guard let mod = scoreModifier else { return score } return score + mod } } } // MARK: - Codable Extension extension Episode { static let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first! static let archive = documentsDirectory.appendingPathComponent("episodes").appendingPathExtension("plist") static func Save(_ episodes: [Episode]) { let encoder = PropertyListEncoder() let codedEpisodes = try? encoder.encode(episodes) try? codedEpisodes?.write(to: archive, options: .noFileProtection) } static func Load() -> [Episode]? { guard let codedEpisodes = try? Data(contentsOf: archive) else {return nil} let decoder = PropertyListDecoder() return try? decoder.decode(Array<Episode>.self, from: codedEpisodes) } } // MARK: - Helper Procs extension Episode { static func Sort(_ episodes: [Episode]) -> [Episode] { return episodes.sorted(by: {$0.number < $1.number}) } }
true
04910b9fb2dd569163271169abb0b9b2a8618d0c
Swift
natisoria/SuperHero_app
/superHeroProject/Controller/Cell/BadsCollectionCell.swift
UTF-8
1,305
2.640625
3
[]
no_license
// // BadsCollectionCell.swift // superHeroProject // // Created by Natalia Soria on 1/3/21. // import UIKit import Kingfisher class BadsCollectionCell : UICollectionViewCell { @IBOutlet weak var badsBackgroundView: UIView! @IBOutlet weak var badsImage: UIImageView! @IBOutlet weak var badsName: UILabel! @IBOutlet weak var badsBrand: UIImageView! @IBOutlet weak var badsProgress: UIProgressView! override func awakeFromNib() { super.awakeFromNib() // corner radius badsBackgroundView.layer.cornerRadius = 8.0 badsBackgroundView.layer.masksToBounds = true badsImage.layer.cornerRadius = 8.0 badsImage.layer.masksToBounds = true } override func prepareForReuse() { super.prepareForReuse() badsImage.image = nil badsName.text = nil badsBrand.image = nil badsProgress.progress = 0 } func configure(image: String?, name: String, brand: String?, power: Float){ badsImage.kf.setImage (with: URL(string: image ?? ""), placeholder: DataProvider.shared.placeholderImage) badsName.text = name badsBrand.image = UIImage (named: brand ?? "") badsProgress.progress = power } }
true