repo_name
stringlengths
6
91
path
stringlengths
6
999
copies
stringclasses
283 values
size
stringlengths
1
7
content
stringlengths
3
1.05M
license
stringclasses
15 values
iCrany/iOSExample
iOSExample/Module/TransitionExample/ViewController/Session4/Present/Error/VC/ErrorPresentFromViewController.swift
1
4069
// // ErrorPresentFromViewController.swift // iOSExample // // Created by iCrany on 2017/12/9. // Copyright © 2017 iCrany. All rights reserved. // import Foundation import UIKit class ErrorPresentFromViewController: UIViewController { fileprivate lazy var interactionController: SwipeUpInteractiveTransition = { let vc = PresentToViewController() let nav = UINavigationController(rootViewController: vc) let interaction = SwipeUpInteractiveTransition(startBlock: { [weak self] in guard let sSelf = self else { return } //Try1: 尝试 present 一个 UIViewController, 并且设置 vc.transitioningDelegate //结果:这个就是正常的 UIViewController 转场到 UIViewController, 交互手势正常 // vc.transitioningDelegate = sSelf // sSelf.present(vc, animated: true) //Try2: 尝试 present 一个 UINavigationController, 并且设置 UIViewController.transitioningDelegate //结果:这个是 UIViewController 转场到 UINavigationController 封装好的 UIViewController, 如果手势设置在 UIViewController.transitioningDelegate 上就交互手势就会失效 // vc.transitioningDelegate = sSelf // sSelf.present(nav, animated: true) //Try3: 尝试 present 一个 UINavigationController, 并且设置 UINavigationController.transitioningDelegate //结果:这个是 UIViewController 转场到 UINavigationController 封装好的 UIViewController, 如果手势设置在 UIViewController.transitioningDelegate 上,交互手势正常 nav.transitioningDelegate = sSelf sSelf.present(nav, animated: true) }, endBlock: { _ in }) return interaction }() fileprivate lazy var dismissAnimation: NormalDismissAnimation = { let dismissAnimation = NormalDismissAnimation() return dismissAnimation }() fileprivate lazy var presentAnimation: ErrorPresentAnimation = { let presentAnimation = ErrorPresentAnimation() return presentAnimation }() required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } init() { super.init(nibName: nil, bundle: nil) self.setupUI() } private func setupUI() { self.view.backgroundColor = .white let titleLabel = UILabel() titleLabel.text = "这里是 ErrorPresentFromViewController" self.view.addSubview(titleLabel) titleLabel.backgroundColor = .black titleLabel.textColor = .white titleLabel.snp.makeConstraints { maker in maker.center.equalToSuperview() maker.size.equalTo(CGSize(width: 200, height: 60)) } self.interactionController.writeToViewController(viewController: self) } } extension ErrorPresentFromViewController: UIViewControllerTransitioningDelegate { func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { //注意: 这里就是因为 PresentAnimation 中有检测是否是 UINavigationController, 如果是 UINavigationController 就是获取第一个 viewControllers 中的第一个 UIViewController, 导致交互动画的失效 return self.presentAnimation } //在 Session4 的例子中,dismiss 的动画如果不定义的话就是用系统默认的 // func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { // return self.dismissAnimation // } func interactionControllerForPresentation(using animator: UIViewControllerAnimatedTransitioning) -> UIViewControllerInteractiveTransitioning? { let nowAnimator = animator as? NormalPresentAnimation guard nowAnimator != nil, self.interactionController.interacting else { return nil } return self.interactionController } }
mit
kylef/Mockingdrive
Mockingdrive/Mockingdrive.swift
1
1719
import XCTest import Mockingjay import Representor let representorSerializers = [ "application/vnd.siren+json": serializeSiren, "application/hal+json": serializeHAL, "application/vnd.hal+json": serializeHAL, ] /// Extensions to XCTest to provide stubbing Hypermedia responses extension XCTest { /// Stub any requests matching the matcher with the given Representor public func stub(matcher:Matcher, contentType:String = "application/hal+json", representor:Representor<HTTPTransition>) -> Stub { return stub(matcher) { request in let acceptHeader = request.valueForHTTPHeaderField("Accept") ?? contentType let contentTypes = acceptHeader.componentsSeparatedByString(",") .map { $0.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet()) } .filter { representorSerializers.keys.contains($0) } if let contentType = contentTypes.first, serializer = representorSerializers[contentType] { let representation = serializer(representor) return json(representation, headers: ["Content-Type": contentType])(request: request) } let errorDescription = "Unknown or unsupported content types (Accept: \(acceptHeader))" return .Failure(NSError(domain: "Mockingdrive", code: 0, userInfo: [NSLocalizedDescriptionKey: errorDescription])) } } /// Stub any requests matching the matcher with the given Representor builder public func stubRepresentor(matcher:Matcher, contentType:String = "application/hal+json", closure:(RepresentorBuilder<HTTPTransition> -> ())) -> Stub { return stub(matcher, contentType: contentType, representor: Representor(closure)) } }
mit
grigaci/RateMyTalkAtMobOS
RateMyTalkAtMobOS/Classes/GUI/Session/Helpers/NSAttributedString+Session.swift
1
628
// // NSAttributedString+Session.swift // RateMyTalkAtMobOS // // Created by Bogdan Iusco on 10/19/14. // Copyright (c) 2014 Grigaci. All rights reserved. // extension NSAttributedString { class func ratingCategoryAttributedString(string: String) -> NSAttributedString { let font = UIFont.fontLatoRegular(16.0) let color = UIColor(fullRed: 94.0, fullGreen: 94.0, fullBlue: 94.0) let dictionary = [NSForegroundColorAttributeName : color, NSFontAttributeName : font] let attributedString = NSAttributedString(string: string, attributes: dictionary) return attributedString } }
bsd-3-clause
Urinx/SublimeCode
Sublime/Sublime/SSHAddNewServerViewController.swift
1
5419
// // SSHAddNewServerViewController.swift // Sublime // // Created by Eular on 3/28/16. // Copyright © 2016 Eular. All rights reserved. // import UIKit import Gifu class SSHAddNewServerViewController: UITableViewController, UITextFieldDelegate { let settingList = [ ["ssh_server", "host"], ["ssh_port", "port"], ["ssh_user", "username"], ["ssh_password", "password"] ] var textFieldList = [UITextField]() override func viewDidLoad() { super.viewDidLoad() title = "New Server" tableView.backgroundColor = Constant.CapeCod tableView.separatorColor = Constant.TableCellSeparatorColor tableView.tableFooterView = UIView() Global.Notifi.addObserver(self, selector: #selector(self.keyboardDidShow), name: UIKeyboardDidShowNotification, object: nil) Global.Notifi.addObserver(self, selector: #selector(self.keyboardWillHide), name: UIKeyboardDidHideNotification, object: nil) let header = UIView(frame: CGRectMake(0, 0, view.width, 80)) let gif = AnimatableImageView() gif.frame = CGRectMake(0, 20, view.width, 60) gif.contentMode = .ScaleAspectFit gif.animateWithImageData(NSData(contentsOfFile: NSBundle.mainBundle().pathForResource("animation", ofType: "gif")!)!) gif.startAnimatingGIF() header.addSubview(gif) tableView.tableHeaderView = header } func keyboardDidShow() { navigationItem.rightBarButtonItem = UIBarButtonItem(image: UIImage(named: "ssh_keyboard"), style: .Plain, target: self, action: #selector(self.dismissKeyboard)) } func keyboardWillHide() { navigationItem.rightBarButtonItem = nil } func dismissKeyboard() { self.view.endEditing(true) } func textFieldShouldReturn(textField: UITextField) -> Bool { textField.resignFirstResponder() return true } override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 2 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return [settingList.count, 1][section] } override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { return 50 } override func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { if section == 0 { return 0 } return Constant.FilesTableSectionHight } override func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 0 { return nil } let headerView = UIView() headerView.frame = CGRectMake(0, 0, view.width, Constant.FilesTableSectionHight) headerView.backgroundColor = Constant.CapeCod return headerView } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: nil) cell.backgroundColor = Constant.NavigationBarAndTabBarColor cell.selectedBackgroundView = UIView(frame: cell.frame) cell.selectedBackgroundView?.backgroundColor = Constant.NavigationBarAndTabBarColor if indexPath.section == 0 { let tf = UITextField() tf.frame = CGRectMake(70, 3, cell.frame.width - 80, cell.frame.height) tf.attributedPlaceholder = NSAttributedString(string: settingList[indexPath.row][1], attributes: [NSForegroundColorAttributeName: UIColor.grayColor()]) tf.textColor = UIColor.whiteColor() tf.delegate = self if tf.placeholder == "port" { tf.keyboardType = .NumberPad } else if tf.placeholder == "host" { tf.keyboardType = .URL } tf.autocorrectionType = .No tf.autocapitalizationType = .None cell.addSubview(tf) cell.imageView?.image = UIImage(named: settingList[indexPath.row][0]) textFieldList.append(tf) } else { let doneImg = UIImageView() doneImg.frame = CGRectMake(0, 0, 40, 40) doneImg.image = UIImage(named: "ssh_done") cell.addSubview(doneImg) doneImg.atCenter() } return cell } override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) if indexPath.section == 1 { var serverInfo = [String:String]() for tf in textFieldList { if tf.text!.isEmpty { view.Toast(message: "\(tf.placeholder!) can't be empty", hasNavigationBar: true) return } else { serverInfo[tf.placeholder!] = tf.text } } let serverPlist = Plist(path: Constant.SublimeRoot+"/etc/ssh_list.plist") do { try serverPlist.appendToPlistFile(serverInfo) navigationController?.popViewControllerAnimated(true) } catch { view.Toast(message: "Save failed!", hasNavigationBar: true) } } } }
gpl-3.0
blockchain/My-Wallet-V3-iOS
Modules/FeatureCoin/Sources/FeatureCoinDomain/Localization/LocalizationConstants+CoinDomain.swift
1
4199
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import Localization extension LocalizationConstants { enum CoinDomain { enum Button { enum Title { enum Rewards { static let summary = NSLocalizedString( "Summary", comment: "Account Actions: Rewards summary CTA title" ) } static let buy = NSLocalizedString( "Buy", comment: "Account Actions: Buy CTA title" ) static let sell = NSLocalizedString( "Sell", comment: "Account Actions: Sell CTA title" ) static let send = NSLocalizedString( "Send", comment: "Account Actions: Send CTA title" ) static let receive = NSLocalizedString( "Receive", comment: "Account Actions: Receive CTA title" ) static let swap = NSLocalizedString( "Swap", comment: "Account Actions: Swap CTA title" ) static let activity = NSLocalizedString( "Activity", comment: "Account Actions: Activity CTA title" ) static let withdraw = NSLocalizedString( "Withdraw", comment: "Account Actions: Withdraw CTA title" ) static let deposit = NSLocalizedString( "Deposit", comment: "Account Actions: Deposit CTA title" ) } enum Description { enum Rewards { static let summary = NSLocalizedString( "View Accrued %@ Rewards", comment: "Account Actions: Rewards summary CTA description" ) static let withdraw = NSLocalizedString( "Withdraw %@ from Rewards Account", comment: "Account Actions: Rewards withdraw CTA description" ) static let deposit = NSLocalizedString( "Add %@ to Rewards Account", comment: "Account Actions: Rewards deposit CTA description" ) } enum Exchange { static let withdraw = NSLocalizedString( "Withdraw %@ from Exchange", comment: "Account Actions: Exchange withdraw CTA description" ) static let deposit = NSLocalizedString( "Add %@ to Exchange", comment: "Account Actions: Exchange deposit CTA description" ) } static let buy = NSLocalizedString( "Use Your Cash or Card", comment: "Account Actions: Buy CTA description" ) static let sell = NSLocalizedString( "Convert Your Crypto to Cash", comment: "Account Actions: Sell CTA description" ) static let send = NSLocalizedString( "Transfer %@ to Other Wallets", comment: "Account Actions: Send CTA description" ) static let receive = NSLocalizedString( "Receive %@ to your account", comment: "Account Actions: Receive CTA description" ) static let swap = NSLocalizedString( "Exchange %@ for Another Crypto", comment: "Account Actions: Swap CTA description" ) static let activity = NSLocalizedString( "View all transactions", comment: "Account Actions: Activity CTA description" ) } } } }
lgpl-3.0
miDrive/MDAlert
MDAlert/Classes/MDAlertViewDefaults.swift
1
1750
// // MDAlertViewDefaults.swift // Pods // // Created by Chris Byatt on 12/05/2017. // // import Foundation class MDAlertViewDefaults { // Default backgorund colour of alert static let alertBackgroundColour: UIColor = UIColor.white // Default height of actions static let alertButtonHeight: CGFloat = 60 // Default corner radius of alert static let alertCornerRadius: CGFloat = 5.0 // Default font for alert title static let titleFont: UIFont = UIFont.systemFont(ofSize: 26.0) // Default colour for alert title static let titleColour: UIColor = UIColor.black // Default font alert message static let bodyFont: UIFont = UIFont.systemFont(ofSize: 16.0) // Default colour for alert message static let bodyColour: UIColor = UIColor.black // Default background colour of action static let actionDefaultBackgroundColour: UIColor = UIColor(red: 4/255, green: 123/255, blue: 205/255, alpha: 1.0) // Default background colour of cancel action static let actionCancelBackgroundColour: UIColor = UIColor(red: 135/255, green: 154/255, blue: 168/255, alpha: 1.0) // Default background colour of destructive action static let actionDestructiveBackgroundColour: UIColor = UIColor(red: 235/255, green: 0/255, blue: 0/255, alpha: 1.0) // Default title colour of action static let actionDefaultTitleColour: UIColor = UIColor.white // Default title colour of destructive action static let actionDestructiveTitleColour: UIColor = UIColor.white // Default title colour of cancel action static let actionCancelTitleColour: UIColor = UIColor.white // Default action font static let actionTitleFont: UIFont = UIFont.systemFont(ofSize: 15.0) }
mit
guillermo-ag-95/App-Development-with-Swift-for-Students
2 - Introduction to UIKit/1 - Strings/lab/Lab - Strings.playground/Pages/5. App Exercise - Password Entry and User Search.xcplaygroundpage/Contents.swift
1
3211
/*: ## App Exercise - Password Entry and User Search >These exercises reinforce Swift concepts in the context of a fitness tracking app. You think it might be fun to incorporate some friendly competition into your fitness tracking app. Users will be able to compete with friends in small fitness challenges. However, to do this users will need a password-protected account. Write an if-else statement below that will check that the entered user name and password match the stored user name and password. While the password should be case sensitive, users should be able to log in even if their entered user name has the wrong capitalization. If the user name and password match, print "You are now logged in!" Otherwise, print "Please check your user name and password and try again." */ let storedUserName = "TheFittest11" let storedPassword = "a8H1LuK91" let enteredUserName = "thefittest11" let enteredPassword: String = "a8H1Luk9" if storedUserName.lowercased() == enteredUserName.lowercased() && storedPassword == enteredPassword { print("You are now logged in!") } else { print("Please check your user name and password and try again.") } /*: Now that users can log in, they need to be able to search through a list of users to find their friends. This might normally be done by having the user enter a name, and then looping through all user names to see if a user name contains the search term entered. You'll learn about loops later, so for now you'll just work through one cycle of that. Imagine you are searching for a friend whose user name is StepChallenger. You enter "step" into a search bar and the app begins to search. When the app comes to the user name "stepchallenger," it checks to see if "StepChallenger" contains "step." Using `userName` and `searchName` below, write an if-else statement that checks to see if `userName` contains the search term. The search should *not* be case sensitive. */ import Foundation let userName = "StepChallenger" let searchName = "step" if userName.lowercased().contains(searchName) { print("There it is.") } /*: _Copyright © 2017 Apple Inc._ _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._ */ //: [Previous](@previous) | page 5 of 5
mit
vzool/ios-nanodegree-meme-me
ImagePicker/TabViewController.swift
1
776
// // TabViewController.swift // ImagePicker // // Created by Abdelaziz Elrashed on 7/17/15. // Copyright (c) 2015 Abdelaziz Elrashed. All rights reserved. // import UIKit class TabViewController: UITabBarController { override func viewDidLoad() { super.viewDidLoad() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } /* // 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. } */ }
mit
jovito-royeca/Cineko
Cineko/DynamicHeightTableViewCell.swift
1
1146
// // DynamicHeightTableViewCell.swift // Cineko // // Created by Jovit Royeca on 12/04/2016. // Copyright © 2016 Jovito Royeca. All rights reserved. // import UIKit class DynamicHeightTableViewCell: UITableViewCell { @IBOutlet weak var dynamicLabel: UILabel! // MARK: Overrides override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } // MARK: Custom Methods func changeColor(backgroundColor: UIColor?, fontColor: UIColor?) { self.backgroundColor = backgroundColor dynamicLabel.textColor = fontColor if accessoryType != .None { if let image = UIImage(named: "forward") { let tintedImage = image.imageWithRenderingMode(.AlwaysTemplate) let imageView = UIImageView(image: tintedImage) imageView.tintColor = fontColor accessoryView = imageView } } } }
apache-2.0
qiuncheng/study-for-swift
learn-rx-swift/Chocotastic-starter/Pods/RxSwift/RxSwift/Observables/Implementations/SkipWhile.swift
6
3228
// // SkipWhile.swift // Rx // // Created by Yury Korolev on 10/9/15. // Copyright © 2015 Krunoslav Zaher. All rights reserved. // class SkipWhileSink<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipWhile<ElementType> typealias Element = ElementType fileprivate let _parent: Parent fileprivate var _running = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { do { _running = try !_parent._predicate(value) } catch let e { forwardOn(.error(e)) dispose() return } } if _running { forwardOn(.next(value)) } case .error, .completed: forwardOn(event) dispose() } } } class SkipWhileSinkWithIndex<ElementType, O: ObserverType> : Sink<O>, ObserverType where O.E == ElementType { typealias Parent = SkipWhile<ElementType> typealias Element = ElementType fileprivate let _parent: Parent fileprivate var _index = 0 fileprivate var _running = false init(parent: Parent, observer: O) { _parent = parent super.init(observer: observer) } func on(_ event: Event<Element>) { switch event { case .next(let value): if !_running { do { _running = try !_parent._predicateWithIndex(value, _index) let _ = try incrementChecked(&_index) } catch let e { forwardOn(.error(e)) dispose() return } } if _running { forwardOn(.next(value)) } case .error, .completed: forwardOn(event) dispose() } } } class SkipWhile<Element>: Producer<Element> { typealias Predicate = (Element) throws -> Bool typealias PredicateWithIndex = (Element, Int) throws -> Bool fileprivate let _source: Observable<Element> fileprivate let _predicate: Predicate! fileprivate let _predicateWithIndex: PredicateWithIndex! init(source: Observable<Element>, predicate: @escaping Predicate) { _source = source _predicate = predicate _predicateWithIndex = nil } init(source: Observable<Element>, predicate: @escaping PredicateWithIndex) { _source = source _predicate = nil _predicateWithIndex = predicate } override func run<O : ObserverType>(_ observer: O) -> Disposable where O.E == Element { if let _ = _predicate { let sink = SkipWhileSink(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } else { let sink = SkipWhileSinkWithIndex(parent: self, observer: observer) sink.disposable = _source.subscribe(sink) return sink } } }
mit
czechboy0/BuildaUtils
Source/ContainerExtensions.swift
2
1073
// // ContainerExtensions.swift // XcodeServerSDK // // Created by Honza Dvorsky on 21/06/2015. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation extension Sequence { public func mapThrows<T>(transform: (Self.Iterator.Element) throws -> T) rethrows -> [T] { var out: [T] = [] for i in self { out.append(try transform(i)) } return out } public func filterThrows(includeElement: (Self.Iterator.Element) throws -> Bool) rethrows -> [Self.Iterator.Element] { var out: [Self.Iterator.Element] = [] for i in self { if try includeElement(i) { out.append(i) } } return out } /** Basically `filter` that stops when it finds the first one. */ public func findFirst(_ test: (Self.Iterator.Element) -> Bool) -> Self.Iterator.Element? { for i in self { if test(i) { return i } } return nil } }
mit
LuisMarinheiro/FastlaneExample
FastlaneExample/Models/Repository.swift
4
5122
// // Repository.swift // FastlaneExample // // Created by Ivan Bruel on 30/05/2017. // Copyright © 2017 Swift Aveiro. All rights reserved. // import Foundation import ObjectMapper struct Repository: ImmutableMappable { let keysURL: String let statusesURL: String let issuesURL: String let defaultBranch: String let issueEventsURL: String? let identifier: Int let owner: User let eventsURL: String let subscriptionURL: String let watchers: Int let gitCommitsURL: String let subscribersURL: String let cloneURL: String let hasWiki: Bool let URL: String let pullsURL: String let fork: Bool let notificationsURL: String let description: String? let collaboratorsURL: String let deploymentsURL: String let languagesURL: String let hasIssues: Bool let commentsURL: String let isPrivate: Bool let size: Int let gitTagsURL: String let updatedAt: String let sshURL: String let name: String let contentsURL: String let archiveURL: String let milestonesURL: String let blobsURL: String let contributorsURL: String let openIssuesCount: Int let forksCount: Int let treesURL: String let svnURL: String let commitsURL: String let createdAt: String let forksURL: String let hasDownloads: Bool let mirrorURL: String? let homepage: String? let teamsURL: String let branchesURL: String let issueCommentURL: String let mergesURL: String let gitRefsURL: String let gitURL: String let forks: Int let openIssues: Int let hooksURL: String let htmlURL: URL let stargazersURL: String let assigneesURL: String let compareURL: String let fullName: String let tagsURL: String let releasesURL: String let pushedAt: String? let labelsURL: String let downloadsURL: String let stargazersCount: Int let watchersCount: Int let language: String let hasPages: Bool var isSwift: Bool { return language == "Swift" } // swiftlint:disable next function_body_length init(map: Map) throws { keysURL = try map.value("keys_url") statusesURL = try map.value("statuses_url") issuesURL = try map.value("issues_url") defaultBranch = try map.value("default_branch") issueEventsURL = try? map.value("issues_events_url") identifier = try map.value("id") owner = try map.value("owner") eventsURL = try map.value("events_url") subscriptionURL = try map.value("subscription_url") watchers = try map.value("watchers") gitCommitsURL = try map.value("git_commits_url") subscribersURL = try map.value("subscribers_url") cloneURL = try map.value("clone_url") hasWiki = try map.value("has_wiki") URL = try map.value("url") pullsURL = try map.value("pulls_url") fork = try map.value("fork") notificationsURL = try map.value("notifications_url") description = try? map.value("description") collaboratorsURL = try map.value("collaborators_url") deploymentsURL = try map.value("deployments_url") languagesURL = try map.value("languages_url") hasIssues = try map.value("has_issues") commentsURL = try map.value("comments_url") isPrivate = try map.value("private") size = try map.value("size") gitTagsURL = try map.value("git_tags_url") updatedAt = try map.value("updated_at") sshURL = try map.value("ssh_url") name = try map.value("name") contentsURL = try map.value("contents_url") archiveURL = try map.value("archive_url") milestonesURL = try map.value("milestones_url") blobsURL = try map.value("blobs_url") contributorsURL = try map.value("contributors_url") openIssuesCount = try map.value("open_issues_count") forksCount = try map.value("forks_count") treesURL = try map.value("trees_url") svnURL = try map.value("svn_url") commitsURL = try map.value("commits_url") createdAt = try map.value("created_at") forksURL = try map.value("forks_url") hasDownloads = try map.value("has_downloads") mirrorURL = try? map.value("mirror_url") homepage = try? map.value("homepage") teamsURL = try map.value("teams_url") branchesURL = try map.value("branches_url") issueCommentURL = try map.value("issue_comment_url") mergesURL = try map.value("merges_url") gitRefsURL = try map.value("git_refs_url") gitURL = try map.value("git_url") forks = try map.value("forks") openIssues = try map.value("open_issues") hooksURL = try map.value("hooks_url") htmlURL = try map.value("html_url", using: URLTransform()) stargazersURL = try map.value("stargazers_url") assigneesURL = try map.value("assignees_url") compareURL = try map.value("compare_url") fullName = try map.value("full_name") tagsURL = try map.value("tags_url") releasesURL = try map.value("releases_url") pushedAt = try? map.value("pushed_at") labelsURL = try map.value("labels_url") downloadsURL = try map.value("downloads_url") stargazersCount = try map.value("stargazers_count") watchersCount = try map.value("watchers_count") language = try map.value("language") hasPages = try map.value("has_pages") } }
mit
jcheng77/missfit-ios
missfit/missfit/Vendor/Refresher/PullToRefreshExtension.swift
1
3129
// // PullToRefresh.swift // // Copyright (c) 2014 Josip Cavar // // 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 import UIKit private let pullToRefreshTag = 324 private let pullToRefreshDefaultHeight: CGFloat = 50 extension UIScrollView { // Actual UIView subclass which is added as subview to desired UIScrollView. If you want customize appearance of this object, do that after addPullToRefreshWithAction public var pullToRefreshView: PullToRefreshView? { get { var pullToRefreshView = viewWithTag(pullToRefreshTag) return pullToRefreshView as? PullToRefreshView } } // If you want to add pull to refresh functionality to your UIScrollView just call this method and pass action closure you want to execute while pull to refresh is animating. If you want to stop pull to refresh you must do that manually calling stopPullToRefreshView methods on your scroll view public func addPullToRefreshWithAction(action :(() -> ())) { var pullToRefreshView = PullToRefreshView(action: action, frame: CGRectMake(0, -pullToRefreshDefaultHeight, self.frame.size.width, pullToRefreshDefaultHeight)) pullToRefreshView.tag = pullToRefreshTag addSubview(pullToRefreshView) } // If you want to use your custom animation when pull to refresh is animating, you should call this method and pass your animator object. public func addPullToRefreshWithAction(action :(() -> ()), withAnimator animator: PullToRefreshViewAnimator) { var pullToRefreshView = PullToRefreshView(action: action, frame: CGRectMake(0, -pullToRefreshDefaultHeight, self.frame.size.width, pullToRefreshDefaultHeight), animator: animator) pullToRefreshView.tag = pullToRefreshTag addSubview(pullToRefreshView) } // Manually start pull to refresh public func startPullToRefresh() { pullToRefreshView?.loading = true } // Manually stop pull to refresh public func stopPullToRefresh() { pullToRefreshView?.loading = false } }
mit
ciiqr/contakt
contakt/contaktTests/String+insensitiveContains-Tests.swift
1
2020
// // String+insensitiveContains-Tests.swift // contakt // // Created by William Villeneuve on 2016-01-24. // Copyright © 2016 William Villeneuve. All rights reserved. // import XCTest class String_insensitiveContains_Tests: XCTestCase { func test_string_lower_contains() { let string = "this is a string" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_string_upper_contains() { let string = "THIS IS A STRING" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_string_someUpper_contains() { let string = "This is A STRING" XCTAssert(string.insensitiveContains("a STR")) XCTAssert(string.insensitiveContains("THIS")) XCTAssert(string.insensitiveContains("this is a string")) } func test_characterView_lower_contains() { let string = "this is a string" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } func test_characterView_upper_contains() { let string = "THIS IS A STRING" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } func test_characterView_someUpper_contains() { let string = "This is A STRING" XCTAssert(string.insensitiveContains("a STR".characters)) XCTAssert(string.insensitiveContains("THIS".characters)) XCTAssert(string.insensitiveContains("this is a string".characters)) } }
unlicense
itsaboutcode/WordPress-iOS
WordPress/Classes/ViewRelated/NUX/EpilogueSectionHeaderFooter.swift
2
352
import UIKit class EpilogueSectionHeaderFooter: UITableViewHeaderFooterView { static let identifier = "EpilogueSectionHeaderFooter" @IBOutlet weak var topConstraint: NSLayoutConstraint! @IBOutlet var titleLabel: UILabel? override func awakeFromNib() { super.awakeFromNib() titleLabel?.textColor = .textSubtle } }
gpl-2.0
hooman/swift
test/Interpreter/class_forbid_objc_assoc_objects.swift
5
8591
// RUN: %target-run-simple-swift // RUN: %target-run-simple-swift(-O) // REQUIRES: objc_interop // REQUIRES: executable_test import ObjectiveC import StdlibUnittest defer { runAllTests() } var Tests = TestSuite("AssocObject") @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class AllowedToHaveAssocObject { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object, assign") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_ASSIGN) } Tests.test("no crash when set assoc object, copy") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY) } Tests.test("no crash when set assoc object, copy_nonatomic") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY_NONATOMIC) } Tests.test("no crash when set assoc object, retain") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("no crash when set assoc object, retain_nonatomic") { let x = AllowedToHaveAssocObject() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnableToHaveAssocObjects { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object, assign") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_ASSIGN) } Tests.test("crash when set assoc object, copy") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY) } Tests.test("crash when set assoc object, copy_nonatomic") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_COPY_NONATOMIC) } Tests.test("crash when set assoc object, retain") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object, retain_nonatomic") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjects() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnableToHaveAssocObjectsGeneric<T> { var state: T init(state: T) { self.state = state } } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object (generic)") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnableToHaveAssocObjectsGeneric(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the child. This is unsound since we will get different // answers since the type checker isn't enforcing this. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class UnsoundAbleToHaveAssocObjectsParentClass { } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class UnsoundUnableToHaveAssocObjectsSubClass : UnsoundAbleToHaveAssocObjectsParentClass { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object set only on child subclass, but assoc to parent") .code { let x = UnsoundAbleToHaveAssocObjectsParentClass() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object set only on child subclass") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the parent. It seems like the bit is propagated... I am // not sure. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") class UnsoundAbleToHaveAssocObjectsParentClass2 { } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class UnsoundUnableToHaveAssocObjectsSubClass2 : UnsoundAbleToHaveAssocObjectsParentClass2 { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass2() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class UnsoundUnableToHaveAssocObjectsSubClass3 : UnsoundAbleToHaveAssocObjectsParentClass2 { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class, child not final") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = UnsoundUnableToHaveAssocObjectsSubClass3() objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // More Generic Tests // In this case, we mark the child. This is unsound since we will get different // answers since the type checker isn't enforcing this. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class GenericAbleToHaveAssocObjectsParentClass<T> { public var state: T init(state: T) { self.state = state } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") final class GenericUnableToHaveAssocObjectsSubClass<T> : GenericAbleToHaveAssocObjectsParentClass<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("no crash when set assoc object set only on child subclass, but assoc to parent") .code { let x = GenericAbleToHaveAssocObjectsParentClass(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } Tests.test("crash when set assoc object set only on child subclass") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } // In this case, we mark the parent. It seems like the bit is propagated... I am // not sure. @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) @_semantics("objc.forbidAssociatedObjects") class GenericAbleToHaveAssocObjectsParentClass2<T> { public var state: T init(state: T) { self.state = state } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) final class GenericUnableToHaveAssocObjectsSubClass2<T> : GenericAbleToHaveAssocObjectsParentClass2<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass2(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } } @available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) class GenericUnableToHaveAssocObjectsSubClass3<T> : GenericAbleToHaveAssocObjectsParentClass2<T> { } if #available(macOS 10.4.4, iOS 12.2, watchOS 5.2, tvOS 12.2, *) { Tests.test("crash when set assoc object set only on parent class, child not final") .crashOutputMatches("objc_setAssociatedObject called on instance") .code { expectCrashLater() let x = GenericUnableToHaveAssocObjectsSubClass3(state: 5) objc_setAssociatedObject(x, "myKey", "myValue", .OBJC_ASSOCIATION_RETAIN) } }
apache-2.0
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/PhotoBrower/LLPhotoBrowser/LLBrowserActionSheet.swift
1
8110
// // LLBrowserActionSheet.swift // LLPhotoBrowser // // Created by LvJianfeng on 2017/4/18. // Copyright © 2017年 LvJianfeng. All rights reserved. // import UIKit typealias LLDidSelectedCell = (NSInteger) -> Void open class LLBrowserActionSheet: UIView, UITableViewDelegate, UITableViewDataSource { /// Title Array fileprivate var titleArray: [String]? /// Cancel Title fileprivate var cancelTitle: String = "取消" /// Did Selected fileprivate var didSelectedAction: LLDidSelectedCell? = nil /// TableView fileprivate var tableView: UITableView? /// Mask View fileprivate var backMaskView: UIView? /// Height fileprivate var tableViewHeight: CGFloat? /// Cell Height fileprivate var tableCellHeight: CGFloat? /// Section View Background Color default: 191.0 191.0 191.0 fileprivate var sectionViewBackgroundColor: UIColor? = UIColor.init(red: 191.0/255.0, green: 191.0/255.0, blue: 191.0/255.0, alpha: 1.0) /// Cell Background Color fileprivate var cellBackgroundColor: UIColor? = UIColor.white /// Title Font fileprivate var titleFont: UIFont? = UIFont.systemFont(ofSize: 14.0) /// Title Color fileprivate var titleTextColor: UIColor? = UIColor.black /// Cancel Color fileprivate var cancelTextColor: UIColor? = UIColor.black /// Line Color fileprivate var lineColor: UIColor? = UIColor.init(red: 212.0/255.0, green: 212.0/255.0, blue: 212.0/255.0, alpha: 1.0) /// Init init(titleArray: [String] = [], cancelTitle: String, cellHeight: CGFloat? = 44.0, backgroundColor: UIColor?, cellBackgroundColor: UIColor, titleFont: UIFont?, titleTextColor: UIColor?, cancelTextColor: UIColor?, lineColor: UIColor?, didSelectedCell:LLDidSelectedCell? = nil) { super.init(frame: CGRect.zero) self.titleArray = titleArray self.cancelTitle = cancelTitle self.tableCellHeight = cellHeight if let _ = backgroundColor { self.sectionViewBackgroundColor = backgroundColor } if let _ = titleFont { self.titleFont = titleFont } if let _ = titleTextColor { self.titleTextColor = titleTextColor } if let _ = cancelTextColor { self.cancelTextColor = cancelTextColor } if let _ = lineColor { self.lineColor = lineColor } self.cellBackgroundColor = cellBackgroundColor self.tableViewHeight = CGFloat((self.titleArray?.count)! + 1) * self.tableCellHeight! + 10.0 self.didSelectedAction = didSelectedCell setupActionSheet() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func setupActionSheet() { backMaskView = UIView.init() backMaskView?.backgroundColor = UIColor.black backMaskView?.alpha = 0 // 渐变效果 UIView.animate(withDuration: 0.3) { self.backMaskView?.alpha = 0.3 } addSubview(backMaskView!) tableView = UITableView.init() tableView?.delegate = self tableView?.dataSource = self tableView?.separatorColor = UIColor.clear tableView?.bounces = false addSubview(tableView!) } // MARK: UITableViewDataSource public func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return (section == 1) ? 10.0 : 0 } public func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { if section == 1 { let view = UIView.init() view.backgroundColor = sectionViewBackgroundColor! return view } return nil } public func numberOfSections(in tableView: UITableView) -> Int { return 2 } public func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return tableCellHeight! } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return (section == 0) ? (titleArray?.count)! : 1 } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let identifier: String = "LLBrowserActionSheetCell" var cell: LLBrowserActionSheetCell? = tableView.dequeueReusableCell(withIdentifier: identifier) as? LLBrowserActionSheetCell if cell == nil { cell = LLBrowserActionSheetCell.init(style: .default, reuseIdentifier: identifier) } cell?.backgroundColor = cellBackgroundColor! cell?.titleLabel?.frame = CGRect.init(x: 0, y: 0, width: ll_w, height: tableCellHeight!) cell?.titleLabel?.font = titleFont! cell?.titleLabel?.textColor = titleTextColor! cell?.bottomLine?.backgroundColor = lineColor! cell?.bottomLine?.isHidden = true if indexPath.section == 0 { cell?.titleLabel?.text = titleArray?[indexPath.row] if (titleArray?.count)! > indexPath.row + 1 { cell?.bottomLine?.frame = CGRect.init(x: 0, y: tableCellHeight! - (1.0 / UIScreen.main.scale), width: self.ll_w, height: 1.0 / UIScreen.main.scale) cell?.bottomLine?.isHidden = false } }else{ cell?.titleLabel?.textColor = cancelTextColor! cell?.titleLabel?.text = cancelTitle } return cell! } // MARK: UITableViewDelegate public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if indexPath.section == 0{ if let didSelected = didSelectedAction { didSelected(indexPath.row) } } dismiss() } override open func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { dismiss() } func show(_ view: UIView) { view.addSubview(self) self.backgroundColor = UIColor.clear self.frame = view.bounds backMaskView?.frame = view.bounds tableView?.frame = CGRect.init(x: 0, y: ll_h, width: ll_w, height: tableViewHeight!) UIView.animate(withDuration: 0.3) { var frame = self.tableView?.frame frame?.origin.y -= self.tableViewHeight! self.tableView?.frame = frame! } } func dismiss() { UIView.animate(withDuration: 0.2, animations: { var frame = self.tableView?.frame frame?.origin.y += self.tableViewHeight! self.tableView?.frame = frame! self.backMaskView?.alpha = 0 }) { (finished) in self.removeFromSuperview() } } func updateFrameByTransform() { // Update if let _ = self.superview { self.frame = (self.superview?.bounds)! backMaskView?.frame = (self.superview?.bounds)! tableView?.frame = CGRect.init(x: 0, y: ll_h - tableViewHeight!, width: ll_w, height: tableViewHeight!) tableView?.reloadData() } } } class LLBrowserActionSheetCell: UITableViewCell { public var titleLabel: UILabel? public var bottomLine: UIView? override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) createCell() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func createCell() { titleLabel = UILabel.init() titleLabel?.textAlignment = .center contentView.addSubview(titleLabel!) bottomLine = UILabel.init() bottomLine?.backgroundColor = UIColor.init(red: 212.0/255.0, green: 212.0/255.0, blue: 212.0/255.0, alpha: 1.0) contentView.addSubview(bottomLine!) } }
mit
Keanyuan/SwiftContact
SwiftContent/SwiftContent/Classes/类和结构体/Player.swift
1
410
// // Player.swift // SwiftContent // // Created by 祁志远 on 2017/6/16. // Copyright © 2017年 祁志远. All rights reserved. // import UIKit class Player { var tracker = LevelTracker() var playerName: String func complete(level: Int) { LevelTracker.unlock(level + 1) tracker.advance(to: level + 1) } init(name: String) { playerName = name } }
mit
powerytg/Accented
Accented/UI/Common/Components/Animation/ExitAnimation.swift
1
305
// // ExitAnimation.swift // Accented // // Created by Tiangong You on 5/20/17. // Copyright © 2017 Tiangong You. All rights reserved. // import UIKit protocol ExitAnimation : NSObjectProtocol { func exitAnimationWillBegin() func performExitAnimation() func exitAnimationDidFinish() }
mit
denizsokmen/Raid
RaidTests/RaidTests.swift
1
886
// // RaidTests.swift // RaidTests // // Created by student7 on 17/12/14. // Copyright (c) 2014 student7. All rights reserved. // import UIKit import XCTest class RaidTests: XCTestCase { override func setUp() { super.setUp() // Put setup code here. This method is called before the invocation of each test method in the class. } override func tearDown() { // Put teardown code here. This method is called after the invocation of each test method in the class. super.tearDown() } func testExample() { // This is an example of a functional test case. XCTAssert(true, "Pass") } func testPerformanceExample() { // This is an example of a performance test case. self.measureBlock() { // Put the code you want to measure the time of here. } } }
gpl-2.0
Noah-Huppert/iOS-Piglatin-Translator
Piglatin Translator/RegexHelper.swift
1
827
// // RegexHelper.swift // Piglatin Translator // // Created by block7 on 3/24/16. // Copyright © 2016 noahhuppert.com. All rights reserved. // import Foundation class RegexHelper { // MARK: Regex Helpers class func getRegexGroup(text: String, match: NSTextCheckingResult, index: Int) -> String { return (text as NSString).substringWithRange(match.rangeAtIndex(index)) } class func matchRegex(text: String, regex: NSRegularExpression) -> [String] { let matches = regex.matchesInString(text, options: [], range: NSRange(location: 0, length: text.characters.count)) var results: [String] = [] for var i = 0; i < matches.count; i++ { results.append(getRegexGroup(text, match: matches[i], index: 1)) } return results } }
mit
MaxKramer/SwiftLuhn
Example/Tests/CardTypeTest.swift
1
911
// // CardTypeTest.swift // SwiftLuhn_Tests // // Created by Max Kramer on 01/09/2018. // Copyright © 2018 CocoaPods. All rights reserved. // import XCTest import SwiftLuhn class CardTypeTest: XCTestCase { func testStringValueShouldReturnCorrectValue() { let mapping = [ SwiftLuhn.CardType.amex: "American Express", SwiftLuhn.CardType.visa: "Visa", SwiftLuhn.CardType.mastercard: "Mastercard", SwiftLuhn.CardType.discover: "Discover", SwiftLuhn.CardType.dinersClub: "Diner's Club", SwiftLuhn.CardType.jcb: "JCB", SwiftLuhn.CardType.maestro: "Maestro", SwiftLuhn.CardType.rupay: "Rupay", SwiftLuhn.CardType.mir: "Mir" ] mapping.forEach { key, value in let result = key.stringValue() XCTAssertEqual(result, value) } } }
mit
aldopolimi/mobilecodegenerator
examples/ParkTraining/generated/ios/ParkTraining/ParkTraining/PhotoNewViewController.swift
2
3044
import UIKit import MobileCoreServices class PhotoNewViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate { @IBOutlet weak var savePhotoButton: UIButton! @IBOutlet weak var takenPhoto: UIImageView! override func viewDidLoad() { super.viewDidLoad() savePhotoButton.layer.cornerRadius = 2 } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewDidDisappear(animated: Bool) { super.viewDidDisappear(animated) } @IBAction func savePhotoButtonTouchDown(sender: UIButton) { //TODO Implement the action } @IBAction func savePhotoButtonTouchUpInside(sender: UIButton) { //TODO Implement the action } func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) { let mediaType = info[UIImagePickerControllerMediaType] as! NSString if mediaType.isEqualToString(kUTTypeImage as String) { let image = info[UIImagePickerControllerOriginalImage] as! UIImage self.takenPhoto.image = image UIImageWriteToSavedPhotosAlbum(image, self, #selector(PhotoNewViewController.completionSelector(wasSavedSuccessfully:didFinishSavingWithError:contextInfo:)), nil) } dismissViewControllerAnimated(true, completion: nil) } func imagePickerControllerDidCancel(picker: UIImagePickerController) { dismissViewControllerAnimated(true, completion: nil) } func completionSelector(wasSavedSuccessfully saved: Bool, didFinishSavingWithError error: NSErrorPointer, contextInfo:UnsafePointer<Void>) { if error != nil { let alert = UIAlertController(title: "Save Failed", message: "Failed to save from camera", preferredStyle: UIAlertControllerStyle.Alert) let cancelAction = UIAlertAction(title: "OK", style: .Cancel, handler: nil) alert.addAction(cancelAction) self.presentViewController(alert, animated: true, completion: nil) } // Check your model // You are missing the videocameraController or it does not match the videoview id } @IBAction func openPhotoCamera(sender: UIButton) { if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.Camera) { let picker = UIImagePickerController() picker.delegate = self picker.sourceType = .Camera picker.mediaTypes = [kUTTypeImage as String] presentViewController(picker, animated: true, completion: nil) } } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { } }
gpl-3.0
cc001/learnSwiftBySmallProjects
03-PlayLocalVideo/PlayLocalVideo/VideoCell.swift
1
715
// // VideoCell.swift // PlayLocalVideo // // Created by 陈闯 on 2016/12/15. // Copyright © 2016年 CC. All rights reserved. // import UIKit struct video { let image: String let title: String let source: String } class VideoCell: UITableViewCell { @IBOutlet weak var videoScreenshot: UIImageView! @IBOutlet weak var videoTitleLabel: UILabel! @IBOutlet weak var videoSourceLabel: UILabel! override func awakeFromNib() { super.awakeFromNib() // Initialization code } override func setSelected(_ selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) // Configure the view for the selected state } }
mit
danielpi/Swift-Playgrounds
Swift-Playgrounds/Swift Stanard Library/String.playground/section-1.swift
1
1927
// Swift Standard Library - Types - String // A String represents an ordered collection of characters. // Creating a String let emptyString = String() let equivilentString = "" let repeatedString = String(count: 5, repeatedValue: Character("a")) // Querying a String var string = "Hello, world!" let firstCheck = string.isEmpty string = "" let secondCheck = string.isEmpty string = "Hello, world!" let hasPrefixFirstCheck = string.hasPrefix("Hello") let hasPrefixSecondCheck = string.hasPrefix("hello") let hasSuffixFirstCheck = string.hasSuffix("world!") let hasSuffixSecondCheck = string.hasSuffix("World!") // Changing and Converting Strings string = "42" if let number = Int(string) { print("Got the number: \(number)") } else { print("Couldn't convert to a number") } // Operators // Concatinate + let combination = "Hello " + "world" // You can use the + operator with two strings as shown in the combination example, or with a string and a character in either order: let exclamationPoint: Character = "!" var charCombo = combination charCombo.append(exclamationPoint) //var extremeCombo: String = exclamationPoint //extremeCombo.append(charCombo) // Append += string = "Hello " string += "world" string.append(exclamationPoint) string // Equality == let string1 = "Hello world!" let string2 = "Hello" + " " + "world" + "!" let equality = string1 == string2 // Less than < let stringGreater = "Number 3" let stringLesser = "Number 2" let resulNotLessThan = stringGreater < stringLesser let resultIsLessThan = stringLesser < stringGreater // What is missing from this chapter? // - How does the less than operator work? "abc" < "def" "def" < "abc" "Number 2" < "number 1" // It just looks at the ordinal valu of the first character??? // - Does the greater than symbol work? "abc" > "def" "def" > "abc" "Number 2" > "number 1" // - How do you access the rodinal values of Characters?
mit
liuchuo/Swift-practice
20150619-6/20150619-6/MasterViewController.swift
1
3658
// // MasterViewController.swift // 20150619-6 // // Created by 欣 陈 on 15/6/19. // Copyright (c) 2015年 欣 陈. All rights reserved. // import UIKit class MasterViewController: UITableViewController { var detailViewController: DetailViewController? = nil var objects = [AnyObject]() override func awakeFromNib() { super.awakeFromNib() if UIDevice.currentDevice().userInterfaceIdiom == .Pad { self.clearsSelectionOnViewWillAppear = false self.preferredContentSize = CGSize(width: 320.0, height: 600.0) } } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. self.navigationItem.leftBarButtonItem = self.editButtonItem() let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "insertNewObject:") self.navigationItem.rightBarButtonItem = addButton if let split = self.splitViewController { let controllers = split.viewControllers self.detailViewController = controllers[controllers.count-1].topViewController as? DetailViewController } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func insertNewObject(sender: AnyObject) { objects.insert(NSDate(), atIndex: 0) let indexPath = NSIndexPath(forRow: 0, inSection: 0) self.tableView.insertRowsAtIndexPaths([indexPath], withRowAnimation: .Automatic) } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showDetail" { if let indexPath = self.tableView.indexPathForSelectedRow() { let object = objects[indexPath.row] as! NSDate let controller = (segue.destinationViewController as! UINavigationController).topViewController as! DetailViewController controller.detailItem = object controller.navigationItem.leftBarButtonItem = self.splitViewController?.displayModeButtonItem() controller.navigationItem.leftItemsSupplementBackButton = true } } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return objects.count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as! UITableViewCell let object = objects[indexPath.row] as! NSDate cell.textLabel!.text = object.description return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return true } override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { objects.removeAtIndex(indexPath.row) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view. } } }
gpl-2.0
TrustWallet/trust-wallet-ios
Trust/Settings/ViewControllers/BrowserConfigurationViewController.swift
1
2704
// Copyright DApps Platform Inc. All rights reserved. import Foundation import UIKit import Eureka import WebKit import Realm protocol BrowserConfigurationViewControllerDelegate: class { func didPressDeleteCache(in controller: BrowserConfigurationViewController) } final class BrowserConfigurationViewController: FormViewController { let viewModel = BrowserConfigurationViewModel() let preferences: PreferencesController weak var delegate: BrowserConfigurationViewControllerDelegate? init( preferences: PreferencesController = PreferencesController() ) { self.preferences = preferences super.init(nibName: nil, bundle: nil) } override func viewDidLoad() { super.viewDidLoad() navigationItem.title = viewModel.title form +++ Section() <<< PushRow<SearchEngine> { [weak self] in guard let `self` = self else { return } $0.title = self.viewModel.searchEngineTitle $0.options = self.viewModel.searchEngines $0.value = SearchEngine(rawValue: self.preferences.get(for: .browserSearchEngine)) ?? .default $0.selectorTitle = self.viewModel.searchEngineTitle $0.displayValueFor = { $0?.title } }.onChange { [weak self] row in guard let value = row.value else { return } self?.preferences.set(value: value.rawValue, for: .browserSearchEngine) }.onPresent { _, selectorController in selectorController.sectionKeyForValue = { _ in return "" } } +++ Section() <<< AppFormAppearance.button { [weak self] in guard let `self` = self else { return } $0.title = self.viewModel.clearBrowserCacheTitle }.onCellSelection { [weak self] _, _ in self?.confirmClear() }.cellUpdate { cell, _ in cell.textLabel?.textAlignment = .left cell.textLabel?.textColor = .black } } private func confirmClear() { confirm( title: viewModel.clearBrowserCacheConfirmTitle, message: viewModel.clearBrowserCacheConfirmMessage, okTitle: R.string.localizable.delete(), okStyle: .destructive, completion: { [weak self] result in guard let `self` = self else { return } switch result { case .success: self.delegate?.didPressDeleteCache(in: self) case .failure: break } } ) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
ChaselAn/ACTagView
ACTagViewDemo/ACTagView/ACTagButton.swift
1
1686
// // ACTagButton.swift // ACTagViewDemo // // Created by ac on 2017/7/30. // Copyright © 2017年 ac. All rights reserved. // import UIKit open class ACTagButton: UIButton { open var tagAttribute = ACTagAttribute() { didSet { setUpUI() } } override public init(frame: CGRect) { super.init(frame: frame) isUserInteractionEnabled = false isSelected = false } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override open var isSelected: Bool { didSet { if isSelected { backgroundColor = tagAttribute.selectedBackgroundColor layer.borderColor = tagAttribute.selectedBorderColor.cgColor } else { backgroundColor = tagAttribute.backgroundColor layer.borderColor = tagAttribute.borderColor.cgColor } } } private func setUpUI() { setTitle(tagAttribute.text, for: .normal) setTitleColor(tagAttribute.textColor, for: .normal) setTitleColor(tagAttribute.selectedTextColor, for: .selected) backgroundColor = tagAttribute.backgroundColor layer.borderWidth = tagAttribute.borderWidth titleLabel?.font = tagAttribute.font setBorderTyper(tagAttribute.borderType) } private func setBorderTyper(_ type: ACTagBorderType) { superview?.layoutIfNeeded() switch type { case .halfOfCircle: layer.cornerRadius = frame.height / 2 layer.masksToBounds = true case .custom(radius: let radius): layer.cornerRadius = radius layer.masksToBounds = true case .none: layer.cornerRadius = 0 layer.masksToBounds = false } } }
mit
venticake/RetricaImglyKit-iOS
RetricaImglyKit/Classes/Frontend/Stores/ImageStore.swift
1
3807
// This file is part of the PhotoEditor Software Development Kit. // Copyright (C) 2016 9elements GmbH <contact@9elements.com> // All rights reserved. // Redistribution and use in source and binary forms, without // modification, are permitted provided that the following license agreement // is approved and a legal/financial contract was signed by the user. // The license agreement can be found under the following link: // https://www.photoeditorsdk.com/LICENSE.txt import UIKit /** The `JSONStore` provides methods to retrieve JSON data from any URL. */ @available(iOS 8, *) @objc(IMGLYImageStoreProtocol) public protocol ImageStoreProtocol { /** Retrieves JSON data from the specified URL. - parameter url: A valid URL. - parameter completionBlock: A completion block. */ func get(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) } /** The `JSONStore` class provides methods to retrieve JSON data from any URL. It also caches the data due to efficiency. */ @available(iOS 8, *) @objc(IMGLYImageStore) public class ImageStore: NSObject, ImageStoreProtocol { /// A shared instance for convenience. public static let sharedStore = ImageStore() /// A service that is used to perform http get requests. public var requestService: RequestServiceProtocol = RequestService() private var store = NSCache() /// Whether or not to display an activity indicator while fetching the images. Default is `true`. public var showSpinner = true /** Retrieves JSON data from the specified URL. - parameter url: A valid URL. - parameter completionBlock: A completion block. */ public func get(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) { if let image = store[url] as? UIImage { completionBlock(image, nil) } else { if url.fileURL { if let data = NSData(contentsOfURL: url), image = UIImage(data: data) { if url.absoluteString.containsString(".9.") { completionBlock(image.resizableImageFrom9Patch(image), nil) } else { completionBlock(image, nil) } } else { let error = NSError(info: Localize("Image not found: ") + url.absoluteString) completionBlock(nil, error) } } else { startRequest(url, completionBlock: completionBlock) } } } private func startRequest(url: NSURL, completionBlock: (UIImage?, NSError?) -> Void) { showProgress() requestService.get(url, cached: true) { (data, error) -> Void in self.hideProgress() if error != nil { completionBlock(nil, error) } else { if let data = data { if var image = UIImage(data: data) { if url.absoluteString.containsString(".9.") { image = image.resizableImageFrom9Patch(image) } self.store[url] = image completionBlock(image, nil) } else { completionBlock(nil, NSError(info: "No image found at \(url).")) } } } } } private func showProgress() { if showSpinner { dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.showWithMessage(Localize("Downloading...")) } } } private func hideProgress() { dispatch_async(dispatch_get_main_queue()) { ProgressView.sharedView.hide() } } }
mit
motoom/ios-apps
Pour/Pour/AppDelegate.swift
2
273
import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { return true } }
mit
kumabook/FeedlyKit
Source/Subscription.swift
1
4344
// // Subscription.swift // MusicFav // // Created by Hiroki Kumamoto on 12/21/14. // Copyright (c) 2014 Hiroki Kumamoto. All rights reserved. // import Foundation import SwiftyJSON public final class Subscription: Stream, ResponseObjectSerializable, ResponseCollectionSerializable, ParameterEncodable { public let id: String public let title: String public let categories: [Category] public let website: String? public let sortId: String? public let updated: Int64? public let added: Int64? public let visualUrl: String? public let iconUrl: String? public let coverUrl: String? public let subscribers: Int? public let velocity: Float? public let partial: Bool? public let coverColor: String? public let contentType: String? public let topic: [String]? public override var streamId: String { return id } public override var streamTitle: String { return title } public class func collection(_ response: HTTPURLResponse, representation: Any) -> [Subscription]? { let json = JSON(representation) return json.arrayValue.map({ Subscription(json: $0) }) } @objc required public convenience init?(response: HTTPURLResponse, representation: Any) { let json = JSON(representation) self.init(json: json) } public init(json: JSON) { self.id = json["id"].stringValue self.title = json["title"].stringValue self.website = json["website"].stringValue self.categories = json["categories"].arrayValue.map({Category(json: $0)}) self.sortId = json["sortid"].string self.updated = json["updated"].int64 self.added = json["added"].int64 self.visualUrl = json["visualUrl"].string self.iconUrl = json["iconUrl"].string self.coverUrl = json["coverUrl"].string self.subscribers = json["subscribers"].int self.velocity = json["velocity"].float self.partial = json["partial"].bool self.coverColor = json["coverColor"].string self.contentType = json["contentType"].string self.topic = json["topic"].arrayValue.map({ $0.stringValue }) } public init(feed: Feed, categories: [Category]) { self.id = feed.id self.title = feed.title self.website = nil self.categories = categories self.sortId = nil self.updated = nil self.added = nil self.visualUrl = feed.visualUrl self.iconUrl = feed.iconUrl self.coverUrl = feed.coverUrl self.subscribers = feed.subscribers self.velocity = feed.velocity self.partial = feed.partial self.coverColor = feed.coverColor self.contentType = feed.contentType self.topic = feed.topics } public convenience init(id: String, title: String, categories: [Category]) { self.init(id: id, title: title, visualUrl: nil, categories: categories) } public init(id: String, title: String, visualUrl: String?, categories: [Category]) { self.id = id self.title = title self.website = nil self.categories = categories self.sortId = nil self.updated = nil self.added = nil self.visualUrl = visualUrl self.iconUrl = nil self.coverUrl = nil self.subscribers = nil self.velocity = nil self.partial = nil self.coverColor = nil self.contentType = nil self.topic = nil } public func toParameters() -> [String : Any] { return [ "title": title, "id": id, "categories": categories.map({ $0.toParameters() }) ] } public override var thumbnailURL: URL? { if let url = visualUrl { return URL(string: url) } else if let url = coverUrl { return URL(string: url) } else if let url = iconUrl { return URL(string: url) } else { return nil } } }
mit
oacastefanita/PollsFramework
Example/PollsFramework-mac/AppDelegate.swift
1
1464
// // AppDelegate.swift // PollsFramework-mac // // Created by Stefanita Oaca on 19/08/2017. // Copyright © 2017 CocoaPods. All rights reserved. // import Cocoa import PollsFramework @NSApplicationMain class AppDelegate: NSObject, NSApplicationDelegate { func applicationDidFinishLaunching(_ aNotification: Notification) { // Insert code here to initialize your application MKStoreKit.shared().startProductRequest() PollsFrameworkController.sharedInstance.setupWithBaseURL("https://demo.honeyshyam.com/api/v1", application:NSApplication.shared) NSApp.registerForRemoteNotifications(matching: .alert) } func applicationWillTerminate(_ aNotification: Notification) { // Insert code here to tear down your application } func application(_ application: NSApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { var newToken: String = "" for i in 0..<deviceToken.count { newToken += String(format: "%02.2hhx", deviceToken[i] as CVarArg) } APP_SESSION.pushNotificationsToken = newToken } func application(_ application: NSApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) { APP_SESSION.pushNotificationsToken = "Notifications not supported" } func application(_ application: NSApplication, didReceiveRemoteNotification userInfo: [String : Any]) { } }
mit
soapyigu/LeetCode_Swift
Array/MinimumSizeSubarraySum.swift
1
860
/** * Question Link: https://leetcode.com/problems/minimum-size-subarray-sum/ * Primary idea: Two Pointers, anchor the former and move forward the latter one to ensure the sum of subarray just covers the target * Note: There could be no invalid subarray which sum >= target * Time Complexity: O(n), Space Complexity: O(1) * */ class MinimumSizeSubarraySum { func minSubArrayLen(_ s: Int, _ nums: [Int]) -> Int { var miniSize = Int.max, start = 0, currentSum = 0 for (i, num) in nums.enumerated() { currentSum += num while currentSum >= s && start <= i { miniSize = min(miniSize, i - start + 1) currentSum -= nums[start] start += 1 } } return miniSize == Int.max ? 0 : miniSize } }
mit
WSDOT/wsdot-ios-app
wsdot/AmtrakCascadesStore.swift
1
13610
// // AmtrakCascadesStore.swift // WSDOT // // Copyright (c) 2016 Washington State Department of Transportation // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // 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. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see <http://www.gnu.org/licenses/> // import Foundation import Alamofire import SwiftyJSON class AmtrakCascadesStore { typealias FetchAmtrakSchedulesCompletion = (_ data: [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]?, _ error: Error?) -> () static func getSchedule(_ date: Date, originId: String, destId: String, completion: @escaping FetchAmtrakSchedulesCompletion) { let URL = "https://www.wsdot.wa.gov/traffic/api/amtrak/Schedulerest.svc/GetScheduleAsJson?AccessCode=" + ApiKeys.getWSDOTKey() + "&StatusDate=" + TimeUtils.formatTime(date, format: "MM/dd/yyyy") + "&TrainNumber=-1&FromLocation=" + originId + "&ToLocation=" + destId AF.request(URL).validate().responseJSON { response in switch response.result { case .success: if let value = response.data { let json = JSON(value) let serviceArrays = parseServiceItemsJSON(json) let servicePairs = getServiceStopPairs(serviceArrays) completion(servicePairs, nil) } case .failure(let error): print(error) completion(nil, error) } } } fileprivate static func parseServiceItemsJSON(_ json: JSON) -> [[AmtrakCascadesServiceStopItem]] { var tripItems = [[AmtrakCascadesServiceStopItem]]() var currentTripNum = -1 // current trip number - not the same as trip index b/c trips don't have to start at 0 or 1 var currentTripIndex = -1 // index into tripItems for (_, stationJson):(String, JSON) in json { if (currentTripNum != stationJson["TripNumber"].intValue) { tripItems.append([AmtrakCascadesServiceStopItem]()) currentTripNum = stationJson["TripNumber"].intValue currentTripIndex = currentTripIndex + 1 } let service = AmtrakCascadesServiceStopItem() service.stationId = stationJson["StationName"].stringValue service.stationName = stationJson["StationFullName"].stringValue service.trainNumber = stationJson["TrainNumber"].intValue service.tripNumer = stationJson["TripNumber"].intValue service.sortOrder = stationJson["SortOrder"].intValue service.arrivalComment = stationJson["ArrivalComment"].string service.departureComment = stationJson["DepartureComment"].string if let scheduledDepartureTime = stationJson["ScheduledDepartureTime"].string { service.scheduledDepartureTime = TimeUtils.parseJSONDateToNSDate(scheduledDepartureTime) } if let scheduledArrivalTime = stationJson["ScheduledArrivalTime"].string { service.scheduledArrivalTime = TimeUtils.parseJSONDateToNSDate(scheduledArrivalTime) } if service.scheduledDepartureTime == nil { service.scheduledDepartureTime = service.scheduledArrivalTime } if service.scheduledArrivalTime == nil { service.scheduledArrivalTime = service.scheduledDepartureTime } if let arrivComments = stationJson["ArrivalComment"].string { if (arrivComments.lowercased().contains("late")){ let mins = TimeUtils.getMinsFromString(arrivComments) service.arrivalComment = "Estimated " + arrivComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledArrivalTime!.addingTimeInterval(mins * 60)) } else if (arrivComments.lowercased().contains("early")){ let mins = TimeUtils.getMinsFromString(arrivComments) service.arrivalComment = "Estimated " + arrivComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledArrivalTime!.addingTimeInterval(mins * -60)) } else { service.arrivalComment = "Estimated " + arrivComments.lowercased() } } else { service.arrivalComment = "" } if let departComments = stationJson["ArrivalComment"].string { if (departComments.lowercased().contains("late")){ let mins = TimeUtils.getMinsFromString(departComments) service.departureComment = "Estimated " + departComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledDepartureTime!.addingTimeInterval(mins * 60)) } else if (departComments.lowercased().contains("early")){ let mins = TimeUtils.getMinsFromString(departComments) service.departureComment = "Estimated " + departComments.lowercased() + " at " + TimeUtils.getTimeOfDay(service.scheduledDepartureTime!.addingTimeInterval(mins * -60)) } else { service.departureComment = "Estimated " + departComments.lowercased() } } else { service.departureComment = "" } service.updated = TimeUtils.parseJSONDateToNSDate(stationJson["UpdateTime"].stringValue) tripItems[currentTripIndex].append(service) } return tripItems } // Creates origin-destination pairs from parsed JSON items of type [[AmtrakCascadesServiceStopItem]] // !!! Special case to consider is when the destination is not selected. In this case the pairs will have the destination value nil. static func getServiceStopPairs(_ servicesArrays: [[AmtrakCascadesServiceStopItem]]) -> [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]{ var servicePairs = [[(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]]() var pairIndex = 0 for services in servicesArrays { servicePairs.append([(AmtrakCascadesServiceStopItem,AmtrakCascadesServiceStopItem?)]()) var serviceIndex = 0 // index in services loop for service in services { if (services.endIndex - 1 <= serviceIndex) && (services.count == 1) { // last item and there was only one service, add a nil servicePairs[pairIndex].append((service, nil)) } else if (serviceIndex + 1 <= services.endIndex - 1){ // Middle Item if service.stationId != services[serviceIndex + 1].stationId { // Stations will be listed twice when there is a transfer, don't add them twice servicePairs[pairIndex].append((service, services[serviceIndex + 1])) } } serviceIndex = serviceIndex + 1 } pairIndex = pairIndex + 1 } return servicePairs } // Builds an array of Station data for using in calculating the users distance from the station. static func getStations() -> [AmtrakCascadesStationItem]{ var stations = [AmtrakCascadesStationItem]() stations.append(AmtrakCascadesStationItem(id: "VAC", name: "Vancouver, BC", lat: 49.2737293, lon: -123.0979175)) stations.append(AmtrakCascadesStationItem(id: "BEL", name: "Bellingham, WA", lat: 48.720423, lon: -122.5109386)) stations.append(AmtrakCascadesStationItem(id: "MVW", name: "Mount Vernon, WA", lat: 48.4185923, lon: -122.334973)) stations.append(AmtrakCascadesStationItem(id: "STW", name: "Stanwood, WA", lat: 48.2417732, lon: -122.3495322)) stations.append(AmtrakCascadesStationItem(id: "EVR", name: "Everett, WA", lat: 47.975512, lon: -122.197854)) stations.append(AmtrakCascadesStationItem(id: "EDM", name: "Edmonds, WA", lat: 47.8111305, lon: -122.3841639)) stations.append(AmtrakCascadesStationItem(id: "SEA", name: "Seattle, WA", lat: 47.6001899, lon: -122.3314322)) stations.append(AmtrakCascadesStationItem(id: "TUK", name: "Tukwila, WA", lat: 47.461079, lon: -122.242693)) stations.append(AmtrakCascadesStationItem(id: "TAC", name: "Tacoma, WA", lat: 47.2419939, lon: -122.4205623)) stations.append(AmtrakCascadesStationItem(id: "OLW", name: "Olympia/Lacey, WA", lat: 46.9913576, lon: -122.793982)) stations.append(AmtrakCascadesStationItem(id: "CTL", name: "Centralia, WA", lat: 46.7177596, lon: -122.9528291)) stations.append(AmtrakCascadesStationItem(id: "KEL", name: "Kelso/Longview, WA", lat: 46.1422504, lon: -122.9132438)) stations.append(AmtrakCascadesStationItem(id: "VAN", name: "Vancouver, WA", lat: 45.6294472, lon: -122.685568)) stations.append(AmtrakCascadesStationItem(id: "PDX", name: "Portland, OR", lat: 45.528639, lon: -122.676284)) stations.append(AmtrakCascadesStationItem(id: "ORC", name: "Oregon City, OR", lat: 45.3659422, lon: -122.5960671)) stations.append(AmtrakCascadesStationItem(id: "SLM", name: "Salem, OR", lat: 44.9323665, lon: -123.0281591)) stations.append(AmtrakCascadesStationItem(id: "ALY", name: "Albany, OR", lat: 44.6300975, lon: -123.1041787)) stations.append(AmtrakCascadesStationItem(id: "EUG", name: "Eugene, OR", lat: 44.055506, lon: -123.094523)) return stations.sorted(by: {$0.name > $1.name}) } // Used to populate the destination selection static func getDestinationData() -> [String] { var dest = [String]() dest.append("Vancouver, BC") dest.append("Bellingham, WA") dest.append("Mount Vernon, WA") dest.append("Stanwood, WA") dest.append("Everett, WA") dest.append("Edmonds, WA") dest.append("Seattle, WA") dest.append("Tukwila, WA") dest.append("Tacoma, WA") dest.append("Olympia/Lacey, WA") dest.append("Centralia, WA") dest.append("Kelso/Longview, WA") dest.append("Vancouver, WA") dest.append("Portland, OR") dest.append("Oregon City, OR") dest.append("Salem, OR") dest.append("Albany, OR") dest.append("Eugene, OR") dest.sort() // dest.insert("All", at: 0) return dest } // Used to populate the origin selection static func getOriginData() -> [String]{ var origins = [String]() origins.append("Vancouver, BC") origins.append("Bellingham, WA") origins.append("Mount Vernon, WA") origins.append("Stanwood, WA") origins.append("Everett, WA") origins.append("Edmonds, WA") origins.append("Seattle, WA") origins.append("Tukwila, WA") origins.append("Tacoma, WA") origins.append("Olympia/Lacey, WA") origins.append("Centralia, WA") origins.append("Kelso/Longview, WA") origins.append("Vancouver, WA") origins.append("Portland, OR") origins.append("Oregon City, OR") origins.append("Salem, OR") origins.append("Albany, OR") origins.append("Eugene, OR") return origins.sorted() } // Station names to ID mapping. static let stationIdsMap: Dictionary<String, String> = [ "All": "N/A", "Vancouver, BC": "VAC", "Bellingham, WA": "BEL", "Mount Vernon, WA": "MVW", "Stanwood, WA": "STW", "Everett, WA": "EVR", "Edmonds, WA": "EDM", "Seattle, WA": "SEA", "Tukwila, WA": "TUK", "Tacoma, WA": "TAC", "Olympia/Lacey, WA": "OLW", "Centralia, WA": "CTL", "Kelso/Longview, WA": "KEL", "Vancouver, WA": "VAN", "Portland, OR": "PDX", "Oregon City, OR": "ORC", "Salem, OR": "SLM", "Albany, OR": "ALY", "Eugene, OR": "EUG" ] static let trainNumberMap: Dictionary<Int, String> = [ 7: "Empire Builder Train", 8: "Empire Builder Train", 11: "Coast Starlight Train", 14: "Coast Starlight Train", 27: "Empire Builder Train", 28: "Empire Builder Train", 500: "Amtrak Cascades Train", 501: "Amtrak Cascades Train", 502: "Amtrak Cascades Train", 503: "Amtrak Cascades Train", 504: "Amtrak Cascades Train", 505: "Amtrak Cascades Train", 506: "Amtrak Cascades Train", 507: "Amtrak Cascades Train", 508: "Amtrak Cascades Train", 509: "Amtrak Cascades Train", 510: "Amtrak Cascades Train", 511: "Amtrak Cascades Train", 512: "Amtrak Cascades Train", 513: "Amtrak Cascades Train", 516: "Amtrak Cascades Train", 517: "Amtrak Cascades Train", 518: "Amtrak Cascades Train", 519: "Amtrak Cascades Train" ] }
gpl-3.0
airspeedswift/swift
test/Sema/enum_conformance_synthesis.swift
3
12063
// RUN: %target-swift-frontend -typecheck -verify -primary-file %s %S/Inputs/enum_conformance_synthesis_other.swift -verify-ignore-unknown -swift-version 4 var hasher = Hasher() enum Foo: CaseIterable { case A, B } func foo() { if Foo.A == .B { } var _: Int = Foo.A.hashValue Foo.A.hash(into: &hasher) _ = Foo.allCases Foo.A == Foo.B // expected-warning {{result of operator '==' is unused}} } enum Generic<T>: CaseIterable { case A, B static func method() -> Int { // Test synthesis of == without any member lookup being done if A == B { } return Generic.A.hashValue } } func generic() { if Generic<Foo>.A == .B { } var _: Int = Generic<Foo>.A.hashValue Generic<Foo>.A.hash(into: &hasher) _ = Generic<Foo>.allCases } func localEnum() -> Bool { enum Local { case A, B } return Local.A == .B } enum CustomHashable { case A, B func hash(into hasher: inout Hasher) {} } func ==(x: CustomHashable, y: CustomHashable) -> Bool { return true } func customHashable() { if CustomHashable.A == .B { } var _: Int = CustomHashable.A.hashValue CustomHashable.A.hash(into: &hasher) } // We still synthesize conforming overloads of '==' and 'hashValue' if // explicit definitions don't satisfy the protocol requirements. Probably // not what we actually want. enum InvalidCustomHashable { case A, B var hashValue: String { return "" } // expected-error {{invalid redeclaration of synthesized implementation for protocol requirement 'hashValue'}} } func ==(x: InvalidCustomHashable, y: InvalidCustomHashable) -> String { return "" } func invalidCustomHashable() { if InvalidCustomHashable.A == .B { } var s: String = InvalidCustomHashable.A == .B s = InvalidCustomHashable.A.hashValue _ = s var _: Int = InvalidCustomHashable.A.hashValue InvalidCustomHashable.A.hash(into: &hasher) } // Check use of an enum's synthesized members before the enum is actually declared. struct UseEnumBeforeDeclaration { let eqValue = EnumToUseBeforeDeclaration.A == .A let hashValue = EnumToUseBeforeDeclaration.A.hashValue } enum EnumToUseBeforeDeclaration { case A } func getFromOtherFile() -> AlsoFromOtherFile { return .A } func overloadFromOtherFile() -> YetAnotherFromOtherFile { return .A } func overloadFromOtherFile() -> Bool { return false } func useEnumBeforeDeclaration() { // Check enums from another file in the same module. if FromOtherFile.A == .A {} let _: Int = FromOtherFile.A.hashValue if .A == getFromOtherFile() {} if .A == overloadFromOtherFile() {} } // Complex enums are not automatically Equatable, Hashable, or CaseIterable. enum Complex { case A(Int) case B } func complex() { if Complex.A(1) == .B { } // expected-error{{cannot convert value of type 'Complex' to expected argument type 'CustomHashable'}} } // Enums with equatable payloads are equatable if they explicitly conform. enum EnumWithEquatablePayload: Equatable { case A(Int) case B(String, Int) case C } func enumWithEquatablePayload() { if EnumWithEquatablePayload.A(1) == .B("x", 1) { } if EnumWithEquatablePayload.A(1) == .C { } if EnumWithEquatablePayload.B("x", 1) == .C { } } // Enums with hashable payloads are hashable if they explicitly conform. enum EnumWithHashablePayload: Hashable { case A(Int) case B(String, Int) case C } func enumWithHashablePayload() { _ = EnumWithHashablePayload.A(1).hashValue _ = EnumWithHashablePayload.B("x", 1).hashValue _ = EnumWithHashablePayload.C.hashValue EnumWithHashablePayload.A(1).hash(into: &hasher) EnumWithHashablePayload.B("x", 1).hash(into: &hasher) EnumWithHashablePayload.C.hash(into: &hasher) // ...and they should also inherit equatability from Hashable. if EnumWithHashablePayload.A(1) == .B("x", 1) { } if EnumWithHashablePayload.A(1) == .C { } if EnumWithHashablePayload.B("x", 1) == .C { } } // Enums with non-hashable payloads don't derive conformance. struct NotHashable {} enum EnumWithNonHashablePayload: Hashable { // expected-error 2 {{does not conform}} case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'EnumWithNonHashablePayload' to 'Equatable'}} } // Enums should be able to derive conformances based on the conformances of // their generic arguments. enum GenericHashable<T: Hashable>: Hashable { case A(T) case B } func genericHashable() { if GenericHashable<String>.A("a") == .B { } var _: Int = GenericHashable<String>.A("a").hashValue } // But it should be an error if the generic argument doesn't have the necessary // constraints to satisfy the conditions for derivation. enum GenericNotHashable<T: Equatable>: Hashable { // expected-error 2 {{does not conform to protocol 'Hashable'}} case A(T) //expected-note 2 {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'GenericNotHashable<T>' to 'Hashable'}} case B } func genericNotHashable() { if GenericNotHashable<String>.A("a") == .B { } let _: Int = GenericNotHashable<String>.A("a").hashValue // No error. hashValue is always synthesized, even if Hashable derivation fails GenericNotHashable<String>.A("a").hash(into: &hasher) // expected-error {{value of type 'GenericNotHashable<String>' has no member 'hash'}} } // An enum with no cases should also derive conformance. enum NoCases: Hashable {} // rdar://19773050 private enum Bar<T> { case E(Unknown<T>) // expected-error {{cannot find type 'Unknown' in scope}} mutating func value() -> T { switch self { // FIXME: Should diagnose here that '.' needs to be inserted, but E has an ErrorType at this point case E(let x): return x.value } } } // Equatable extension -- rdar://20981254 enum Instrument { case Piano case Violin case Guitar } extension Instrument : Equatable {} extension Instrument : CaseIterable {} enum UnusedGeneric<T> { case a, b, c } extension UnusedGeneric : CaseIterable {} // Explicit conformance should work too public enum Medicine { case Antibiotic case Antihistamine } extension Medicine : Equatable {} public func ==(lhs: Medicine, rhs: Medicine) -> Bool { return true } // No explicit conformance; but it can be derived, for the same-file cases. enum Complex2 { case A(Int) case B } extension Complex2 : Hashable {} extension Complex2 : CaseIterable {} // expected-error {{type 'Complex2' does not conform to protocol 'CaseIterable'}} extension FromOtherFile: CaseIterable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} extension CaseIterableAcrossFiles: CaseIterable { public static var allCases: [CaseIterableAcrossFiles] { return [ .A ] } } // No explicit conformance and it cannot be derived. enum NotExplicitlyHashableAndCannotDerive { case A(NotHashable) //expected-note {{associated value type 'NotHashable' does not conform to protocol 'Hashable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Hashable'}} // expected-note@-1 {{associated value type 'NotHashable' does not conform to protocol 'Equatable', preventing synthesized conformance of 'NotExplicitlyHashableAndCannotDerive' to 'Equatable'}} } extension NotExplicitlyHashableAndCannotDerive : Hashable {} // expected-error 2 {{does not conform}} extension NotExplicitlyHashableAndCannotDerive : CaseIterable {} // expected-error {{does not conform}} // Verify that conformance (albeit manually implemented) can still be added to // a type in a different file. extension OtherFileNonconforming: Hashable { static func ==(lhs: OtherFileNonconforming, rhs: OtherFileNonconforming) -> Bool { return true } func hash(into hasher: inout Hasher) {} } // ...but synthesis in a type defined in another file doesn't work yet. extension YetOtherFileNonconforming: Equatable {} // expected-error {{cannot be automatically synthesized in an extension in a different file to the type}} extension YetOtherFileNonconforming: CaseIterable {} // expected-error {{does not conform}} // Verify that an indirect enum doesn't emit any errors as long as its "leaves" // are conformant. enum StringBinaryTree: Hashable { indirect case tree(StringBinaryTree, StringBinaryTree) case leaf(String) } // Add some generics to make it more complex. enum BinaryTree<Element: Hashable>: Hashable { indirect case tree(BinaryTree, BinaryTree) case leaf(Element) } // Verify mutually indirect enums. enum MutuallyIndirectA: Hashable { indirect case b(MutuallyIndirectB) case data(Int) } enum MutuallyIndirectB: Hashable { indirect case a(MutuallyIndirectA) case data(Int) } // Verify that it works if the enum itself is indirect, rather than the cases. indirect enum TotallyIndirect: Hashable { case another(TotallyIndirect) case end(Int) } // Check the use of conditional conformances. enum ArrayOfEquatables : Equatable { case only([Int]) } struct NotEquatable { } enum ArrayOfNotEquatables : Equatable { // expected-error{{type 'ArrayOfNotEquatables' does not conform to protocol 'Equatable'}} case only([NotEquatable]) //expected-note {{associated value type '[NotEquatable]' does not conform to protocol 'Equatable', preventing synthesized conformance of 'ArrayOfNotEquatables' to 'Equatable'}} } // Conditional conformances should be able to be synthesized enum GenericDeriveExtension<T> { case A(T) } extension GenericDeriveExtension: Equatable where T: Equatable {} extension GenericDeriveExtension: Hashable where T: Hashable {} // Incorrectly/insufficiently conditional shouldn't work enum BadGenericDeriveExtension<T> { case A(T) //expected-note {{associated value type 'T' does not conform to protocol 'Hashable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Hashable'}} //expected-note@-1 {{associated value type 'T' does not conform to protocol 'Equatable', preventing synthesized conformance of 'BadGenericDeriveExtension<T>' to 'Equatable'}} } extension BadGenericDeriveExtension: Equatable {} // // expected-error@-1 {{type 'BadGenericDeriveExtension<T>' does not conform to protocol 'Equatable'}} extension BadGenericDeriveExtension: Hashable where T: Equatable {} // expected-error@-1 {{type 'BadGenericDeriveExtension' does not conform to protocol 'Hashable'}} // But some cases don't need to be conditional, even if they look similar to the // above struct AlwaysHashable<T>: Hashable {} enum UnusedGenericDeriveExtension<T> { case A(AlwaysHashable<T>) } extension UnusedGenericDeriveExtension: Hashable {} // Cross-file synthesis is disallowed for conditional cases just as it is for // non-conditional ones. extension GenericOtherFileNonconforming: Equatable where T: Equatable {} // expected-error@-1{{implementation of 'Equatable' cannot be automatically synthesized in an extension in a different file to the type}} // rdar://problem/41852654 // There is a conformance to Equatable (or at least, one that implies Equatable) // in the same file as the type, so the synthesis is okay. Both orderings are // tested, to catch choosing extensions based on the order of the files, etc. protocol ImplierMain: Equatable {} enum ImpliedMain: ImplierMain { case a(Int) } extension ImpliedOther: ImplierMain {} // FIXME: Remove -verify-ignore-unknown. // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(Foo, Foo) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '<T> (Generic<T>, Generic<T>) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(InvalidCustomHashable, InvalidCustomHashable) -> Bool' // <unknown>:0: error: unexpected note produced: candidate has non-matching type '(EnumToUseBeforeDeclaration, EnumToUseBeforeDeclaration) -> Bool'
apache-2.0
PGSSoft/AutoMate
AutoMateExample/AutoMateExampleUITests/PageObjects/CollectionPage.swift
1
725
// // CollectionPage.swift // AutoMateExample // // Created by Bartosz Janda on 06.04.2017. // Copyright © 2017 PGS Software. All rights reserved. // import XCTest import AutoMate // MARK: - CollectionPage open class CollectionPage: BaseAppPage, PushedPage { // MARK: Elements open var collectionView: XCUIElement { return view.collectionViews[Locators.collectionView] } // MARK: Helpers open func cell(with name: String) -> XCUIElement { return collectionView.cells.element(containingLabels: [Locators.cellName: name]) } } // MARK: - Locators private extension CollectionPage { enum Locators: String, Locator { case collectionView case cellName } }
mit
PlanTeam/BSON
Sources/BSON/Types/Optional.swift
1
583
extension Optional where Wrapped == Primitive { public subscript(key: String) -> Primitive? { get { return (self as? Document)?[key] } set { var document = (self as? Document) ?? [:] document[key] = newValue self = document } } public subscript(index: Int) -> Primitive { get { return (self as! Document)[index] } set { var document = self as! Document document[index] = newValue self = document } } }
mit
headione/criticalmaps-ios
CriticalMapsKit/Sources/SharedModels/CoordinatieRegion.swift
1
875
import CoreLocation import Foundation import MapKit /// A structure for region data public struct CoordinateRegion: Equatable { public var center: CLLocationCoordinate2D public var span: MKCoordinateSpan public init( center: CLLocationCoordinate2D, span: MKCoordinateSpan ) { self.center = center self.span = span } public init(coordinateRegion: MKCoordinateRegion) { self.center = coordinateRegion.center self.span = coordinateRegion.span } public var asMKCoordinateRegion: MKCoordinateRegion { .init(center: self.center, span: self.span) } public static func == (lhs: Self, rhs: Self) -> Bool { lhs.center.latitude == rhs.center.latitude && lhs.center.longitude == rhs.center.longitude && lhs.span.latitudeDelta == rhs.span.latitudeDelta && lhs.span.longitudeDelta == rhs.span.longitudeDelta } }
mit
adamastern/decked
Example/Example/ViewController.swift
1
434
// // ViewController.swift // Example // // Created by Adam Stern on 23/04/2016. // Copyright © 2016 decked. All rights reserved. // import UIKit import Decked class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
mit
telldus/telldus-live-mobile-v3
ios/HomescreenWidget/UIViews/SensorWidget/SensorClass.swift
1
883
// // SensorClass.swift // TelldusLiveApp // // Created by Rimnesh Fernandez on 23/10/20. // Copyright © 2020 Telldus Technologies AB. All rights reserved. // import Foundation class SensorClass { static let intervalOne: Dictionary<String, Any> = [ "id": "1", "label": "Update every 5 minutes", "valueInMin": 5, ] static let intervalTwo: Dictionary<String, Any> = [ "id": "2", "label": "Update every 10 minutes", "valueInMin": 10, ] static let intervalThree: Dictionary<String, Any> = [ "id": "3", "label": "Update every 30 minutes", "valueInMin": 30, ] static let intervalFour: Dictionary<String, Any> = [ "id": "4", "label": "Update every 1 hour", "valueInMin": 60, ] static let SensorUpdateInterval: [Dictionary<String, Any>] = [ intervalOne, intervalTwo, intervalThree, intervalFour ] }
gpl-3.0
headione/criticalmaps-ios
CriticalMapsKit/Sources/ApiClient/Endpoints.swift
1
165
import Foundation public enum Endpoints { public static let criticalmassInEndpoint = "criticalmass.in" public static let apiEndpoint = "api.criticalmaps.net" }
mit
vmanot/swift-package-manager
Fixtures/DependencyResolution/External/SimpleCDep/Bar/Package.swift
9
138
import PackageDescription let package = Package( name: "Bar", dependencies: [ .Package(url: "../Foo", majorVersion: 1)])
apache-2.0
nodekit-io/nodekit-darwin
src/nodekit/NKElectro/NKEProtocol/NKE_ProtocolFileDecode.swift
1
3972
/* * nodekit.io * * Copyright (c) 2016-7 OffGrid Networks. All Rights Reserved. * * 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. */ import Foundation class NKE_ProtocolFileDecode: NSObject { var resourcePath: NSString? // The path to the bundle resource var urlPath: NSString // The relative path from root var fileName: NSString // The filename, with extension var fileBase: NSString // The filename, without the extension var fileExtension: NSString // The file extension var mimeType: NSString? // The mime type var textEncoding: NSString? // The text encoding init(url: NSURL) { resourcePath = nil var _fileTypes: [NSString: NSString] = [ "html": "text/html" , "js" : "text/plain" , "css": "text/css", "svg": "image/svg+xml"] urlPath = (url.path! as NSString).stringByDeletingLastPathComponent if urlPath.substringToIndex(1) == "/" { urlPath = urlPath.substringFromIndex(1) } urlPath = (("app" as NSString).stringByAppendingPathComponent(url.host!) as NSString).stringByAppendingPathComponent(urlPath as String) fileExtension = url.pathExtension!.lowercaseString fileName = url.lastPathComponent! if (fileExtension.length == 0) { fileBase = fileName } else { fileBase = fileName.substringToIndex(fileName.length - fileExtension.length - 1) } mimeType = nil textEncoding = nil super.init() if (fileName.length > 0) { resourcePath = urlPath.stringByAppendingPathComponent(fileName as String) if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } if ((resourcePath == nil) && (fileExtension.length > 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent(fileName as String) if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent((fileBase as String) + ".html") if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } if ((resourcePath == nil) && (fileExtension.length == 0)) { resourcePath = (("app" as NSString).stringByAppendingPathComponent(urlPath as String) as NSString).stringByAppendingPathComponent("index.html") if (!NKStorage.exists(resourcePath as! String)) { resourcePath = nil } } mimeType = _fileTypes[fileExtension] if (mimeType != nil) { if mimeType!.hasPrefix("text") { textEncoding = "utf-8" } } } } func exists() -> Bool { return (resourcePath != nil) } }
apache-2.0
paulkite/AlertHandler
AlertHandlerDemo/AlertHandlerDemo/AppDelegate.swift
1
2158
// // AppDelegate.swift // V77AlertHandler // // Created by Paul Kite on 3/11/16. // Copyright © 2016 Voodoo77 Studios, Inc. All rights reserved. // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { // Override point for customization after application launch. return true } func applicationWillResignActive(application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game. } func applicationDidEnterBackground(application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(application: UIApplication) { // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } }
mit
reddream520/DouYu
DouYuZhiBo/DouYuZhiBo/Classes/Discover/Controller/DiscoverViewController.swift
1
868
// // DiscoverViewController.swift // DouYuZhiBo // // Created by WeiMac on 2017/6/26. // Copyright © 2017年 Snail. All rights reserved. // import UIKit class DiscoverViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* // 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.destinationViewController. // Pass the selected object to the new view controller. } */ }
mit
AthensWorks/OBWapp-iOS
Brew Week/Brew Week/EstablishmentViewController.swift
1
13676
// // EstablishmentViewController.swift // Brew Week // // Created by Ben Lachman on 5/29/15. // Copyright (c) 2015 Ohio Brew Week. All rights reserved. // import UIKit import CoreData import Alamofire class EstablishmentViewController: UITableViewController, NSFetchedResultsControllerDelegate, ManagedObjectViewController, UISearchResultsUpdating { let searchController = UISearchController(searchResultsController: nil) var managedObjectContext: NSManagedObjectContext? = nil var filteredEstablishments = [Establishment]() override func awakeFromNib() { super.awakeFromNib() } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. searchController.searchResultsUpdater = self searchController.dimsBackgroundDuringPresentation = false definesPresentationContext = true tableView.tableHeaderView = searchController.searchBar // Request beers Alamofire.request(.GET, Endpoint(path: "beers")).validate().responseJSON { response in switch response.result { case .Success(let beersJSON as [String: AnyObject]): Beer.beersFromJSON(beersJSON) guard let guid = UIDevice.currentDevice().identifierForVendor?.UUIDString else { return } var params: [String: AnyObject] = ["device_guid": guid]; let appDelegate = UIApplication.sharedApplication().delegate as? AppDelegate // { // "beer_id": 123, // "device_guid": "GUID", // "age": 35, // "lat": "Y", // "lon": "X", // } if let drinker = appDelegate?.drinker { params["age"] = drinker.ageInYears } if let location = appDelegate?.locationManager?.location { params["lat"] = location.coordinate.latitude params["lon"] = location.coordinate.longitude } // Request establishmets after successful beers response, // as establishments will omit any beers not already in the store Alamofire.request(.GET, Endpoint(path: "establishments"), parameters: params, encoding: .URL).validate().responseJSON { response in switch response.result { case .Success(let value as [String: AnyObject]): Establishment.establishmentsFromJSON(value) case .Failure(let error): print("Establishments response is error: \(error)") default: print("Establishments response is incorrectly typed") } } case .Failure(let error): print("Beers response is error: \(error)") default: print("Beers response is incorrectly typed") } } // Request breweries Alamofire.request(.GET, Endpoint(path: "breweries")).validate().responseJSON { response in switch response.result { case .Success(let breweriesJSON as [String: AnyObject]): Brewery.breweriesFromJSON(breweriesJSON) case .Failure(let error): print("Breweries response is error: \(error)") default: print("Breweries response is incorrectly typed") } } } override func viewDidAppear(animated: Bool) { if (UIApplication.sharedApplication().delegate as? AppDelegate)?.drinker == nil { let modal = UIStoryboard(name: "Main", bundle: nil).instantiateViewControllerWithIdentifier("UserVerificationViewController") as! UserVerificationViewController modal.modalTransitionStyle = .CoverVertical self.presentViewController(modal, animated: true, completion: nil) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } //MARK: insertNewObject @IBAction func insertNewObject(sender: AnyObject) { let context = self.fetchedResultsController.managedObjectContext let entity = self.fetchedResultsController.fetchRequest.entity! let 🏬 = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context) as! Establishment // If appropriate, configure the new managed object. // Normally you should use accessor methods, but using KVC here avoids the need to add a custom class to the template. 🏬.name = "Dive Bar" 🏬.address = "12 Grimey Lane" // Save the context. do { try context.save() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } } // MARK: - Actions @IBAction func refreshEstablishments(sender: UIRefreshControl) { // /establishment/:establishment_id/beer_statuses Alamofire.request(.GET, Endpoint(path: "establishments")).validate().responseJSON { establishmentsResponse in switch establishmentsResponse.result { case .Success(let establishmentsJSON as [String: [AnyObject]]): Establishment.establishmentsFromJSON(establishmentsJSON) case .Failure(let error): print("Establishments response is error: \(error)") default: print("Establishments response is incorrectly typed") } self.refreshControl?.endRefreshing() } } // MARK: - Segues override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "showBeers" { if let indexPath = self.tableView.indexPathForSelectedRow { let selectedEstablishment: Establishment if filtering { selectedEstablishment = filteredEstablishments[indexPath.row] } else { selectedEstablishment = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Establishment } _ = selectedEstablishment.beerStatuses let controller = segue.destinationViewController as! BeersTableViewController controller.managedObjectContext = managedObjectContext controller.establishment = selectedEstablishment } } else if segue.identifier == "showMap" { let controller = segue.destinationViewController as! MapViewController controller.managedObjectContext = managedObjectContext } } // MARK: - Table View override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return self.fetchedResultsController.sections?.count ?? 0 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { if filtering { return filteredEstablishments.count } let sectionInfo = self.fetchedResultsController.sections![section] return sectionInfo.numberOfObjects } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("EstablishmentCell", forIndexPath: indexPath) self.configureCell(cell, atIndexPath: indexPath) return cell } override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) { let 🏬: Establishment if filtering { 🏬 = filteredEstablishments[indexPath.row] } else { 🏬 = self.fetchedResultsController.objectAtIndexPath(indexPath) as! Establishment } cell.textLabel?.text = 🏬.name var displayAddress = 🏬.address if let rangeOfAthens = displayAddress.rangeOfString(", Athens", options: .CaseInsensitiveSearch) { displayAddress = displayAddress.substringWithRange(displayAddress.startIndex ..< rangeOfAthens.startIndex).stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceAndNewlineCharacterSet()) } cell.detailTextLabel?.text = displayAddress } // MARK: - Fetched results controller var fetchedResultsController: NSFetchedResultsController { if _fetchedResultsController != nil { return _fetchedResultsController! } let fetchRequest = NSFetchRequest() // Edit the entity name as appropriate. let entity = NSEntityDescription.entityForName("Establishment", inManagedObjectContext: self.managedObjectContext!) fetchRequest.entity = entity // Set the batch size to a suitable number. fetchRequest.fetchBatchSize = 50 // Edit the sort key as appropriate. //TODO: we need to sort based on the order sent by the server. add index generated from the order received from the server. let sortDescriptor = NSSortDescriptor(key: "name", ascending: true) fetchRequest.sortDescriptors = [sortDescriptor] // Edit the section name key path and cache name if appropriate. // nil for section name key path means "no sections". let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Establishments") aFetchedResultsController.delegate = self _fetchedResultsController = aFetchedResultsController NSFetchedResultsController.deleteCacheWithName("Establishments") do { try _fetchedResultsController!.performFetch() } catch { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. //println("Unresolved error \(error), \(error.userInfo)") abort() } return _fetchedResultsController! } var _fetchedResultsController: NSFetchedResultsController? = nil /* func controllerWillChangeContent(controller: NSFetchedResultsController) { self.tableView.beginUpdates() } func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) { switch type { case .Insert: self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) case .Delete: self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade) default: return } } func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) { switch type { case .Insert: tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) case .Delete: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) case .Update: self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!) case .Move: tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade) tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade) default: return } } func controllerDidChangeContent(controller: NSFetchedResultsController) { self.tableView.endUpdates() } */ // Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed. func controllerDidChangeContent(controller: NSFetchedResultsController) { // In the simplest, most efficient, case, reload the table view. self.tableView.reloadData() } // MARK: - Filtering var filtering: Bool { return searchController.active && searchController.searchBar.text != "" } func filterContentForSearchText(searchText: String, scope: String = "All") { let substrings = searchText.componentsSeparatedByString(" ") .filter { $0.isEmpty == false } .map { $0.lowercaseString } filteredEstablishments = fetchedResultsController.fetchedObjects? .flatMap { $0 as? Establishment } .filter { establishment in let lowercaseName = establishment.name.lowercaseString for substring in substrings { if lowercaseName.containsString(substring) == false { return false } } return true } ?? [Establishment]() tableView.reloadData() } func updateSearchResultsForSearchController(searchController: UISearchController) { guard let searchText = searchController.searchBar.text else { return } filterContentForSearchText(searchText) } }
apache-2.0
CoderST/DYZB
DYZB/DYZB/Class/Tools/NetworkTools.swift
1
954
// // NetworkTools.swift // DYZB // // Created by xiudou on 16/9/20. // Copyright © 2016年 xiudo. All rights reserved. // import UIKit import Alamofire enum MethodType { case get case post } class NetworkTools { class func requestData(_ type : MethodType,URLString : String,parameters:[String : Any]? = nil,finishCallBack : @escaping (_ result : Any) -> ()){ // 确定请求类型 let method = type == .get ? HTTPMethod.get : HTTPMethod.post // 发送网络请求 Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in if let url = response.request?.url{ print("请求的URL = \(url)") } // 守护结果 guard let result = response.result.value else{ debugLog("没有结果") return } finishCallBack(result: result) } } }
mit
illescasDaniel/Questions
Questions/ViewControllers/LicensesViewController.swift
1
2900
import UIKit class LicensesViewController: UIViewController { @IBOutlet weak var textView: UITextView! private lazy var licensesAttributedText: NSAttributedString = { let headlineFontStyle = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .headline)] let subheadFontStyle = [NSAttributedString.Key.font: UIFont.preferredFont(forTextStyle: .subheadline)] let bgMusicBensound = "Royalty Free Music from Bensound:\n".attributedStringWith(headlineFontStyle) let bgMusicBensoundLink = "http://www.bensound.com/royalty-free-music/track/the-lounge\n".attributedStringWith(subheadFontStyle) let correctSound = "\nCorrect.mp3, creator: LittleRainySeasons:\n".attributedStringWith(headlineFontStyle) let correctSoundLink = "https://www.freesound.org/people/LittleRainySeasons/sounds/335908\n".attributedStringWith(subheadFontStyle) let incorrectSound = "\nGame Sound Wrong.wav, creator: Bertrof\n\"This work is licensed under the Attribution License.\": \n".attributedStringWith(headlineFontStyle) let incorrectSoundLink = "https://www.freesound.org/people/Bertrof/sounds/131657/\n https://creativecommons.org/licenses/by/3.0/legalcode\n".attributedStringWith(subheadFontStyle) let sideVolumeHUD = "\nSideVolumeHUD - illescasDaniel. Licensed under the MIT License\n".attributedStringWith(headlineFontStyle) let sideVolumeHUDLink = "https://github.com/illescasDaniel/SideVolumeHUD\n".attributedStringWith(subheadFontStyle) let icons = "\nIcons 8\n".attributedStringWith(headlineFontStyle) let icon1 = "https://icons8.com/icon/1054/screenshot".attributedStringWith(subheadFontStyle) let icon2 = "https://icons8.com/icon/8186/create-filled".attributedStringWith(subheadFontStyle) let icon3 = "https://icons8.com/icon/2897/cloud-filled".attributedStringWith(subheadFontStyle) let attributedText = bgMusicBensound + bgMusicBensoundLink + correctSound + correctSoundLink + incorrectSound + incorrectSoundLink + sideVolumeHUD + sideVolumeHUDLink + icons + icon1 + icon2 + icon3 return attributedText }() // MARK: View life cycle override func viewDidLoad() { super.viewDidLoad() self.navigationItem.title = L10n.Settings_Options_Licenses self.textView.attributedText = licensesAttributedText self.textView.textAlignment = .center self.textView.textContainerInset = UIEdgeInsets(top: 30, left: 10, bottom: 30, right: 10) self.loadCurrentTheme() self.textView.frame = UIScreen.main.bounds self.textView.autoresizingMask = [.flexibleWidth, .flexibleHeight] } // MARK: Convenience @IBAction internal func loadCurrentTheme() { textView.tintColor = .themeStyle(dark: .warmColor, light: .coolBlue) if UserDefaultsManager.darkThemeSwitchIsOn { textView.backgroundColor = .themeStyle(dark: .black, light: .white) textView.textColor = .themeStyle(dark: .white, light: .black) } } }
mit
shanksyang/SwiftRegex
SwiftRegex/SwiftRegex.swift
1
4323
// // SwiftRegex.swift // SwiftRegex // // Created by Gregory Todd Williams on 6/7/14. // Copyright (c) 2014 Gregory Todd Williams. All rights reserved. // import Foundation //extension String { // func rangeFromNSRange(nsRange : NSRange) -> Range<String.Index>? { // let from16 = utf16.startIndex.advancedBy(nsRange.location, limit: utf16.endIndex) // let to16 = from16.advancedBy(nsRange.length, limit: utf16.endIndex) // if let from = String.Index(from16, within: self), // let to = String.Index(to16, within: self) { // return from ..< to // } // return nil // } //} // // //extension String { // func NSRangeFromRange(range : Range<String.Index>) -> NSRange { // let utf16view = self.utf16 // let from = String.UTF16View.Index(range.startIndex, within: utf16view) // let to = String.UTF16View.Index(range.endIndex, within: utf16view) // return NSMakeRange(utf16view.startIndex.distanceTo(from), from.distanceTo(to)) // } //} infix operator =~ {} func =~ (value : String, pattern : String) -> RegexMatchResult { let nsstr = value as NSString // we use this to access the NSString methods like .length and .substringWithRange(NSRange) let options : NSRegularExpressionOptions = [] do { let re = try NSRegularExpression(pattern: pattern, options: options) let all = NSRange(location: 0, length: nsstr.length) var matches : Array<String> = [] var captureResult : [RegexCaptureResult] = [RegexCaptureResult]() re.enumerateMatchesInString(value, options: [], range: all) { (result, flags, ptr) -> Void in guard let result = result else { return } var captureItems : [String] = [] for i in 0..<result.numberOfRanges { let range = result.rangeAtIndex(i) print(range) let string = nsstr.substringWithRange(range) if(i > 0) { captureItems.append(string) continue } matches.append(string) } captureResult.append(RegexCaptureResult(items: captureItems)) print(matches) } return RegexMatchResult(items: matches, captureItems: captureResult) } catch { return RegexMatchResult(items: [], captureItems: []) } } struct RegexMatchCaptureGenerator : GeneratorType { var items: Array<String> mutating func next() -> String? { if items.isEmpty { return nil } let ret = items[0] items = Array(items[1..<items.count]) return ret } } struct RegexMatchResult : SequenceType, BooleanType { var items: Array<String> var captureItems: [RegexCaptureResult] func generate() -> RegexMatchCaptureGenerator { print(items) return RegexMatchCaptureGenerator(items: items) } var boolValue: Bool { return items.count > 0 } subscript (i: Int) -> String { return items[i] } } struct RegexCaptureResult { var items: Array<String> } class SwiftRegex { //是否包含 class func containsMatch(pattern: String, inString string: String) -> Bool { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.firstMatchInString(string, options: matchOptions, range: range) != nil } //匹配 class func match(pattern: String, inString string: String) -> RegexMatchResult { return string =~ pattern } //替换 class func replaceMatches(pattern: String, inString string: String, withString replacementString: String) -> String? { let options : NSRegularExpressionOptions = [] let matchOptions : NSMatchingOptions = [] let regex = try! NSRegularExpression(pattern: pattern, options: options) let range = NSMakeRange(0, string.characters.count) return regex.stringByReplacingMatchesInString(string, options: matchOptions, range: range, withTemplate: replacementString) } }
bsd-3-clause
TheSafo/Sinkr
ios stuff/Sinkr/Model/SettingsManager.swift
1
544
// // SettingsManager.swift // Sinkr // // Created by Jake Saferstein on 7/10/16. // Copyright © 2016 Jake Saferstein. All rights reserved. // import Foundation class SettingsManager { static let sharedManager = SettingsManager() /** This prevents others from using initialiser */ private init() { } func getAvailableSpecialMovies() -> [MoveType] { let placeholder = Index(row: -1, col: -1) return [.Bounce(placeholder, placeholder), .Electricity([])] } }
gpl-3.0
mssun/passforios
passKit/Helpers/KeyStore.swift
2
377
// // KeyStore.swift // passKit // // Created by Danny Moesch on 20.07.19. // Copyright © 2019 Bob Sun. All rights reserved. // import Foundation public protocol KeyStore { func add(string: String?, for key: String) func contains(key: String) -> Bool func get(for key: String) -> String? func removeContent(for key: String) func removeAllContent() }
mit
maxbritto/cours-ios11-swift4
Niveau_avance/Objectif 2/Safety First/Safety First/Model/Vault.swift
1
1354
// // CredentialsManager.swift // Safety First // // Created by Maxime Britto on 05/09/2017. // Copyright © 2017 Maxime Britto. All rights reserved. // import Foundation import RealmSwift class Vault { private let _realm:Realm private let _credentialList:Results<Credentials> init(withRealm realm:Realm) { _realm = realm _credentialList = _realm.objects(Credentials.self) } func addCredentials(title:String, login:String, password:String, url:String) -> Credentials { let newCredential = Credentials() newCredential.title = title newCredential.login = login newCredential.password = password newCredential.url = url try? _realm.write { _realm.add(newCredential) } return newCredential } func getCredentialCount() -> Int { return _credentialList.count } func getCredential(atIndex index:Int) -> Credentials? { guard index >= 0 && index < getCredentialCount() else { return nil } return _credentialList[index] } func deleteCredential(atIndex index:Int) { if let credToDelete = getCredential(atIndex: index) { try? _realm.write { _realm.delete(credToDelete) } } } }
apache-2.0
AL333Z/Words-MVVM-Android-iOS
Words-iOS/Words/Util/UIKitExtensions.swift
2
2079
// // Util.swift // ReactiveTwitterSearch // // Created by Colin Eberhardt on 10/05/2015. // Copyright (c) 2015 Colin Eberhardt. All rights reserved. // import UIKit import ReactiveCocoa struct AssociationKey { static var hidden: UInt8 = 1 static var alpha: UInt8 = 2 static var text: UInt8 = 3 } // lazily creates a gettable associated property via the given factory func lazyAssociatedProperty<T: AnyObject>(host: AnyObject, key: UnsafePointer<Void>, factory: ()->T) -> T { return objc_getAssociatedObject(host, key) as? T ?? { let associatedProperty = factory() objc_setAssociatedObject(host, key, associatedProperty, UInt(OBJC_ASSOCIATION_RETAIN)) return associatedProperty }() } func lazyMutableProperty<T>(host: AnyObject, key: UnsafePointer<Void>, setter: T -> (), getter: () -> T) -> MutableProperty<T> { return lazyAssociatedProperty(host, key) { var property = MutableProperty<T>(getter()) property.producer .start(next: { newValue in setter(newValue) }) return property } } extension UIView { public var rac_alpha: MutableProperty<CGFloat> { return lazyMutableProperty(self, &AssociationKey.alpha, { self.alpha = $0 }, { self.alpha }) } public var rac_hidden: MutableProperty<Bool> { return lazyMutableProperty(self, &AssociationKey.hidden, { self.hidden = $0 }, { self.hidden }) } } extension UILabel { public var rac_text: MutableProperty<String> { return lazyMutableProperty(self, &AssociationKey.text, { self.text = $0 }, { self.text ?? "" }) } } extension UITextField { public var rac_text: MutableProperty<String> { return lazyAssociatedProperty(self, &AssociationKey.text) { self.addTarget(self, action: "changed", forControlEvents: UIControlEvents.EditingChanged) var property = MutableProperty<String>(self.text ?? "") property.producer .start(next: { newValue in self.text = newValue }) return property } } func changed() { rac_text.value = self.text } }
apache-2.0
laurentVeliscek/AudioKit
AudioKit/Common/Nodes/Effects/Filters/Moog Ladder/AKMoogLadderPresets.swift
2
974
// // AKMoogLadderPresets.swift // AudioKit // // Created by Nicholas Arner, revision history on Github. // Copyright © 2016 AudioKit. All rights reserved. // import Foundation /// Preset for the AKMoogLadder public extension AKMoogLadder { /// Blurry, foggy filter public func presetFogMoogLadder() { cutoffFrequency = 515.578 resonance = 0.206 } /// Dull noise filter public func presetDullNoiseMoogLadder() { cutoffFrequency = 3088.157 resonance = 0.075 } /// Print out current values in case you want to save it as a preset public func printCurrentValuesAsPreset() { print("public func presetSomeNewMoogLadderFilter() {") print(" cutoffFrequency = \(String(format: "%0.3f", cutoffFrequency))") print(" resonance = \(String(format: "%0.3f", resonance))") print(" ramp time = \(String(format: "%0.3f", rampTime))") print("}\n") } }
mit
aahmedae/blitz-news-ios
Blitz News/AppDelegate.swift
1
2740
// // AppDelegate.swift // Blitz News // // Created by Asad Ahmed on 5/13/17. // // import UIKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { // setup app theme setupCustomAppTheme() return true } func applicationWillResignActive(_ application: UIApplication) { // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state. // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game. } func applicationDidEnterBackground(_ application: UIApplication) { // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later. // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits. } func applicationWillEnterForeground(_ application: UIApplication) { // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background. } func applicationDidBecomeActive(_ application: UIApplication) { // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface. } func applicationWillTerminate(_ application: UIApplication) { // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:. } // Sets up the custom app theme fileprivate func setupCustomAppTheme() { // navigation bar let navigationBarAppearace = UINavigationBar.appearance() navigationBarAppearace.tintColor = UISettings.NAV_BAR_HEADER_FONT_COLOR navigationBarAppearace.barTintColor = UISettings.HEADER_BAR_COLOR navigationBarAppearace.titleTextAttributes = [NSForegroundColorAttributeName:UISettings.NAV_BAR_HEADER_FONT_COLOR, NSFontAttributeName: UISettings.NAV_BAR_HEADER_FONT] // status bar UIApplication.shared.statusBarStyle = UISettings.STATUS_BAR_STYLE } }
mit
whitepixelstudios/Material
Sources/iOS/Card.swift
1
7894
/* * Copyright (C) 2015 - 2017, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * * Redistributions of source code must retain the above copyright notice, this * list of conditions and the following disclaimer. * * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * * Neither the name of CosmicMind nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ import UIKit open class Card: PulseView { /// A container view for subviews. open let container = UIView() @IBInspectable open override var cornerRadiusPreset: CornerRadiusPreset { didSet { container.cornerRadiusPreset = cornerRadiusPreset } } @IBInspectable open var cornerRadius: CGFloat { get { return container.layer.cornerRadius } set(value) { container.layer.cornerRadius = value } } open override var shapePreset: ShapePreset { didSet { container.shapePreset = shapePreset } } @IBInspectable open override var backgroundColor: UIColor? { didSet { container.backgroundColor = backgroundColor } } /// A reference to the toolbar. @IBInspectable open var toolbar: Toolbar? { didSet { oldValue?.removeFromSuperview() if let v = toolbar { container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around toolbarEdgeInsets. open var toolbarEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { toolbarEdgeInsets = EdgeInsetsPresetToValue(preset: toolbarEdgeInsetsPreset) } } /// A reference to toolbarEdgeInsets. @IBInspectable open var toolbarEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the contentView. @IBInspectable open var contentView: UIView? { didSet { oldValue?.removeFromSuperview() if let v = contentView { v.clipsToBounds = true container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around contentViewEdgeInsets. open var contentViewEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { contentViewEdgeInsets = EdgeInsetsPresetToValue(preset: contentViewEdgeInsetsPreset) } } /// A reference to contentViewEdgeInsets. @IBInspectable open var contentViewEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /// A reference to the bottomBar. @IBInspectable open var bottomBar: Bar? { didSet { oldValue?.removeFromSuperview() if let v = bottomBar { container.addSubview(v) } layoutSubviews() } } /// A preset wrapper around bottomBarEdgeInsets. open var bottomBarEdgeInsetsPreset = EdgeInsetsPreset.none { didSet { bottomBarEdgeInsets = EdgeInsetsPresetToValue(preset: bottomBarEdgeInsetsPreset) } } /// A reference to bottomBarEdgeInsets. @IBInspectable open var bottomBarEdgeInsets = EdgeInsets.zero { didSet { layoutSubviews() } } /** An initializer that accepts a NSCoder. - Parameter coder aDecoder: A NSCoder. */ public required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } /** An initializer that accepts a CGRect. - Parameter frame: A CGRect. */ public override init(frame: CGRect) { super.init(frame: frame) } /// A convenience initializer. public convenience init() { self.init(frame: .zero) } /** A convenience initiazlier. - Parameter toolbar: An optional Toolbar. - Parameter contentView: An optional UIView. - Parameter bottomBar: An optional Bar. */ public convenience init?(toolbar: Toolbar?, contentView: UIView?, bottomBar: Bar?) { self.init(frame: .zero) prepareProperties(toolbar: toolbar, contentView: contentView, bottomBar: bottomBar) } open override func layoutSubviews() { super.layoutSubviews() container.frame.size.width = bounds.width reload() } /// Reloads the layout. open func reload() { var h: CGFloat = 0 if let v = toolbar { h = prepare(view: v, with: toolbarEdgeInsets, from: h) } if let v = contentView { h = prepare(view: v, with: contentViewEdgeInsets, from: h) } if let v = bottomBar { h = prepare(view: v, with: bottomBarEdgeInsets, from: h) } container.frame.size.height = h bounds.size.height = h } open override func prepare() { super.prepare() pulseAnimation = .none cornerRadiusPreset = .cornerRadius1 prepareContainer() } /** Prepare the view size from a given top position. - Parameter view: A UIView. - Parameter edge insets: An EdgeInsets. - Parameter from top: A CGFloat. - Returns: A CGFloat. */ @discardableResult open func prepare(view: UIView, with insets: EdgeInsets, from top: CGFloat) -> CGFloat { let y = insets.top + top view.frame.origin.y = y view.frame.origin.x = insets.left let w = container.bounds.width - insets.left - insets.right var h = view.bounds.height if 0 == h || nil != view as? UILabel { (view as? UILabel)?.sizeToFit() h = view.sizeThatFits(CGSize(width: w, height: .greatestFiniteMagnitude)).height } view.frame.size.width = w view.frame.size.height = h return y + h + insets.bottom } /** A preparation method that sets the base UI elements. - Parameter toolbar: An optional Toolbar. - Parameter contentView: An optional UIView. - Parameter bottomBar: An optional Bar. */ internal func prepareProperties(toolbar: Toolbar?, contentView: UIView?, bottomBar: Bar?) { self.toolbar = toolbar self.contentView = contentView self.bottomBar = bottomBar } } extension Card { /// Prepares the container. fileprivate func prepareContainer() { container.clipsToBounds = true addSubview(container) } }
bsd-3-clause
martrik/MonoAppleWatch
App/Mono WatchKit Extension/NotificationController.swift
2
1865
// // NotificationController.swift // Mono WatchKit Extension // // Created by Martí Serra Vivancos on 01/02/15. // Copyright (c) 2015 Tomorrow Dev. All rights reserved. // import WatchKit import Foundation class NotificationController: WKUserNotificationInterfaceController { override init() { // Initialize variables here. super.init() // Configure interface objects here. } override func willActivate() { // This method is called when watch view controller is about to be visible to user super.willActivate() } override func didDeactivate() { // This method is called when watch view controller is no longer visible super.didDeactivate() } /* override func didReceiveLocalNotification(localNotification: UILocalNotification, withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) { // This method is called when a local notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification inteface as quickly as possible. // // After populating your dynamic notification interface call the completion block. completionHandler(.Custom) } */ /* override func didReceiveRemoteNotification(remoteNotification: [NSObject : AnyObject], withCompletion completionHandler: ((WKUserNotificationInterfaceType) -> Void)) { // This method is called when a remote notification needs to be presented. // Implement it if you use a dynamic notification interface. // Populate your dynamic notification inteface as quickly as possible. // // After populating your dynamic notification interface call the completion block. completionHandler(.Custom) } */ }
mit
gregomni/swift
test/Parse/ConditionalCompilation/macabiTargetEnv.swift
9
1295
// RUN: %swift -swift-version 4 -typecheck %s -verify -target x86_64-apple-ios12.0-macabi -parse-stdlib // RUN: %swift-ide-test -swift-version 4 -test-input-complete -source-filename=%s -target x86_64-apple-ios12.0-macabi // REQUIRES: maccatalyst_support #if targetEnvironment(macabi) // expected-warning {{'macabi' has been renamed to 'macCatalyst'}} {{23-29=macCatalyst}} func underMacABI() { foo() // expected-error {{cannot find 'foo' in scope}} } #endif #if !targetEnvironment(macabi) // expected-warning {{'macabi' has been renamed to 'macCatalyst'}} {{24-30=macCatalyst}} // This block does not typecheck but the #if prevents it from // from being a compiler error. let i: SomeType = "SomeString" // no-error #endif #if targetEnvironment(macCatalyst) func underTargetEnvironmentMacCatalyst() { foo() // expected-error {{cannot find 'foo' in scope}} } #endif // Make sure we don't treat the macabi environment as a simulator. #if targetEnvironment(simulator) // This block does not typecheck but the #if prevents it from // from being a compiler error. let i: SomeType = "SomeString" // no-error #endif #if os(macCatalyst) // expected-warning@-1 {{unknown operating system for build configuration 'os'}} // expected-note@-2 *{{did you mean}} func underOSMacCatalyst() { } #endif
apache-2.0
dboyliao/NumSwift
NumSwift/Source/FFT.swift
1
11862
// // Dear maintainer: // // When I wrote this code, only I and God // know what it was. // Now, only God knows! // // So if you are done trying to 'optimize' // this routine (and failed), // please increment the following counter // as warning to the next guy: // // var TotalHoursWastedHere = 0 // // Reference: http://stackoverflow.com/questions/184618/what-is-the-best-comment-in-source-code-you-have-ever-encountered import Accelerate /** Complex-to-Complex Fast Fourier Transform. - Note: we use radix-2 fft. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: - `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func fft(_ realp:[Double], imagp: [Double]) -> (realp:[Double], imagp:[Double]) { let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputRealp = [Double](realp[0..<fftN]) var inputImagp = [Double](imagp[0..<fftN]) var fftCoefRealp = [Double](repeating: 0.0, count: fftN) var fftCoefImagp = [Double](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD) vDSP_DFT_ExecuteD(setup!, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp) // destroy setup. vDSP_DFT_DestroySetupD(setup) return (fftCoefRealp, fftCoefImagp) } /** Complex-to-Complex Fast Fourier Transform. - Note: that we use radix-2 fft. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func fft(_ realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputRealp = [Float](realp[0..<fftN]) var inputImagp = [Float](imagp[0..<fftN]) var fftCoefRealp = [Float](repeating: 0.0, count: fftN) var fftCoefImagp = [Float](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.FORWARD) vDSP_DFT_Execute(setup!, &inputRealp, &inputImagp, &fftCoefRealp, &fftCoefImagp) // destroy setup. vDSP_DFT_DestroySetup(setup) return (fftCoefRealp, fftCoefImagp) } /** Complex-to-Complex Inverse Fast Fourier Transform. - Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Double], imagp:[Double])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func ifft(_ realp:[Double], imagp:[Double]) -> (realp:[Double], imagp:[Double]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputCoefRealp = [Double](realp[0..<fftN]) var inputCoefImagp = [Double](imagp[0..<fftN]) var outputRealp = [Double](repeating: 0.0, count: fftN) var outputImagp = [Double](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetupD(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE) vDSP_DFT_ExecuteD(setup!, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp) // normalization of ifft var scale = Double(fftN) var normalizedOutputRealp = [Double](repeating: 0.0, count: fftN) var normalizedOutputImagp = [Double](repeating: 0.0, count: fftN) vDSP_vsdivD(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN)) vDSP_vsdivD(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN)) // destroy setup. vDSP_DFT_DestroySetupD(setup) return (normalizedOutputRealp, normalizedOutputImagp) } /** Complex-to-Complex Inverse Fast Fourier Transform. - Note: we use radix-2 Inverse Fast Fourier Transform. As a result, it may process only partial input data depending on the # of data is of power of 2 or not. - Parameters: - realp: real part of input data - imagp: imaginary part of input data - Returns: `(realp:[Float], imagp:[Float])`: Fourier coeficients. It's a tuple with named attributes, `realp` and `imagp`. */ public func ifft(_ realp:[Float], imagp:[Float]) -> (realp:[Float], imagp:[Float]){ let log2N = vDSP_Length(log2f(Float(realp.count))) let fftN = Int(1 << log2N) // buffers. var inputCoefRealp = [Float](realp[0..<fftN]) var inputCoefImagp = [Float](imagp[0..<fftN]) var outputRealp = [Float](repeating: 0.0, count: fftN) var outputImagp = [Float](repeating: 0.0, count: fftN) // setup DFT and execute. let setup = vDSP_DFT_zop_CreateSetup(nil, vDSP_Length(fftN), vDSP_DFT_Direction.INVERSE) defer { // destroy setup. vDSP_DFT_DestroySetup(setup) } vDSP_DFT_Execute(setup!, &inputCoefRealp, &inputCoefImagp, &outputRealp, &outputImagp) // normalization of ifft var scale = Float(fftN) var normalizedOutputRealp = [Float](repeating: 0.0, count: fftN) var normalizedOutputImagp = [Float](repeating: 0.0, count: fftN) vDSP_vsdiv(&outputRealp, 1, &scale, &normalizedOutputRealp, 1, vDSP_Length(fftN)) vDSP_vsdiv(&outputImagp, 1, &scale, &normalizedOutputImagp, 1, vDSP_Length(fftN)) return (normalizedOutputRealp, normalizedOutputImagp) } /** Convolution with Fast Fourier Transform Perform convolution by Fast Fourier Transform - Parameters: - x: input array for convolution. - y: input array for convolution. - mode: mode of the convolution. - "full": return full result (default). - "same": return result with the same length as the longest input arrays between x and y. - "valid": only return the result given for points where two arrays overlap completely. - Returns: the result of the convolution of x and y. */ public func fft_convolve(_ x:[Double], y:[Double], mode:String = "full") -> [Double] { var longArray:[Double] var shortArray:[Double] if x.count < y.count { longArray = [Double](y) shortArray = [Double](x) } else { longArray = [Double](x) shortArray = [Double](y) } let N = longArray.count let M = shortArray.count let convN = N+M-1 let convNPowTwo = leastPowerOfTwo(convN) longArray = pad(longArray, toLength:convNPowTwo, value:0.0) shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0) let zeros = [Double](repeating: 0.0, count: convNPowTwo) var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros) var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros) // setup input buffers for vDSP_zvmulD // long array: var coefLongArrayComplex = DSPDoubleSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp) // short array: var coefShortArrayComplex = DSPDoubleSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp) // setup output buffers for vDSP_zvmulD var coefConvRealp = [Double](repeating: 0.0, count: convNPowTwo) var coefConvImagp = [Double](repeating: 0.0, count: convNPowTwo) var coefConvComplex = DSPDoubleSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp) // Elementwise Complex Multiplication vDSP_zvmulD(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1, &coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1)) // ifft var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp) // Remove padded zeros convResult = [Double](convResult[0..<convN]) // modify the result according mode before return let finalResult:[Double] switch mode { case "same": let numOfResultToBeRemoved = convN - N let toBeRemovedHalf = numOfResultToBeRemoved / 2 if numOfResultToBeRemoved % 2 == 0 { finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)]) } else { finalResult = [Double](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)]) } case "valid": finalResult = [Double](convResult[(M-1)..<(convN-M+1)]) default: finalResult = convResult } return finalResult } /** Convolution with Fast Fourier Transform Perform convolution by Fast Fourier Transform - Parameters: - x: input array for convolution. - y: input array for convolution. - mode: mode of the convolution. - "full": return full result (default). - "same": return result with the same length as the longest input array between x and y. - "valid": only return the result given for points where two arrays overlap completely. - Returns: the result of the convolution of x and y. */ public func fft_convolve(_ x:[Float], y:[Float], mode:String = "full") -> [Float] { var longArray:[Float] var shortArray:[Float] if x.count < y.count { longArray = [Float](y) shortArray = [Float](x) } else { longArray = [Float](x) shortArray = [Float](y) } let N = longArray.count let M = shortArray.count let convN = N+M-1 let convNPowTwo = leastPowerOfTwo(convN) longArray = pad(longArray, toLength:convNPowTwo, value:0.0) shortArray = pad(shortArray, toLength:convNPowTwo, value:0.0) let zeros = [Float](repeating: 0.0, count: convNPowTwo) var (coefLongArrayRealp, coefLongArrayImagp) = fft(longArray, imagp:zeros) var (coefShortArrayRealp, coefShortArrayImagp) = fft(shortArray, imagp:zeros) // setup input buffers for vDSP_zvmulD // long array: var coefLongArrayComplex = DSPSplitComplex(realp:&coefLongArrayRealp, imagp:&coefLongArrayImagp) // short array: var coefShortArrayComplex = DSPSplitComplex(realp:&coefShortArrayRealp, imagp:&coefShortArrayImagp) // setup output buffers for vDSP_zvmulD var coefConvRealp = [Float](repeating: 0.0, count: convNPowTwo) var coefConvImagp = [Float](repeating: 0.0, count: convNPowTwo) var coefConvComplex = DSPSplitComplex(realp:&coefConvRealp, imagp:&coefConvImagp) // Elementwise Complex Multiplication vDSP_zvmul(&coefLongArrayComplex, 1, &coefShortArrayComplex, 1, &coefConvComplex, 1, vDSP_Length(convNPowTwo), Int32(1)) // ifft var (convResult, _) = ifft(coefConvRealp, imagp:coefConvImagp) // Remove padded zeros convResult = [Float](convResult[0..<convN]) // modify the result according mode before return let finalResult:[Float] switch mode { case "same": let numOfResultToBeRemoved = convN - N let toBeRemovedHalf = numOfResultToBeRemoved / 2 if numOfResultToBeRemoved % 2 == 0 { finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf)]) } else { finalResult = [Float](convResult[toBeRemovedHalf..<(convN-toBeRemovedHalf-1)]) } case "valid": finalResult = [Float](convResult[(M-1)..<(convN-M+1)]) default: finalResult = convResult } return finalResult }
mit
eTilbudsavis/native-ios-eta-sdk
Sources/CoreAPI/Models/CoreAPI_Dealer.swift
1
3843
// // ┌────┬─┐ ┌─────┐ // │ ──┤ └─┬───┬───┤ ┌──┼─┬─┬───┐ // ├── │ ╷ │ · │ · │ ╵ │ ╵ │ ╷ │ // └────┴─┴─┴───┤ ┌─┴─────┴───┴─┴─┘ // └─┘ // // Copyright (c) 2018 ShopGun. All rights reserved. import UIKit extension CoreAPI { public struct Dealer: Decodable, Equatable { public typealias Identifier = GenericIdentifier<Dealer> public var id: Identifier public var name: String public var website: URL? public var description: String? public var descriptionMarkdown: String? public var logoOnWhite: URL public var logoOnBrandColor: URL public var brandColor: UIColor? public var country: Country public var favoriteCount: Int enum CodingKeys: String, CodingKey { case id case name case website case description case descriptionMarkdown = "description_markdown" case logoOnWhite = "logo" case colorStr = "color" case pageFlip = "pageflip" case country case favoriteCount = "favorite_count" enum PageFlipKeys: String, CodingKey { case logo case colorStr = "color" } } public init(from decoder: Decoder) throws { let values = try decoder.container(keyedBy: CodingKeys.self) self.id = try values.decode(Identifier.self, forKey: .id) self.name = try values.decode(String.self, forKey: .name) self.website = try? values.decode(URL.self, forKey: .website) self.description = try? values.decode(String.self, forKey: .description) self.descriptionMarkdown = try? values.decode(String.self, forKey: .descriptionMarkdown) self.logoOnWhite = try values.decode(URL.self, forKey: .logoOnWhite) if let colorStr = try? values.decode(String.self, forKey: .colorStr) { self.brandColor = UIColor(hex: colorStr) } let pageflipValues = try values.nestedContainer(keyedBy: CodingKeys.PageFlipKeys.self, forKey: .pageFlip) self.logoOnBrandColor = try pageflipValues.decode(URL.self, forKey: .logo) self.country = try values.decode(Country.self, forKey: .country) self.favoriteCount = try values.decode(Int.self, forKey: .favoriteCount) } } // MARK: - public struct Country: Decodable, Equatable { public typealias Identifier = GenericIdentifier<Country> public var id: Identifier public init(id: Identifier) { self.id = id } } } //{ // "id": "25f5mL", // "ern": "ern:dealer:25f5mL", // "name": "3", // "website": "http://3.dk", // "description": "3 tilbyder danskerne mobiltelefoni og mobilt bredbånd. Kombinationen af 3’s 3G-netværk og lynhurtige 4G /LTE-netværk, sikrer danskerne adgang til fremtidens netværk - i dag.", // "description_markdown": null, // "logo": "https://d3ikkoqs9ddhdl.cloudfront.net/img/logo/default/25f5mL_2gvnjz51j.png", // "color": "000000", // "pageflip": { // "logo": "https://d3ikkoqs9ddhdl.cloudfront.net/img/logo/pageflip/25f5mL_4ronjz51j.png", // "color": "000000" // }, // "category_ids": [], // "country": { // "id": "DK", // "unsubscribe_print_url": null // }, // "favorite_count": 0, // "facebook_page_id": "168499089859599", // "youtube_user_id": "3Denmark", // "twitter_handle": "3BusinessDK" //}
mit
loudnate/LoopKit
LoopKit/Persistence/UploadState.swift
1
193
// // UploadState.swift // LoopKit // // Copyright © 2018 LoopKit Authors. All rights reserved. // enum UploadState: Int { case notUploaded = 0 case uploading case uploaded }
mit
mikemee/SQLite.swift2
SQLiteTests/ExpressionTests.swift
1
79
import XCTest @testable import SQLite class ExpressionTests : XCTestCase { }
mit
marketplacer/Dodo
DodoTests/Helpers/DodoTouchTargetTests.swift
6
791
import UIKit import XCTest class DodoTouchTargetTests: XCTestCase { func testIncreaseTheBounds() { let bounds = CGRect( origin: CGPoint(), size: CGSize(width: 30, height: 40) ) let result = DodoTouchTarget.optimize(bounds) XCTAssertEqual(result.width, 44) XCTAssertEqual(result.height, 44) XCTAssertEqual(result.origin.x, -7) XCTAssertEqual(result.origin.y, -2) } func testKeepTheBoundsBEcauseTheyAreBigEnought() { let bounds = CGRect( origin: CGPoint(), size: CGSize(width: 50, height: 60) ) let result = DodoTouchTarget.optimize(bounds) XCTAssertEqual(result.width, 50) XCTAssertEqual(result.height, 60) XCTAssertEqual(result.origin.x, 0) XCTAssertEqual(result.origin.y, 0) } }
mit
MessageKit/MessageKit
Sources/Views/Cells/MediaMessageCell.swift
1
3407
// MIT License // // Copyright (c) 2017-2019 MessageKit // // 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 UIKit /// A subclass of `MessageContentCell` used to display video and audio messages. open class MediaMessageCell: MessageContentCell { /// The play button view to display on video messages. open lazy var playButtonView: PlayButtonView = { let playButtonView = PlayButtonView() return playButtonView }() /// The image view display the media content. open var imageView: UIImageView = { let imageView = UIImageView() imageView.contentMode = .scaleAspectFill return imageView }() // MARK: - Methods /// Responsible for setting up the constraints of the cell's subviews. open func setupConstraints() { imageView.fillSuperview() playButtonView.centerInSuperview() playButtonView.constraint(equalTo: CGSize(width: 35, height: 35)) } open override func setupSubviews() { super.setupSubviews() messageContainerView.addSubview(imageView) messageContainerView.addSubview(playButtonView) setupConstraints() } open override func prepareForReuse() { super.prepareForReuse() imageView.image = nil } open override func configure( with message: MessageType, at indexPath: IndexPath, and messagesCollectionView: MessagesCollectionView) { super.configure(with: message, at: indexPath, and: messagesCollectionView) guard let displayDelegate = messagesCollectionView.messagesDisplayDelegate else { fatalError(MessageKitError.nilMessagesDisplayDelegate) } switch message.kind { case .photo(let mediaItem): imageView.image = mediaItem.image ?? mediaItem.placeholderImage playButtonView.isHidden = true case .video(let mediaItem): imageView.image = mediaItem.image ?? mediaItem.placeholderImage playButtonView.isHidden = false default: break } displayDelegate.configureMediaMessageImageView(imageView, for: message, at: indexPath, in: messagesCollectionView) } /// Handle tap gesture on contentView and its subviews. open override func handleTapGesture(_ gesture: UIGestureRecognizer) { let touchLocation = gesture.location(in: imageView) guard imageView.frame.contains(touchLocation) else { super.handleTapGesture(gesture) return } delegate?.didTapImage(in: self) } }
mit
tspecht/SwiftLint
Source/SwiftLintFrameworkTests/ASTRuleTests.swift
5
6074
// // ASTRuleTests.swift // SwiftLint // // Created by JP Simard on 5/28/15. // Copyright (c) 2015 Realm. All rights reserved. // import SwiftLintFramework import XCTest class ASTRuleTests: XCTestCase { func testTypeNames() { for kind in ["class", "struct", "enum"] { XCTAssertEqual(violations("\(kind) Abc {}\n"), []) XCTAssertEqual(violations("\(kind) Ab_ {}\n"), [StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: 1), severity: .High, reason: "Type name should only contain alphanumeric characters: 'Ab_'")]) XCTAssertEqual(violations("\(kind) abc {}\n"), [StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: 1), severity: .High, reason: "Type name should start with an uppercase character: 'abc'")]) XCTAssertEqual(violations("\(kind) Ab {}\n"), [StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: 1), severity: .Medium, reason: "Type name should be between 3 and 40 characters in length: 'Ab'")]) let longName = join("", Array(count: 40, repeatedValue: "A")) XCTAssertEqual(violations("\(kind) \(longName) {}\n"), []) let longerName = longName + "A" XCTAssertEqual(violations("\(kind) \(longerName) {}\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: 1), severity: .Medium, reason: "Type name should be between 3 and 40 characters in length: " + "'\(longerName)'") ]) } } func testNestedTypeNames() { XCTAssertEqual(violations("class Abc {\n class Def {}\n}\n"), []) XCTAssertEqual(violations("class Abc {\n class def\n}\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 2, character: 5), severity: .High, reason: "Type name should start with an uppercase character: 'def'") ] ) } func testVariableNames() { for kind in ["class", "struct"] { for varType in ["var", "let"] { let characterOffset = 8 + count(kind) XCTAssertEqual(violations("\(kind) Abc { \(varType) def: Void }\n"), []) XCTAssertEqual(violations("\(kind) Abc { \(varType) de_: Void }\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: characterOffset), severity: .High, reason: "Variable name should only contain alphanumeric characters: 'de_'") ]) XCTAssertEqual(violations("\(kind) Abc { \(varType) Def: Void }\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: characterOffset), severity: .High, reason: "Variable name should start with a lowercase character: 'Def'") ]) XCTAssertEqual(violations("\(kind) Abc { \(varType) de: Void }\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: characterOffset), severity: .Medium, reason: "Variable name should be between 3 and 40 characters in length: " + "'de'") ]) let longName = join("", Array(count: 40, repeatedValue: "d")) XCTAssertEqual(violations("\(kind) Abc { \(varType) \(longName): Void }\n"), []) let longerName = longName + "d" XCTAssertEqual(violations("\(kind) Abc { \(varType) \(longerName): Void }\n"), [ StyleViolation(type: .NameFormat, location: Location(file: nil, line: 1, character: characterOffset), severity: .Medium, reason: "Variable name should be between 3 and 40 characters in length: " + "'\(longerName)'") ]) } } } func testFunctionBodyLengths() { let longFunctionBody = "func abc() {" + join("", Array(count: 40, repeatedValue: "\n")) + "}\n" XCTAssertEqual(violations(longFunctionBody), []) let longerFunctionBody = "func abc() {" + join("", Array(count: 41, repeatedValue: "\n")) + "}\n" XCTAssertEqual(violations(longerFunctionBody), [StyleViolation(type: .Length, location: Location(file: nil, line: 1, character: 1), severity: .VeryLow, reason: "Function body should be span 40 lines or less: currently spans 41 lines")]) } func testTypeBodyLengths() { for kind in ["class", "struct", "enum"] { let longTypeBody = "\(kind) Abc {" + join("", Array(count: 200, repeatedValue: "\n")) + "}\n" XCTAssertEqual(violations(longTypeBody), []) let longerTypeBody = "\(kind) Abc {" + join("", Array(count: 201, repeatedValue: "\n")) + "}\n" XCTAssertEqual(violations(longerTypeBody), [StyleViolation(type: .Length, location: Location(file: nil, line: 1, character: 1), severity: .VeryLow, reason: "Type body should be span 200 lines or less: currently spans 201 lines")]) } } func testNesting() { verifyRule(NestingRule().example, type: .Nesting, commentDoesntViolate: false) } func testControlStatements() { verifyRule(ControlStatementRule().example, type: .ControlStatement) } }
mit
ellited/Lieferando-Services
Lieferando Services/PlaceParseModel.swift
1
710
// // Place.swift // Lieferando Services // // Created by Mikhail Rudenko on 10/06/2017. // Copyright © 2017 App-Smart. All rights reserved. // import Foundation import SQLite struct PlaceParseModel { let id = Expression<Int>("id") let name = Expression<String?>("name") let imageUrl = Expression<String?>("imageUrl") let postalCode = Expression<String?>("postalCode") let city = Expression<String?>("city") let street = Expression<String?>("street") let url = Expression<String?>("url") let rating = Expression<String?>("rating") let person = Expression<String?>("person") let fax = Expression<String?>("fax") let email = Expression<String?>("email") }
apache-2.0
nguyenantinhbk77/practice-swift
File Management/Deleting File and Folders/Deleting File and Folders/ViewController.swift
3
177
// // ViewController.swift // Deleting File and Folders // // Created by Domenico on 27/05/15. // License MIT // import UIKit class ViewController: UIViewController { }
mit
praca-japao/156
PMC156Inteligente/CategoriesTableViewController.swift
1
3262
// // CategoriesTableViewController.swift // PMC156Inteligente // // Created by Giovanni Pietrangelo on 11/29/15. // Copyright © 2015 Sigma Apps. All rights reserved. // import UIKit class CategoriesTableViewController: UITableViewController { var categorySelected: String! override func viewDidLoad() { super.viewDidLoad() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // MARK: - Table view delegate override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { let cell = tableView.cellForRowAtIndexPath(indexPath) categorySelected = cell?.textLabel?.text performSegueWithIdentifier("newRequest", sender: self) } // MARK: - Table view data source override func numberOfSectionsInTableView(tableView: UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 10 } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier("Category", forIndexPath: indexPath) cell.textLabel?.text = "Categoria" return cell } // Override to support conditional editing of the table view. override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the specified item to be editable. return false } /* // Override to support editing the table view. override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) { if editingStyle == .Delete { // Delete the row from the data source tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade) } else if editingStyle == .Insert { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) { } */ /* // Override to support conditional rearranging of the table view. override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool { // Return false if you do not want the item to be re-orderable. return true } */ // MARK: - Navigation // In a storyboard-based application, you will often want to do a little preparation before navigation override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if segue.identifier == "newRequest" { // Date Controller let destinationViewController = segue.destinationViewController as! NewRequestViewController destinationViewController.category = categorySelected } } }
gpl-2.0
natecook1000/swift-compiler-crashes
fixed/26155-swift-constraints-constraintgraph-change-undo.swift
7
207
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing "" struct a{enum a{var b{{class case,
mit
LoopKit/LoopKit
LoopKitUI/View Controllers/ChartsManager.swift
1
7243
// // Chart.swift // Naterade // // Created by Nathan Racklyeft on 2/19/16. // Copyright © 2016 Nathan Racklyeft. All rights reserved. // import Foundation import HealthKit import LoopKit import SwiftCharts open class ChartsManager { private lazy var timeFormatter: DateFormatter = { let formatter = DateFormatter() let dateFormat = DateFormatter.dateFormat(fromTemplate: "j", options: 0, locale: Locale.current)! let isAmPmTimeFormat = dateFormat.firstIndex(of: "a") != nil formatter.dateFormat = isAmPmTimeFormat ? "h a" : "H:mm" return formatter }() public init( colors: ChartColorPalette, settings: ChartSettings, axisLabelFont: UIFont = .systemFont(ofSize: 14), // caption1, but hard-coded until axis can scale with type preference charts: [ChartProviding], traitCollection: UITraitCollection ) { self.colors = colors self.chartSettings = settings self.charts = charts self.traitCollection = traitCollection self.chartsCache = Array(repeating: nil, count: charts.count) axisLabelSettings = ChartLabelSettings(font: axisLabelFont, fontColor: colors.axisLabel) guideLinesLayerSettings = ChartGuideLinesLayerSettings(linesColor: colors.grid) } // MARK: - Configuration private let colors: ChartColorPalette private let chartSettings: ChartSettings private let labelsWidthY: CGFloat = 30 public let charts: [ChartProviding] /// The amount of horizontal space reserved for fixed margins public var fixedHorizontalMargin: CGFloat { return chartSettings.leading + chartSettings.trailing + labelsWidthY + chartSettings.labelsToAxisSpacingY } private let axisLabelSettings: ChartLabelSettings private let guideLinesLayerSettings: ChartGuideLinesLayerSettings public var gestureRecognizer: UIGestureRecognizer? // MARK: - UITraitEnvironment public var traitCollection: UITraitCollection public func didReceiveMemoryWarning() { for chart in charts { chart.didReceiveMemoryWarning() } xAxisValues = nil } // MARK: - Data /// The earliest date on the X-axis public var startDate = Date() { didSet { if startDate != oldValue { xAxisValues = nil // Set a new minimum end date endDate = startDate.addingTimeInterval(.hours(3)) } } } /// The latest date on the X-axis private var endDate = Date() { didSet { if endDate != oldValue { xAxisValues = nil } } } /// The latest allowed date on the X-axis public var maxEndDate = Date.distantFuture { didSet { endDate = min(endDate, maxEndDate) } } /// Updates the endDate using a new candidate date /// /// Dates are rounded up to the next hour. /// /// - Parameter date: The new candidate date public func updateEndDate(_ date: Date) { if date > endDate { let components = DateComponents(minute: 0) endDate = min( maxEndDate, Calendar.current.nextDate( after: date, matching: components, matchingPolicy: .strict, direction: .forward ) ?? date ) } } // MARK: - State private var xAxisValues: [ChartAxisValue]? { didSet { if let xAxisValues = xAxisValues, xAxisValues.count > 1 { xAxisModel = ChartAxisModel(axisValues: xAxisValues, lineColor: colors.axisLine, labelSpaceReservationMode: .fixed(20)) } else { xAxisModel = nil } chartsCache.replaceAllElements(with: nil) } } private var xAxisModel: ChartAxisModel? private var chartsCache: [Chart?] // MARK: - Generators public func chart(atIndex index: Int, frame: CGRect) -> Chart? { if let chart = chartsCache[index], chart.frame != frame { chartsCache[index] = nil } if chartsCache[index] == nil, let xAxisModel = xAxisModel, let xAxisValues = xAxisValues { chartsCache[index] = charts[index].generate(withFrame: frame, xAxisModel: xAxisModel, xAxisValues: xAxisValues, axisLabelSettings: axisLabelSettings, guideLinesLayerSettings: guideLinesLayerSettings, colors: colors, chartSettings: chartSettings, labelsWidthY: labelsWidthY, gestureRecognizer: gestureRecognizer, traitCollection: traitCollection) } return chartsCache[index] } public func invalidateChart(atIndex index: Int) { chartsCache[index] = nil } // MARK: - Shared Axis private func generateXAxisValues() { if let endDate = charts.compactMap({ $0.endDate }).max() { updateEndDate(endDate) } let points = [ ChartPoint( x: ChartAxisValueDate(date: startDate, formatter: timeFormatter), y: ChartAxisValue(scalar: 0) ), ChartPoint( x: ChartAxisValueDate(date: endDate, formatter: timeFormatter), y: ChartAxisValue(scalar: 0) ) ] let segments = ceil(endDate.timeIntervalSince(startDate).hours) let xAxisValues = ChartAxisValuesStaticGenerator.generateXAxisValuesWithChartPoints(points, minSegmentCount: segments - 1, maxSegmentCount: segments + 1, multiple: TimeInterval(hours: 1), axisValueGenerator: { ChartAxisValueDate( date: ChartAxisValueDate.dateFromScalar($0), formatter: timeFormatter, labelSettings: self.axisLabelSettings ) }, addPaddingSegmentIfEdge: false ) xAxisValues.first?.hidden = true xAxisValues.last?.hidden = true self.xAxisValues = xAxisValues } /// Runs any necessary steps before rendering charts public func prerender() { if xAxisValues == nil { generateXAxisValues() } } } fileprivate extension Array { mutating func replaceAllElements(with element: Element) { self = Array(repeating: element, count: count) } } public protocol ChartProviding { /// Instructs the chart to clear its non-critical resources like caches func didReceiveMemoryWarning() /// The last date represented in the chart data var endDate: Date? { get } /// Creates a chart from the current data /// /// - Returns: A new chart object func generate(withFrame frame: CGRect, xAxisModel: ChartAxisModel, xAxisValues: [ChartAxisValue], axisLabelSettings: ChartLabelSettings, guideLinesLayerSettings: ChartGuideLinesLayerSettings, colors: ChartColorPalette, chartSettings: ChartSettings, labelsWidthY: CGFloat, gestureRecognizer: UIGestureRecognizer?, traitCollection: UITraitCollection ) -> Chart }
mit
pos0637/ios-test-listview
TestListView/TestListView/SubView1Controller.swift
1
533
// // SubView1Controller.swift // TestListView // // Created by Alex on 2016/10/29. // Copyright © 2016年 Alex. All rights reserved. // import UIKit import XLPagerTabStrip class SubView1Controller: UIViewController, IndicatorInfoProvider { var mItemInfo = IndicatorInfo(title: "unknown") public func setItemInfo(_ info: IndicatorInfo!) { mItemInfo = info } func indicatorInfo(for pagerTabStripController: PagerTabStripViewController) -> IndicatorInfo { return mItemInfo } }
mit
bravelocation/yeltzland-ios
yeltzland/Views/LoadingIndicator.swift
1
1039
// // LoadingIndicator.swift // Yeltzland // // Created by John Pollard on 22/08/2020. // Copyright © 2020 John Pollard. All rights reserved. // import Foundation import UIKit #if canImport(SwiftUI) import SwiftUI #endif // Adapted from blog post at https://mobiraft.com/ios/swiftui/animations-in-swiftui/ @available(iOS 13.0, *) struct LoadingIndicator: View { var body: some View { HStack(spacing: 4.0) { DotView() DotView(delay: 0.2) DotView(delay: 0.4) } } } @available(iOS 13.0, *) struct DotView: View { @State var delay: Double = 0 @State var scale: CGFloat = 0.5 var body: some View { Circle() .frame(width: 16, height: 16) .scaleEffect(scale) .foregroundColor(Color("blue-tint")) .animation(Animation.easeInOut(duration: 0.6).repeatForever().delay(delay)) .onAppear { withAnimation { self.scale = 1 } } } }
mit
asm-products/voicesrepo
Voices/Voices/RootViewController.swift
1
2519
// // ViewController.swift // Voices // // Created by Mazyad Alabduljaleel on 11/1/14. // Copyright (c) 2014 Assembly. All rights reserved. // import UIKit /** The root view controller contains the whole app, and manages the * content scroll view which contains the content view controllers */ class RootViewController: UIViewController { private let contentViewControllers: [UIViewController] @IBOutlet var contentScrollView: UIScrollView? required init(coder aDecoder: NSCoder) { let mainStoryboard = UIStoryboard(name: "Main", bundle: nil) contentViewControllers = [ "ContactsViewController", "RecordViewController", "InboxViewController" ].map { mainStoryboard.instantiateViewControllerWithIdentifier($0) as UIViewController } super.init(coder: aDecoder) } override func viewDidLoad() { super.viewDidLoad() // Keep calm, and assert all your assumptions assert(contentScrollView != nil, "Content scroll view must be connected in IB") let scrollView = contentScrollView! scrollView.contentSize.width = CGFloat(contentViewControllers.count) * self.view.bounds.width scrollView.contentOffset.x = self.view.bounds.width var xOffset = CGFloat(0) for viewController in contentViewControllers { viewController.view.frame.origin.x = xOffset viewController.view.frame.size = scrollView.bounds.size scrollView.addSubview(viewController.view) xOffset += self.view.bounds.width } } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func preferredStatusBarStyle() -> UIStatusBarStyle { return .LightContent } } /** Subclass the Root view to draw the background gradient */ class RootView: UIView { override class func layerClass() -> AnyClass { return CAGradientLayer.self } required init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) let gradientLayer = layer as CAGradientLayer gradientLayer.colors = [ UIColor.orangeColor().CGColor, UIColor.redColor().CGColor ] gradientLayer.startPoint = CGPoint(x: 0, y: 0) gradientLayer.endPoint = CGPoint(x: 1, y: 1) contentMode = .Redraw } }
agpl-3.0
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01800-swift-functiontype-get.swift
12
223
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing protocol c { func e { } typealias e let : b func b: e
mit
Jamol/Nutil
Xcode/NutilSampleOSX/main.swift
1
2812
// // main.swift // NutilSampleOSX // // Created by Jamol Bao on 11/3/16. // // import Foundation import Nutil #if false var tcp = TcpSocket() tcp.onConnect { print("Tcp.onConnect, err=\($0)\n") } //let ret = tcp.connect("127.0.0.1", 52328) let ret = tcp.connect("www.google.com", 80) #endif #if false var a = Acceptor() a.onAccept { (fd, ip, port) in print("onAccept, fd=\(fd), ip=\(ip), port=\(port)") } _ = a.listen("127.0.0.1", 52328) #endif #if false var udp = UdpSocket() udp.onRead { var d = [UInt8](repeating: 0, count: 4096) let len = d.count let ret = d.withUnsafeMutableBufferPointer() { return udp.read($0.baseAddress!, len) } print("Udp.onRead, ret=\(ret)") } _ = udp.bind("127.0.0.1", 52328) #endif #if false var ssl = SslSocket() ssl.onConnect { print("Ssl.onConnect, err=\($0)\n") } let ret = ssl.connect("www.google.com", 443) #endif #if false let req = NutilFactory.createRequest(version: "HTTP/1.1")! req .onData { (data: UnsafeMutableRawPointer, len: Int) in print("data received, len=\(len)") } .onHeaderComplete { print("header completed") } .onRequestComplete { print("request completed") } .onError { err in print("request error, err=\(err)") } _ = req.sendRequest("GET", "https://www.google.com") #endif #if false let server = HttpServer() _ = server.start(addr: "0.0.0.0", port: 8443) #endif #if false let ws = NutilFactory.createWebSocket() ws.onData { (data, len, isText, fin) in print("WebSocket.onData, len=\(len), fin=\(fin)") ws.close() } .onError { err in print("WebSocket.onError, err=\(err)") } let ret = ws.connect("wss://127.0.0.1:8443") { err in print("WebSocket.onConnect, err=\(err)") let buf = Array<UInt8>(repeating: 64, count: 16*1024) let ret = ws.sendData(buf, buf.count, false, true) } #endif #if true var totalBytesReceived = 0 let req = NutilFactory.createRequest(version: "HTTP/2.0")! req .onData { (data: UnsafeMutableRawPointer, len: Int) in totalBytesReceived += len print("data received, len=\(len), total=\(totalBytesReceived)") } .onHeaderComplete { print("header completed") } .onRequestComplete { print("request completed") } .onError { err in print("request error, err=\(err)") } req.addHeader("user-agent", "kuma 1.0") //_ = req.sendRequest("GET", "https://127.0.0.1:8443/testdata") //_ = req.sendRequest("GET", "https://www.google.com") _ = req.sendRequest("GET", "https://http2.golang.org/reqinfo") //_ = req.sendRequest("GET", "https://www.cloudflare.com") #endif RunLoop.main.run()
mit
airspeedswift/swift-compiler-crashes
crashes-fuzzing/01139-swift-genericparamlist-addnestedarchetypes.swift
1
227
// Distributed under the terms of the MIT license // Test case submitted to project by https://github.com/practicalswift (practicalswift) // Test case found by fuzzing struct j func f<d> ( ) -> [j<d> { protocol c : b { func b
mit
mercadopago/px-ios
MercadoPagoSDK/MercadoPagoSDK/Core/Extensions/String+Additions.swift
1
2577
import Foundation extension String { static let NON_BREAKING_LINE_SPACE = "\u{00a0}" static let SPACE = " " static func isNullOrEmpty(_ value: String?) -> Bool { return value == nil || value!.isEmpty } func existsLocalized() -> Bool { let localizedString = self.localized return localizedString != self } static func isDigitsOnly(_ number: String) -> Bool { if Regex("^[0-9]*$").test(number) { return true } else { return false } } func startsWith(_ prefix: String) -> Bool { if prefix == self { return true } let startIndex = self.range(of: prefix) if startIndex == nil || self.startIndex != startIndex?.lowerBound { return false } return true } func lastCharacters(number: Int) -> String { let trimmedString: String = (self as NSString).substring(from: max(self.count - number, 0)) return trimmedString } func indexAt(_ theInt: Int) ->String.Index { return self.index(self.startIndex, offsetBy: theInt) } func trimSpaces() -> String { var stringTrimmed = self.replacingOccurrences(of: " ", with: "") stringTrimmed = stringTrimmed.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) return stringTrimmed } mutating func paramsAppend(key: String, value: String?) { if !key.isEmpty && !String.isNullOrEmpty(value) { if self.isEmpty { self = key + "=" + value! } else { self += "&" + key + "=" + value! } } } func toAttributedString(attributes: [NSAttributedString.Key: Any]? = nil) -> NSMutableAttributedString { return NSMutableAttributedString(string: self, attributes: attributes) } func getAttributedStringNewLine() -> NSMutableAttributedString { return "\n".toAttributedString() } static func getDate(_ string: String?) -> Date? { guard let dateString = string else { return nil } let dateFormatter = DateFormatter() dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ" return dateFormatter.date(from: dateString) } var isNumber: Bool { return rangeOfCharacter(from: CharacterSet.decimalDigits.inverted) == nil } func insert(_ string: String, ind: Int) -> String { return String(self.prefix(ind)) + string + String(self.suffix(self.count - ind)) } var isNotEmpty: Bool { return !isEmpty } }
mit
Zerounodue/splinxsChat
splinxsChat/startViewController.swift
1
4566
// // startViewController.swift // splinxsChat // // Created by Elia Kocher on 17.05.16. // Copyright © 2016 BFH. All rights reserved. // import UIKit class startViewController: UIViewController { var isConnected = false let localIP = "http://192.168.178.36:3000" let splinxsIP = "http://147.87.116.139:3000" @IBOutlet weak var nicknameTextFiel: UITextField! @IBOutlet weak var ipSegmentedControl: UISegmentedControl! @IBOutlet weak var statusLable: UILabel! override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func viewDidAppear(animated: Bool) { self.statusLable.text = "Offline" socketIOcontroller.sharedInstance.isConnectionEstablished{ (isConnected) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.isConnected = isConnected self.statusLable.text = isConnected ? "Online" : "Offline" }) } } @IBAction func infoAction(sender: AnyObject) { let alertController = UIAlertController(title: "Info", message: "The local IP is: " + localIP + " consider to chang it in order to mach your PC's IP \n the Splinxs server is avaliable only if you are connected to the BFH network", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } @IBAction func connectAction(sender: AnyObject) { //check if it's connected to socket.io if !isConnected { let alertController = UIAlertController(title: "Attention", message: "You are not connected, maybe the server is down. \n I try to reconnect now.", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } //check if the text is not empty else if nicknameTextFiel.text?.characters.count == 0 { let alertController = UIAlertController(title: "Attention", message: "You must enter a nickname", preferredStyle: UIAlertControllerStyle.Alert) alertController.addAction(UIAlertAction(title: "Ok", style: UIAlertActionStyle.Default,handler: nil)) self.presentViewController(alertController, animated: true, completion: nil) return } else { //self.nickname = nicknameTextFiel.text self.performSegueWithIdentifier("goToUsers", sender: nicknameTextFiel.text) } } override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { if let identifier = segue.identifier { if identifier == "goToUsers" { let usersTableVC = segue.destinationViewController as! usersTableViewController usersTableVC.nickname = nicknameTextFiel.text } } } @IBAction func ipChanged(sender: AnyObject) { isConnected = false self.statusLable.text = "Offline" let socketIP = (ipSegmentedControl.selectedSegmentIndex != 0) ? splinxsIP : localIP socketIOcontroller.sharedInstance.closeConnection() socketIOcontroller.sharedInstance.setSocketIP(socketIP) socketIOcontroller.sharedInstance.isConnectionEstablished{ (isConnected) -> Void in dispatch_async(dispatch_get_main_queue(), { () -> Void in self.isConnected = isConnected self.statusLable.text = isConnected ? "Online" : "Offline" }) } socketIOcontroller.sharedInstance.establishConnection() } /* // 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. } */ }
mit
Fenrikur/ef-app_ios
Eurofurence/Modules/Map Detail/Interactor/DefaultMapDetailInteractor.swift
1
3391
import EurofurenceModel import Foundation class DefaultMapDetailInteractor: MapDetailInteractor, MapsObserver { private struct ViewModel: MapDetailViewModel { let map: Map var mapImagePNGData: Data var mapName: String { return map.location } func showContentsAtPosition(x: Float, y: Float, describingTo visitor: MapContentVisitor) { let contentHandler = ContentHandler(x: x, y: y, visitor: visitor) map.fetchContentAt(x: Int(x), y: Int(y), completionHandler: contentHandler.handle) } } private struct ContentHandler { var x: Float var y: Float var visitor: MapContentVisitor func handle(_ content: MapContent) { switch content { case .location(let altX, let altY, let name): let coordinate = MapCoordinate(x: altX, y: altY) if let name = name { let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: name) visitor.visit(contextualInfo) } visitor.visit(coordinate) case .room(let room): let coordinate = MapCoordinate(x: x, y: y) let contextualInfo = MapInformationContextualContent(coordinate: coordinate, content: room.name) visitor.visit(contextualInfo) case .dealer(let dealer): visitor.visit(dealer.identifier) case .multiple(let contents): visitor.visit(OptionsViewModel(contents: contents, handler: self)) case .none: break } } } private struct OptionsViewModel: MapContentOptionsViewModel { private let contents: [MapContent] private let handler: ContentHandler init(contents: [MapContent], handler: ContentHandler) { self.contents = contents self.handler = handler optionsHeading = .selectAnOption options = contents.compactMap { (content) -> String? in switch content { case .room(let room): return room.name case .dealer(let dealer): return dealer.preferredName case .location(_, _, let name): return name default: return nil } } } var optionsHeading: String var options: [String] func selectOption(at index: Int) { let content = contents[index] handler.handle(content) } } private let mapsService: MapsService private var maps = [Map]() init(mapsService: MapsService) { self.mapsService = mapsService mapsService.add(self) } func makeViewModelForMap(identifier: MapIdentifier, completionHandler: @escaping (MapDetailViewModel) -> Void) { guard let map = maps.first(where: { $0.identifier == identifier }) else { return } map.fetchImagePNGData { (mapGraphicData) in let viewModel = ViewModel(map: map, mapImagePNGData: mapGraphicData) completionHandler(viewModel) } } func mapsServiceDidChangeMaps(_ maps: [Map]) { self.maps = maps } }
mit
mohssenfathi/MTLImage
Example-iOS/Example-iOS/ViewControllers/Info/InfoViewController.swift
1
1839
// // InfoViewController.swift // MTLImage // // Created by Mohssen Fathi on 4/3/16. // Copyright © 2016 CocoaPods. All rights reserved. // import UIKit class InfoViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { @IBOutlet weak var tableView: UITableView! var metadata: [[String:Any]]! override func viewDidLoad() { super.viewDidLoad() } @IBAction func closeButtonPressed(_ sender: AnyObject) { dismiss(animated: true, completion: nil) } // MARK: - UITableView // MARK: DataSource func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return metadata.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath) let titleLabel = cell.viewWithTag(101) as! UILabel let valueLabel = cell.viewWithTag(102) as! UILabel let dict = metadata[(indexPath as NSIndexPath).row] as! [String : String] titleLabel.text = dict["title"]?.capitalized valueLabel.text = dict["value"] return cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } /* // 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. } */ }
mit
colinta/Moya
Demo/Demo/GitHubAPI.swift
6
2180
import Foundation import Moya // MARK: - Provider setup private func JSONResponseDataFormatter(data: NSData) -> NSData { do { let dataAsJSON = try NSJSONSerialization.JSONObjectWithData(data, options: []) let prettyData = try NSJSONSerialization.dataWithJSONObject(dataAsJSON, options: .PrettyPrinted) return prettyData } catch { return data //fallback to original data if it cant be serialized } } let GitHubProvider = MoyaProvider<GitHub>(plugins: [NetworkLoggerPlugin(verbose: true, responseDataFormatter: JSONResponseDataFormatter)]) // MARK: - Provider support private extension String { var URLEscapedString: String { return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLHostAllowedCharacterSet())! } } public enum GitHub { case Zen case UserProfile(String) case UserRepositories(String) } extension GitHub: TargetType { public var baseURL: NSURL { return NSURL(string: "https://api.github.com")! } public var path: String { switch self { case .Zen: return "/zen" case .UserProfile(let name): return "/users/\(name.URLEscapedString)" case .UserRepositories(let name): return "/users/\(name.URLEscapedString)/repos" } } public var method: Moya.Method { return .GET } public var parameters: [String: AnyObject]? { switch self { case .UserRepositories(_): return ["sort": "pushed"] default: return nil } } public var sampleData: NSData { switch self { case .Zen: return "Half measures are as bad as nothing at all.".dataUsingEncoding(NSUTF8StringEncoding)! case .UserProfile(let name): return "{\"login\": \"\(name)\", \"id\": 100}".dataUsingEncoding(NSUTF8StringEncoding)! case .UserRepositories(_): return "[{\"name\": \"Repo Name\"}]".dataUsingEncoding(NSUTF8StringEncoding)! } } } public func url(route: TargetType) -> String { return route.baseURL.URLByAppendingPathComponent(route.path).absoluteString }
mit
natestedman/ArrayLoader
ArrayLoader/ArrayLoader.swift
1
4113
// ArrayLoader // Written in 2015 by Nate Stedman <nate@natestedman.com> // // To the extent possible under law, the author(s) have dedicated all copyright and // related and neighboring rights to this software to the public domain worldwide. // This software is distributed without any warranty. // // You should have received a copy of the CC0 Public Domain Dedication along with // this software. If not, see <http://creativecommons.org/publicdomain/zero/1.0/>. import ReactiveCocoa import Result /// The base protocol for array loader types. /// /// An array loader incrementally builds an array of `Element` values by loading `previous` and `next` pages. These /// pages can be infinite – bounded only by memory limits, or can terminate. /// /// The current state of the array loader is tracked through the current `state` value, of type `LoaderState`. This /// includes the current array and the states for the current `previous` and `next` pages: whether they have more /// values, have completed, are currently loading more values, or failed to load more values. The failure case includes /// an associated error of type `Error`. The possible page states are documented in more detail in the `PageState` type. public protocol ArrayLoader { // MARK: - Types /// The element type of the array loader. associatedtype Element /// The error type of the array loader. associatedtype Error: ErrorType // MARK: - State /// The current state of the array loader. var state: AnyProperty<LoaderState<Element, Error>> { get } // MARK: - Events /// A producer for the events of the array loader. When started, this producer will immediately yield a /// `.Current` event. var events: SignalProducer<LoaderEvent<Element, Error>, NoError> { get } // MARK: - Loading Elements /// Instructs the array loader to load its next page. If the next page is already loading, this function should do /// nothing. func loadNextPage() /// Instructs the array loader to load the previous page. If the previous page is already loading, this function /// should do nothing. func loadPreviousPage() } // MARK: - State Extensions extension ArrayLoader { // MARK: - Properties /// The elements currently loaded by the array loader. public var elements: [Element] { return state.value.elements } /// The next page state of the array loader. public var nextPageState: PageState<Error> { return state.value.nextPageState } /// The previous page state of the array loader. public var previousPageState: PageState<Error> { return state.value.previousPageState } } extension ArrayLoader { // MARK: - Transformations /// Transforms the array loader's elements. /// /// - parameter transform: An element function. @warn_unused_result public func mapElements<Other>(transform: Element -> Other) -> AnyArrayLoader<Other, Error> { return AnyArrayLoader( arrayLoader: self, transformState: { $0.mapElements(transform) }, transformEvents: { $0.mapElements(transform) } ) } /// Transforms the array loader's errors. /// /// - parameter transform: An error transform function. @warn_unused_result public func mapErrors<Other: ErrorType>(transform: Error -> Other) -> AnyArrayLoader<Element, Other> { return AnyArrayLoader( arrayLoader: self, transformState: { $0.mapErrors(transform) }, transformEvents: { $0.mapErrors(transform) } ) } } extension ArrayLoader where Error == NoError { // MARK: - Composition Support /** Promotes a non-erroring array loader to be compatible with error-yielding array loaders. - parameter error: The error type to promote to. */ @warn_unused_result public func promoteErrors<Promoted: ErrorType>(error: Promoted.Type) -> AnyArrayLoader<Element, Promoted> { return mapErrors({ $0 as! Promoted }) } }
cc0-1.0
TheHolyGrail/Swallow
Source/Core/Session.swift
3
808
// // Session.swift // ELWebService // // Created by Angelo Di Paolo on 2/29/16. // Copyright © 2016 WalmartLabs. All rights reserved. // import Foundation // MARK: - Session public protocol Session { func dataTask(request: URLRequestEncodable, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTask } extension URLSession: Session { public func dataTask(request: URLRequestEncodable, completion: @escaping (Data?, URLResponse?, Error?) -> Void) -> DataTask { return dataTask(with: request.urlRequestValue, completionHandler: completion) as DataTask } } // MARK: - Data Task public protocol DataTask { var state: URLSessionTask.State { get } func suspend() func resume() func cancel() } extension URLSessionDataTask: DataTask {}
mit
amujic5/AFEA
AFEA-StarterProject/AFEA-StarterProject/Extensions/PercentageFormatter.swift
1
249
import Foundation extension NumberFormatter { static let percentage: NumberFormatter = { let formatter = NumberFormatter() formatter.numberStyle = .percent formatter.locale = .current return formatter }() }
mit
SwiftOnEdge/Edge
Sources/POSIX/Socket.swift
1
1414
#if os(Linux) import Glibc let sockStream = Int32(SOCK_STREAM.rawValue) let sockDgram = Int32(SOCK_DGRAM.rawValue) let sockSeqPacket = Int32(SOCK_SEQPACKET.rawValue) let sockRaw = Int32(SOCK_RAW.rawValue) let sockRDM = Int32(SOCK_RDM.rawValue) #else import Darwin.C let sockStream = SOCK_STREAM let sockDgram = SOCK_DGRAM let sockSeqPacket = SOCK_SEQPACKET let sockRaw = SOCK_RAW let sockRDM = SOCK_RDM #endif public typealias Port = UInt16 public struct SocketType { public static let stream = SocketType(rawValue: sockStream) public static let datagram = SocketType(rawValue: sockDgram) public static let seqPacket = SocketType(rawValue: sockSeqPacket) public static let raw = SocketType(rawValue: sockRaw) public static let reliableDatagram = SocketType(rawValue: sockRDM) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } } public struct AddressFamily { public static let unix = AddressFamily(rawValue: AF_UNIX) public static let inet = AddressFamily(rawValue: AF_INET) public static let inet6 = AddressFamily(rawValue: AF_INET6) public static let ipx = AddressFamily(rawValue: AF_IPX) public static let netlink = AddressFamily(rawValue: AF_APPLETALK) public let rawValue: Int32 public init(rawValue: Int32) { self.rawValue = rawValue } }
mit
juheon0615/GhostHandongSwift
HandongAppSwift/MenuModel.swift
3
506
// // MenuModel.swift // HandongAppSwift // // Created by csee on 2015. 2. 5.. // Copyright (c) 2015년 GHOST. All rights reserved. // import Foundation class MenuModel { var menu: String var price: String init(menu: String?, price: String?) { if menu != nil { self.menu = menu! } else { self.menu = " " } if price != nil { self.price = price! } else { self.price = "" } } }
mit
cozkurt/coframework
COFramework/COFramework/Swift/Components/CustomTable/Extensions/UITableViewCell+CustomTable.swift
1
812
// // UITableViewCell+CustomTable.swift // FuzFuz // // Created by Cenker Ozkurt on 1/28/20. // Copyright © 2020 FuzFuz. All rights reserved. // import UIKit import Foundation extension UITableViewCell { func removeSeparator() { self.separatorInset = UIEdgeInsets.init(top: 0, left: 1000, bottom: 0, right: 0) } func hideThisCell(customTableBase: CustomTableBase?) { customTableBase?.expandCell(cellDescriptor: CellDescriptor(cellName: self.reuseIdentifier), hidden: true) } func showThisCell(customTableBase: CustomTableBase?) { customTableBase?.expandCell(cellDescriptor: CellDescriptor(cellName: self.reuseIdentifier), hidden: false) } func reloadData(customTableBase: CustomTableBase?) { customTableBase?.reloadData() } }
gpl-3.0
nerdishbynature/OysterKit
OysterKit/OysterKitTests/stateTestBranch.swift
1
2687
// // stateTestBranch.swift // OysterKit Mac // // Created by Nigel Hughes on 03/07/2014. // Copyright (c) 2014 RED When Excited Limited. All rights reserved. // import XCTest import OysterKit class stateTestBranch: XCTestCase { let tokenizer = Tokenizer() func testBranch(){ let branch = char("x").branch(char("y").token("xy"), char("z").token("xz")) tokenizer.branch(branch, OKStandard.eot) XCTAssert(tokenizer.tokenize("xyxz") == [token("xy"),token("xz")]) } func testRepeatLoopEquivalence(){ let seperator = Characters(from: ",").token("sep") let lettersWithLoop = LoopingCharacters(from:"abcdef").token("easy") let state = Characters(from:"abcdef").token("ignore") let lettersWithRepeat = Repeat(state: state).token("easy") let space = Characters(from: " ") let bracketedWithRepeat = Delimited(open: "(", close: ")", states: lettersWithRepeat).token("bracket") let bracketedWithLoop = Delimited(open: "(", close: ")", states: lettersWithLoop).token("bracket") tokenizer.branch([ bracketedWithLoop, seperator, space ]) let underTest = Tokenizer() underTest.branch([ bracketedWithRepeat, seperator, space]) let testString = "(a),(b) (c)(e),(abc),(def) (fed)(aef)" let testTokens = underTest.tokenize(testString) let referenceTokens = tokenizer.tokenize(testString) assertTokenListsEqual(testTokens, reference: referenceTokens) } func testNestedBranch(){ let branch = Branch(states: [char("x").branch(char("y").token("xy"), char("z").token("xz"))]) tokenizer.branch(branch) XCTAssert(tokenizer.tokenize("xyxz") == [token("xy"),token("xz")]) } func testXY(){ tokenizer.sequence(char("x"),char("y").token("xy")) tokenizer.branch(OKStandard.eot) XCTAssert(tokenizer.tokenize("xy") == [token("xy")], "Chained results do not match") } func testSequence1(){ let expectedResults = [token("done",chars:"xyz")] tokenizer.branch( sequence(char("x"),char("y"),char("z").token("done")), OKStandard.eot ) XCTAssert(tokenizer.tokenize("xyz") == expectedResults) } func testSequence2(){ let expectedResults = [token("done",chars:"xyz")] tokenizer.branch( char("x").sequence(char("y"),char("z").token("done")), OKStandard.eot ) XCTAssert(tokenizer.tokenize("xyz") == expectedResults) } }
bsd-2-clause
ahoppen/swift
test/decl/ext/extension-inheritance-conformance-native.swift
38
286
// RUN: %target-typecheck-verify-swift class Object {} class Responder: Object {} class View: Responder {} extension View {} protocol Foo {} extension Foo { func bar() -> Self { return self } } extension Object: Foo {} _ = Object().bar() _ = Responder().bar() _ = View().bar()
apache-2.0
dreamsxin/swift
validation-test/compiler_crashers_fixed/26667-swift-iterabledeclcontext-getmembers.swift
11
594
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See http://swift.org/LICENSE.txt for license information // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -parse struct B<T{class B<h let e=B{ T:{ struct d{ class A{var A{i{ a:{{ } class d{ struct B{ struct B{ var a{var a{ B{ } { func a { e= { var _=a{ {A{ } { let a<T{B: {{ <T{a{ struct D{ { } func a{ {{ struct B
apache-2.0
katzbenj/MeBoard
Keyboard/ExNumKeyboard.swift
2
6696
// // ExNumKeyboard.swift // TransliteratingKeyboard // // Created by Alexei Baboulevitch on 7/10/14. // Copyright (c) 2014 Alexei Baboulevitch ("Archagon"). All rights reserved. // func exNumKeyboard() -> Keyboard { let exNumKeyboard = Keyboard() let shift = Key(.shift) let backspace = Key(.backspace) let offset = 0 for key in [":~", "Q1", "W2", "E3", "R4", "T5", "Y6", "U7", "I8", "O9", "P0", "({", ")}", "/\\"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 0 + offset, page: 0) } let tabKey = Key(.tab) tabKey.uppercaseKeyCap = "tab" tabKey.uppercaseOutput = "\t" tabKey.lowercaseOutput = "\t" tabKey.size = 1 exNumKeyboard.addKey(tabKey, row: 1 + offset, page: 0) for key in ["A#", "S$", "D%", "F+", "G-", "H=", "J*", "K^", "L&", "!¡", "\"<", "'>"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 1 + offset, page: 0) } let tab2 = Key(.tab) tab2.uppercaseKeyCap = "tab" tab2.uppercaseOutput = "\t" tab2.lowercaseOutput = "\t" //exNumKeyboard.addKey(tab2, row: 1 + offset, page: 0) exNumKeyboard.addKey(shift, row: 2 + offset, page: 0) for key in ["Z`", "X_", "C✓", "V°", "B×", "N≈", "M÷", ",;", ".•", "?¿"] { let keyModel = Key(.character) if key.characters.count == 1 { keyModel.setLetter(key) } else { let secondLetterIndex = key.index(key.startIndex, offsetBy: 1) keyModel.setLetter(String(key[key.startIndex]), secondaryLetter: String(key[secondLetterIndex])) } exNumKeyboard.addKey(keyModel, row: 2 + offset, page: 0) } //let backspace = Key(.backspace) exNumKeyboard.addKey(backspace, row: 2 + offset, page: 0) let keyModeChangeNumbers = Key(.modeChange) keyModeChangeNumbers.uppercaseKeyCap = "123" keyModeChangeNumbers.toMode = 1 exNumKeyboard.addKey(keyModeChangeNumbers, row: 3 + offset, page: 0) let keyboardChange = Key(.keyboardChange) exNumKeyboard.addKey(keyboardChange, row: 3 + offset, page: 0) //let settings = Key(.settings) //exNumKeyboard.addKey(settings, row: 3 + offset, page: 0) let space = Key(.space) space.uppercaseKeyCap = "space" space.uppercaseOutput = " " space.lowercaseOutput = " " exNumKeyboard.addKey(space, row: 3 + offset, page: 0) let keyModel = Key(.specialCharacter) keyModel.setLetter("@") exNumKeyboard.addKey(keyModel, row: 3 + offset, page: 0) let returnKey = Key(.return) returnKey.uppercaseKeyCap = "return" returnKey.uppercaseOutput = "\n" returnKey.lowercaseOutput = "\n" exNumKeyboard.addKey(returnKey, row: 3 + offset, page: 0) let atSize = 1 / exNumKeyboard.pages[0].maxRowSize() let spaceBarSize = 0.6 - atSize exNumKeyboard.pages[0].setRelativeSizes(percentArray: [0.1, 0.1, spaceBarSize, atSize, 0.2], rowNum: 3 + offset) for key in ["#", "$", "&", ":", "-", "7", "8", "9", "/", "°"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 0, page: 1) } for key in ["@", "(", ")", "=", "+", "4", "5", "6", "*", "_"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 1, page: 1) } let keyModeChangeSpecialCharacters = Key(.modeChange) keyModeChangeSpecialCharacters.uppercaseKeyCap = "#+=" keyModeChangeSpecialCharacters.toMode = 2 exNumKeyboard.addKey(keyModeChangeSpecialCharacters, row: 2, page: 1) for key in ["'", "\"", "%", "1", "2", "3"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 2, page: 1) } exNumKeyboard.addKey(Key(backspace), row: 2, page: 1) let keyModeChangeLetters = Key(.modeChange) keyModeChangeLetters.uppercaseKeyCap = "ABC" keyModeChangeLetters.toMode = 0 exNumKeyboard.addKey(keyModeChangeLetters, row: 3, page: 1) exNumKeyboard.addKey(Key(keyboardChange), row: 3, page: 1) //exNumKeyboard.addKey(Key(settings), row: 3, page: 1) exNumKeyboard.addKey(Key(space), row: 3, page: 1) for key in [",", "0", "."] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 3, page: 1) } exNumKeyboard.addKey(Key(returnKey), row: 3, page: 1) exNumKeyboard.pages[1].setRelativeSizes(percentArray: [0.1, 0.1, 0.3, 0.1, 0.1, 0.1, 0.2], rowNum: 3 + offset) for key in ["£", "€", "¥", "₵", "©", "®", "™", "~", "¿", "≈"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 0, page: 2) } for key in ["[", "]", "{", "}", "<", ">", "^", "¡", "×", "•"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 1, page: 2) } exNumKeyboard.addKey(Key(keyModeChangeNumbers), row: 2, page: 2) for key in ["`", ";", "÷", "\\", "|", "✓"] { let keyModel = Key(.specialCharacter) keyModel.setLetter(key) exNumKeyboard.addKey(keyModel, row: 2, page: 2) } exNumKeyboard.addKey(Key(backspace), row: 2, page: 2) exNumKeyboard.addKey(Key(keyModeChangeLetters), row: 3, page: 2) exNumKeyboard.addKey(Key(keyboardChange), row: 3, page: 2) //exNumKeyboard.addKey(Key(settings), row: 3, page: 2) exNumKeyboard.addKey(Key(space), row: 3, page: 2) exNumKeyboard.addKey(Key(returnKey), row: 3, page: 2) exNumKeyboard.pages[2].setRelativeSizes(percentArray: [0.1, 0.1, 0.6, 0.2], rowNum: 3 + offset) return exNumKeyboard } func proportionalButtonSize(page: Page, percentage: Double)->Double { assert(percentage < 1) let maxRowSize = page.maxRowSize() return maxRowSize * percentage }
bsd-3-clause
xcs-go/swift-Learning
Control Flow.playground/Contents.swift
1
19169
//: Playground - noun: a place where people can play import UIKit var str = "Hello, playground" // For 循环 // swift提供了两种for循环:for--in / for //for in 循环对一个集合里面的每个元素执行一系列语句 //for 循环,用来重复执行一系列语句直到达成特定条件,一般通过在每次循环完成后增加计数器的值来实现 //for in:可以使用for-in循环来遍历一个集合里面的所有元素,例如由数字表示的区间、数组中的元素、字符串中的字符 for index in 1...5{ print("\(index) time 5 is \(index * 5)") } // 如果你不需要知道区间序列内每一项的值,你可以使用下划线“_”替代变量名来忽略对值的访问 let base = 3 let power = 10 var answer = 1 for _ in 1...power { answer *= base } print("\(base) to the power of \(power) is \(answer)") // 使用for-in 遍历一个数组所有元素 let names = ["Anna","Alex","Brian","Jack"] for name in names{ print("Hello,\(name)!") } // 可以遍历一个字典来访问它的健值对。遍历字典时,字典的每项元素会以(key,value)元组的形式返回,可以在for in循环中使用显式的常量名称来解读(key,value)元组。 let numberOfLegs = ["spider":"8","ant":"6","cat":"4"] for(animalNam,legCount) in numberOfLegs{ print("\(animalNam)s have \(legCount) legs") } // 注意:字典元素的遍历顺序和插入顺序可能不同,字典的内容在内部是无序的,所以遍历元素是不能保证顺序。 //For 循环 swift提供使用条件判断和递增方法的标准C样式for循环 for var index = 0;index<3; ++index{ print("index is \(index)") } // while循环 //while循环运行一系列语句直到条件变成false。这类循环适合使用在第一次迭代次数未知的情况下。 // while循环,每次在循环开始时计算条件是否符合,如果不符合,则跳过循环,符合条件才会执行循环里面的代码 // repeat-while循环,每次在循环结束时计算条件是否符合 // 条件语句 //if和switch;if语句he其它语言的if语句一样,只是没有了() //switch 区间匹配 case分支的模式也可以是一个值的区间。 let approximateCount = 62 let countedThings = "moons orbiting Saturn" var naturalCount:String switch approximateCount{ case 0: naturalCount = "no" case 1..<5: naturalCount = "a few" case 5..<12: naturalCount = "serveral" case 12..<100: naturalCount = "dozens of" case 100..<1000: naturalCount = "hundreds of" default: naturalCount = "many" } print("There are \(naturalCount) \(countedThings).") // 元组 ,我们可以使用元组在同一个switch语句中测试多个值,元组中的元素可以是值,也可以是区间,另外,使用下划线(_)来匹配所有可能的值 let somePoint = (1,1) print("\(somePoint.1)") // 可以利用点语法从元组中取出某个值 switch somePoint{ case(0,0): print("(0,0) is at the origin") case(_,0): print("(\(somePoint.0),0) is on the x-axis") case(0,_): print("(0,\(somePoint.1)) is on the y-axis") case(-2...2,-2...2): print("(\(somePoint.0), \(somePoint.1)) is inside the box") default: print("(\(somePoint.0), \(somePoint.1)) is outside of the box") } // 带标签的语句 // 使用标签来标记一个循环体或者switch代码块,当使用break或者continue时,带上这个标签,可以控制标签代表对象的中断或者执行 // 产生一个带标签的语句是通过在该语句的关键词的同一行前面放置一个标签,并且该标签后面还需要带着一个冒号。 //label name:while condition{ //} // 提前退出 // 像if语句一样,guard的执行取决于一个表达式的布尔值。可以使用guard语句来要求条件必须为真时,以执行guard语句后的代码。不同于if语句,一个guard语句总是有一个else分句,如果条件不为真则执行else分句中的代码 //func greet(person:[String:String]){ // guard let name = person["name"] else{ // return // } // print("hello \(name)") // // guard let location = person["location"] else { // print("I hope the weather is nice near you.") // return // } // print("I hope the weather is nice in \(location)") //} // 函数 // 1:函数的定义与调用 // 定义函数时,可以定义函数的参数和参数的类型,也可以定义函数的返回值 // 每个函数有个函数名。用来描述函数执行的任务,使用函数时,使用函数名调用函数吗并且给该函数传递相关的参数 func sayHello(person:String) -> String { let greeting = "hello, " + person + "!" return greeting } print(sayHello("lmg")) // 函数参数与返回值 //1:无参函数 func sayHelloWorld() -> String{ return"hello world" } print(sayHelloWorld()) // 2:多参数函数 // 函数可以带有多种参数,参数类型也可以不相同,这些参数被包含在函数的括号中,相互之间用逗号分隔 func sayHi(personName:String, alreadyGreeted:Bool) -> String { if alreadyGreeted { return sayHello(personName) } else { return sayHelloWorld() } } print(sayHi("Tim", true)) //3:无返回值函数 func sayGoodbye(personName: String) { print("Goodbye, \(personName)!") } sayGoodbye("Dave") // 被调用时,一个函数的返回值可以被忽略 //func printAndCount(StringToPrint:String) -> Int { // print(StringToPrint) // return StringToPrint.characters.count //} //func printWithoutCounting(stringToPrint:String) { // printAndCount(stringToPrint) // 被调用,函数的返回值被忽略 //} // //printAndCount("hello world") // 多重返回值函数 // 使用元组类型让多个值作为一个复合值从函数中返回 //func minMax(array:[Int]) -> (min:Int,max:Int) { // var currentMin = array[0] // var currentMax = array[0] // for value in array[1..<array.count]{ // if value < currentMin { // currentMin = value // }else if value > currentMax { // currentMax = value // } // } // return(currentMin,currentMax) //} //print(minMax([2,5,6,8,0,74,85])) // 可选元组返回类型 // 如果函数返回的元组类型有可能整个元组都没有值,则可以在元组的返回值的右括号中添加一个❓来表示该元组是一个可选的。 func minMax(array:[Int]) -> (min:Int,max:Int)? { var currentMin = array[0] var currentMax = array[0] for value in array[1..<array.count]{ if value < currentMin { currentMin = value }else if value > currentMax { currentMax = value } } return(currentMin,currentMax) } print(minMax([2,5,6,8,0,74,85])) // 可以使用可选绑定来检查minMax:函数返回的是一个实际的元组值还是nil // 函数参数名称 // 函数参数都有有一个外部参数名和一个局部参数名,外部参数名用于在函数调用时标注传递给函数的参数,局部参数名在函数的实现内部使用 //func someFunction(firstParameterName:Int,secondParameterName:Int) { // //} // //someFunction(1, 2) // 指定外部参数名:在局部参数名前指定外部参数名,中间以空格分隔 func say(to person:String,and anotherPerson:String) -> String { return "hello \(person) and \(anotherPerson)" } print(say(to: "Bill", and: "Ted")) // 可变参数:一个可变参数可以接受零个或多个值。函数调用时, 你可以用可变参数来指定函数参数可以被传入不确定数量的输入值通过在变量名后面加入(...)的方式来定义可变参数。 // 可变参数的传入值在函数体中变为此类型的一个数组。一个函数最多只有一个可变参数 func arithmeticMean(numbers:Double...) -> Double { var total:Double = 0 for number in numbers { total += number } return total / Double(numbers.count) } arithmeticMean(1,2,3,4,5) // 常量参数和变量参数 //func alignRight(var String:String,totalLength:Int,pad:Character) -> String { // let amountToPad = totalLength - String.characters.count // if amountToPad<1{ // return String // } // let padstring = String(pad) // for _ in 1...amoutToPad { // String = padstring + String // } // return String //} // //let originalString = "hello" //let paddedString = alignRight(originalString, 10, "-") // 输入输出参数 // 如果你想要一个函数可以修改参数的值,并且想要在这些修改在函数调用结束后仍然存在,那么就应该把这个参数定义为输入输出参数.在参数定义前加input关键字,传入参数时,需要在参数名前加&符,表示这个值可以被修改 func swapTwoInts(inout a:Int,inout b:Int){ let temporaryA = a a = b b = temporaryA } var someInt = 3 var anotherInt = 107 swapTwoInts(&someInt, &anotherInt) // 函数类型 func addTwoInts(a:Int,b:Int) -> Int { return a + b } func mulitiplyTwoInts(a:Int,b:Int) -> Int { return a * b } // 使用函数类型 // 在swift中,使用函数类型就想使用其他类型一样。可以定义一个类型为函数的常量或变量,并将适当的函数赋值给它 var mathFunction:(Int,Int) -> Int = addTwoInts // 通过使用mathFunction来调用被赋值的函数 print("\(mathFunction(2,3))") // 有相同匹配类型的不同函数可以被赋值给同一个变量 mathFunction = mulitiplyTwoInts print("\(mathFunction(2,3))") // 函数类型作为参数类型 func printMathResult(mathFunction:(Int,Int) -> Int,a :Int,b:Int) -> Int { // print("\(mathFunction(a,b))") return mathFunction(a,b) } printMathResult(addTwoInts, 3, 4) // 函数类型作为返回类型 // 在返回箭头后写一个完整的函数类型 func stepForward(input:Int) -> Int { return input + 1 } func stepBackward(input:Int) -> Int { return input - 1 } func chooseStepFunction(backwards:Bool) -> (Int) ->Int { return backwards ? stepBackward : stepForward } var currentValue = 3 let moveNearerToZero = chooseStepFunction(currentValue > 0) // 嵌套函数 : 在一个函数体中定义另一个函数,叫做嵌套函数 // 默认情况下,嵌套函数是对外界不可见的,但是可以被它们的外围函数调用,一个外围函数也可以返回它的某一个嵌套函数,使得这个函数可以在其他领域中被调用 // 闭包 // 闭包是自包含的函数代码块,可以在代码中被传递和使用。闭包可以捕获和存储其所在上下文中任意常量和变量的应用。这就是所谓的闭合并包裹着这些常量和变量,俗称闭包 // 闭包的三种形式 //1:全局函数是一个有名字但不会捕获任何值的闭包 //2:嵌套函数是一个有名字并可以捕获其封闭函数内值的闭包 //3:闭包表达式是一个利用轻量级语法所写的可以捕获其上下文中变量或常量的值的匿名闭包 //swift 的闭包表达式拥有简洁的风格,并鼓励在常见场景中进行语法优化 //1:利用上下文推断参数和返回值类型 //2:隐士返回单表达式闭包,即单表达式闭包可以省略return关键字 //3:参数名称缩写 //4:尾随闭包语法 // 闭包表达式 // sort方法:会根据提供的用于排序的闭包函数将已知类型数组中的值进行排序,排序完成后,sort方法会返回一个与原数组大小相同,包含同类型元素且元素已正确排序的新数组。 let stringNames = ["Chris","Alex","Ewa","Barry","Daniella"] //func backWards(s1:String,s2:String) -> Bool{ // return s1 > s2 //} //var reversed = stringNames.sorted(backWards) // //print("\(reversed)") // 闭包表达式语法形式: // {(parameters) -> returnType in 闭包的函数体部分由关键字in引入,该关键字表示闭包的参数和返回值类型定义已经完成,闭包函数体即将开始 // statements //} var reversed = stringNames.sorted({(s1:String,s2:String) -> Bool in return s1 > s2 }) // 根据上下文推断类型:通过内联闭包表达式构造的闭包作为参数传递给函数或方法时,都可以推断出闭包的参数和返回值类型。这意味着闭包作为函数或者方法的参数时,几乎不需要利用完整格式构造内联闭包. reversed = stringNames.sorted({s1,s2 in return s1 > s2}) print("\(reversed)") // 单表达式闭包隐士返回 // 单行表达式闭包可以通过省略return关键字来隐士返回单行表达式的结果 reversed = stringNames.sorted({s1,s2 in s1 > s2}) // 参数名称缩写 // swift自动为内联闭包提供了参数名称缩写功能,可以直接通过$0,$1,$2来顺序调用闭包的参数.如果在闭包表达式中使用参数名称缩写,您可以在闭包参数列表中省略对其的定义,并且对应参数名称缩写的类型会通过函数类型进行推断。in关键字也同样可以被省略 reversed = stringNames.sorted({$0 > $1}) // 运算符函数 //swift的string类型定义了有关“>”的字符串实现,其作为一个函数接受两个String类型的参数并返回Bool类型的值。swift可以自动推断您想使用大于号的字符串函数实现 reversed = stringNames.sorted(>) // 尾随闭包 // 如果您需要将一个很长的闭包表达式作为最后一个参数传递给函数,可以使用尾随闭包来增强函数的可读性。尾随闭包是一个书写在函数括号之后的闭包表达式,函数支持将其作为最后一个参数调用: func someFunctionThatTakesAClosure(closure:() -> Void) { // 函数体部分 } // 以下是不使用尾随闭包进行函数调用 someFunctionThatTakesAClosure({ // 闭包主体部分 }) // 一下是使用尾随闭包进行函数调用 someFunctionThatTakesAClosure(){ // 闭包主体部分 } reversed = stringNames.sorted(){(s1:String,s2:String) -> Bool in s1 > s2} print("\(reversed)") reversed = stringNames.sorted(){s1,s2 in s1 > s2} reversed = stringNames.sorted(){$0 > $1} // 如果函数只需要闭包表达式一个参数,当使用尾随闭包时,可以把()省略掉 reversed = stringNames.sorted{$0 > $1} print("\(reversed)") // Array类型的map(_:)方法,其获取一个闭包表达式作为其唯一参数,该闭包函数会为数组中的每一个元素调用一次,并且返回该元素所映射的值。具体的映射方式和返回值类型由闭包来指定 let digitNames = [ 0:"Zero",1:"One",2:"Two",3:"There",4:"Four",5:"Five",6:"Six",7:"Seven",8:"Eight",9:"Nine" ] let numbers = [16,58,510] let strings = numbers.map{(var number) -> String in var output = "" while number > 0 { output = digitNames[number % 10]! + output number /= 10 } return output } // 捕获值 // 闭包可以在其被定义的上下文中捕获常量或变量。即便定义这些常量和变量的原作用域已经不存在,闭包仍然可以在闭包函数体内引用和修改这些值 func makeIncrementor(forIncrement amout:Int) -> () -> Int { var runningTotal = 0 func incrementor() -> Int { runningTotal += amout return runningTotal } return incrementor // 函数可以作为一个返回值返回 } // 为了优化,如果一个值是不可变的,swift可能会改为捕获并保存一份对值的拷贝 let incrementByTen = makeIncrementor(forIncrement: 10) incrementByTen() incrementByTen() incrementByTen() // 如果创建了另一个incrementor,它会有属于它自己的一个全新、独立的runningTotal变量的引用;再次调用原来的incrementByTen会在原来的变量runningTotal上继续增加值,该变量和increnmentBySeven中捕获的变量没有任何联系 let incrementBySeven = makeIncrementor(forIncrement: 7) incrementBySeven() incrementByTen() // 闭包是引用类型 // 函数和闭包都是引用类型 // 无论将函数或闭包赋值给一个变量还是常量,实际上都是将变量或常量的值设置为对应函数或闭包的引用.因此,如果将闭包赋值给了两个不同的常量或变量,两个值都会指向同一个闭包 let alsoIncrementByTen = incrementByTen alsoIncrementByTen() // 非逃逸闭包 // 当一个闭包作为参数传到一个函数中,但是这个闭包在函数返回之后才被执行,我们称该闭包从函数中逃逸。当定义接受闭包作为函数的参数时,可以在参数名之前标注@noescape,用来指明之歌闭包不允许“逃逸”出这个函数. // 闭包职能在函数体中执行,不能脱离函数体执行 func someFunctionWithNoescapeCloure(@noescape cloure:() -> Void) { } var completionHandlers:[() -> Void] = [] // 定义了一个数组变量 func someFunctionWithEscapingClosure(completionHandler: () -> Void) { completionHandlers.append(completionHandler) } //print("irhjdf") class someClass { var x = 10 func dosomething() { someFunctionWithEscapingClosure { self.x = 100 } someFunctionWithNoescapeCloure({x = 200}) } } let instance = someClass() instance.dosomething() print(instance.x) completionHandlers.first?() print(instance.x) completionHandlers.last?() print(instance.x) // 自动闭包 // 自动闭包是一种自动创建的闭包,用于包装传递给函数作为参数的表达式。这种闭包不接受任何参数,当它被调用的时候,会返回被包装在其中的表达式的值。 // 自动闭包让你能够延迟求值 var customersInLine = ["Chris","Alex","Ewa","Barry","Daniella"] print(customersInLine.count) let customerProvider = {customersInLine.removeAtIndex(0)} // {}创建自动闭包 print(customersInLine.count) // 当它被调用的时候,会返回被包装在其中的表达式 print(customerProvider()) // 当它被调用的时候,会返回被包装在其中的表达式 print("Now servins \(customerProvider())!") print(customersInLine.count) // 将闭包作为参数传递给函数时,能获得同样的延时求值行为 func serveCustomer (customerProvider:() -> String) { // 说明接受的是显式的闭包 print("now serviing \(customerProvider())!") // 调用闭包 } serveCustomer(customerProvider) // serveCustomer({customerInLine.removeAtIndex(0)}) print(customersInLine.count) // @autoclosure :标记接收一个自动闭包 func serverCustomer(@autoclosure customerProvider:() -> String) { // 说明接受的是自动闭包 print("Now serving \(customerProvider())!") } serverCustomer(customerProvider()) // @autoclosure 特性暗含了@noescape特性。如果你想让这个闭包可以“逃逸”,则应该使用@autoclosure(escaping)特性 var customereProviders: [() -> String] = [] func collectCustomerProviders(@autoclosure(escaping) customerProvider: () -> String) { customereProviders.append(customerProvider) } collectCustomerProviders(customerProvider()) print("Collected \(customereProviders.count) closures.") for custo in customereProviders { print("Now serving \(customerProvider())!") } print("Collected \(customereProviders.count) closures.")
apache-2.0
yanagiba/swift-ast
Sources/AST/Generic/GenericArgumentClause.swift
2
1102
/* Copyright 2016 Ryuichi Intellectual Property and the Yanagiba project contributors 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. */ import Source public struct GenericArgumentClause { public let argumentList: [Type] public var sourceRange: SourceRange = .EMPTY public init(argumentList: [Type]) { self.argumentList = argumentList } } extension GenericArgumentClause : ASTTextRepresentable { public var textDescription: String { return "<\(argumentList.map({ $0.textDescription }).joined(separator: ", "))>" } } extension GenericArgumentClause : SourceLocatable { }
apache-2.0
RocketChat/Rocket.Chat.iOS
Rocket.Chat/Views/UIPickerView/PickerViewDelegate.swift
1
1054
// // PickerViewDelegate.swift // Rocket.Chat // // Created by Vadym Brusko on 10/12/17. // Copyright © 2017 Rocket.Chat. All rights reserved. // import Foundation class PickerViewDelegate: NSObject, UIPickerViewDataSource, UIPickerViewDelegate { typealias SelectHandler = (String) -> Void internal var data: [String] internal let selectHandler: SelectHandler required init(data: [String], selectHandler: @escaping SelectHandler) { self.data = data self.selectHandler = selectHandler } public func numberOfComponents(in pickerView: UIPickerView) -> Int { return 1 } public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int { return data.count } func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? { return data[row] } func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) { selectHandler(data[row]) } }
mit
lxcid/ListDiff
Tests/ListDiffTests/ListDiffStressTests/Support/CellData.swift
1
820
@testable import ListDiff import XCTest final class CellData: Equatable, Diffable { // MARK: - Properties let title: String let subtitle: String // MARK: - Diffable let diffIdentifier: AnyHashable // MARK: - Init init( diffIdentifier: AnyHashable, title: String, subtitle: String) { self.title = title self.subtitle = subtitle self.diffIdentifier = diffIdentifier } // MARK: - Equatable static func == (lhs: CellData, rhs: CellData) -> Bool { XCTAssert( lhs.diffIdentifier == rhs.diffIdentifier, "We expect the algorythm to compare items only with same `diffIdentifier`" ) return lhs.title == rhs.title && lhs.subtitle == rhs.subtitle } }
mit
ben-ng/swift
validation-test/compiler_crashers_fixed/27570-checkenumrawvalues.swift
1
450
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func u{struct c<T, U{class d?enum S<e{ enum B<T> :d
apache-2.0
ben-ng/swift
validation-test/compiler_crashers_fixed/02056-swift-type-walk.swift
1
564
// This source file is part of the Swift.org open source project // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors // Licensed under Apache License v2.0 with Runtime Library Exception // // See https://swift.org/LICENSE.txt for license information // See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors // RUN: not %target-swift-frontend %s -typecheck func e(T.a(.c == nil protocol A { } class b: B<T) { } struct A : a { extension Array { func b: Collection where f: c<T) -> T] = i()) { var e?) { } } } func a<h : a {
apache-2.0
samodom/TestableCoreLocation
TestableCoreLocation/CLLocationManager/CLLocationManagerRequestAlwaysAuthorizationSpy.swift
1
2060
// // CLLocationManagerRequestAlwaysAuthorizationSpy.swift // TestableCoreLocation // // Created by Sam Odom on 3/6/17. // Copyright © 2017 Swagger Soft. All rights reserved. // import CoreLocation import FoundationSwagger import TestSwagger public extension CLLocationManager { private static let requestAlwaysAuthorizationCalledKeyString = UUIDKeyString() private static let requestAlwaysAuthorizationCalledKey = ObjectAssociationKey(requestAlwaysAuthorizationCalledKeyString) private static let requestAlwaysAuthorizationCalledReference = SpyEvidenceReference(key: requestAlwaysAuthorizationCalledKey) /// Spy controller for ensuring that a location manager has had `requestAlwaysAuthorization` /// called on it. public enum RequestAlwaysAuthorizationSpyController: SpyController { public static let rootSpyableClass: AnyClass = CLLocationManager.self public static let vector = SpyVector.direct public static let coselectors = [ SpyCoselectors( methodType: .instance, original: #selector(CLLocationManager.requestAlwaysAuthorization), spy: #selector(CLLocationManager.spy_requestAlwaysAuthorization) ) ] as Set public static let evidence = [requestAlwaysAuthorizationCalledReference] as Set public static let forwardsInvocations = false } /// Spy method that replaces the true implementation of `requestAlwaysAuthorization` dynamic public func spy_requestAlwaysAuthorization() { requestAlwaysAuthorizationCalled = true } /// Indicates whether the `requestAlwaysAuthorization` method has been called on this object. public final var requestAlwaysAuthorizationCalled: Bool { get { return loadEvidence(with: CLLocationManager.requestAlwaysAuthorizationCalledReference) as? Bool ?? false } set { saveEvidence(newValue, with: CLLocationManager.requestAlwaysAuthorizationCalledReference) } } }
mit
zhubofei/IGListKit
Examples/Examples-iOS/IGListKitExamples/ViewControllers/LoadMoreViewController.swift
4
3111
/** Copyright (c) 2016-present, Facebook, Inc. All rights reserved. The examples provided by Facebook are for non-commercial testing and evaluation purposes only. Facebook reserves all rights not expressly granted. 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 FACEBOOK 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 IGListKit import UIKit final class LoadMoreViewController: UIViewController, ListAdapterDataSource, UIScrollViewDelegate { lazy var adapter: ListAdapter = { return ListAdapter(updater: ListAdapterUpdater(), viewController: self) }() let collectionView = UICollectionView(frame: .zero, collectionViewLayout: UICollectionViewFlowLayout()) lazy var items = Array(0...20) var loading = false let spinToken = "spinner" override func viewDidLoad() { super.viewDidLoad() view.addSubview(collectionView) adapter.collectionView = collectionView adapter.dataSource = self adapter.scrollViewDelegate = self } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() collectionView.frame = view.bounds } // MARK: ListAdapterDataSource func objects(for listAdapter: ListAdapter) -> [ListDiffable] { var objects = items as [ListDiffable] if loading { objects.append(spinToken as ListDiffable) } return objects } func listAdapter(_ listAdapter: ListAdapter, sectionControllerFor object: Any) -> ListSectionController { if let obj = object as? String, obj == spinToken { return spinnerSectionController() } else { return LabelSectionController() } } func emptyView(for listAdapter: ListAdapter) -> UIView? { return nil } // MARK: UIScrollViewDelegate func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) { let distance = scrollView.contentSize.height - (targetContentOffset.pointee.y + scrollView.bounds.height) if !loading && distance < 200 { loading = true adapter.performUpdates(animated: true, completion: nil) DispatchQueue.global(qos: .default).async { // fake background loading task sleep(2) DispatchQueue.main.async { self.loading = false let itemCount = self.items.count self.items.append(contentsOf: Array(itemCount..<itemCount + 5)) self.adapter.performUpdates(animated: true, completion: nil) } } } } }
mit
luispadron/GradePoint
GradePoint/CustomControls/UIBlurAlert/UIBlurAlertView.swift
1
2857
// // UIBlurAlertView.swift // GradePoint // // Created by Luis Padron on 1/17/17. // Copyright © 2017 Luis Padron. All rights reserved. // import UIKit internal class UIBlurAlertView: UIView { // MARK: - Properties private var _title: NSAttributedString internal var title: NSAttributedString { get { return self._title } } private var _message: NSAttributedString? internal var message: NSAttributedString? { get { return self._message} } private lazy var titleLabel = UILabel() private lazy var messageLabel = UILabel() internal var buttons = [UIButton]() { didSet { self.updateButtons() } } // MARK: - Initializers internal required init(frame: CGRect, title: NSAttributedString, message: NSAttributedString?) { self._title = title self._message = message super.init(frame: frame) self.drawViews() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - Helpers private func drawViews() { self.layer.cornerRadius = 5 self.clipsToBounds = true titleLabel.attributedText = _title titleLabel.textAlignment = .center messageLabel.attributedText = _message messageLabel.textAlignment = .center // Set up frames titleLabel.frame = CGRect(x: 0, y: 0, width: self.bounds.width, height: 30) messageLabel.frame = CGRect(x: 0, y: titleLabel.frame.height + 25, width: self.bounds.width, height: 30) messageLabel.resizeToFitText() self.addSubview(titleLabel) self.addSubview(messageLabel) // Add a border to view let bottomBorder = CALayer() bottomBorder.frame = CGRect(x: self.layer.frame.minX, y: titleLabel.frame.height, width: self.layer.frame.width, height: 1) bottomBorder.backgroundColor = UIColor.gray.cgColor self.layer.addSublayer(bottomBorder) } private func updateButtons() { // Loop through all the buttons and add them for (index, button) in buttons.enumerated() { // Calculate the size and positions let width = self.bounds.width / CGFloat(buttons.count) let height = self.bounds.height * 1/4 let xForButton: CGFloat = width * CGFloat(index) let yForButton: CGFloat = self.bounds.maxY - height button.frame = CGRect(x: xForButton, y: yForButton, width: width, height: height) // If already added, then just continue and dont add the button as a subview again if let _ = self.subviews.firstIndex(of: button) { continue } self.addSubview(button) } } }
apache-2.0