repo_name
stringlengths
6
91
path
stringlengths
8
968
copies
stringclasses
210 values
size
stringlengths
2
7
content
stringlengths
61
1.01M
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
6
99.8
line_max
int64
12
1k
alpha_frac
float64
0.3
0.91
ratio
float64
2
9.89
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
FAU-Inf2/kwikshop-ios
Kwik Shop/SettingsViewController.swift
1
5368
// // SettingsViewController.swift // Kwik Shop // // Created by Adrian Kretschmer on 25.08.15. // Copyright (c) 2015 FAU-Inf2. All rights reserved. // import UIKit class SettingsViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { // MARK: Properties @IBOutlet weak var settingsTableView : UITableView! private let LANGUAGE_SELECTION_ENABLED = false private var LANGUAGE_SECTION : Int { return LANGUAGE_SELECTION_ENABLED ? 0 : -1 } private var AUTOCOMPLETION_SECTION : Int { return LANGUAGE_SELECTION_ENABLED ? 1 : 0 } override func viewDidLoad() { super.viewDidLoad() settingsTableView.delegate = self settingsTableView.dataSource = self self.title = "navigation_bar_settings".localized } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) if let indexPath = settingsTableView.indexPathForSelectedRow { settingsTableView.deselectRowAtIndexPath(indexPath, animated: animated) } if LANGUAGE_SELECTION_ENABLED { settingsTableView.reloadRowsAtIndexPaths([NSIndexPath(forRow: 0, inSection: LANGUAGE_SECTION)], withRowAnimation: .None) } } func numberOfSectionsInTableView(tableView: UITableView) -> Int { return LANGUAGE_SELECTION_ENABLED ? 2 : 1 } func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { // Return the number of rows in the section. if section == LANGUAGE_SECTION { return 1 } if section == AUTOCOMPLETION_SECTION { return 2 } return 0 } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let identifier : String let row = indexPath.row let section = indexPath.section if section == LANGUAGE_SECTION { identifier = "languageSettingsCell" } else /*if section == AUTOCOMPLETION_SECTION*/ { if row == 0 { identifier = "autocompletionSettingsCell" } else /*if row == 1*/ { identifier = "brandAutocompletionSettingsCell" } } let cell = tableView.dequeueReusableCellWithIdentifier(identifier, forIndexPath: indexPath) cell.textLabel?.numberOfLines = 2 if section == LANGUAGE_SECTION { cell.textLabel?.text = "settings_language".localized cell.detailTextLabel?.text = LanguageHelper.instance.selectedLanguage } else { if row == 0 { cell.textLabel?.text = "settings_manage_autocompletion_history".localized } else if row == 1 { cell.textLabel?.text = "settings_manage_brand_autocompletion_history".localized } cell.detailTextLabel?.text = "" } return cell } func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == LANGUAGE_SECTION { return "settings_language".localized } if section == AUTOCOMPLETION_SECTION { return "settings_autocompletion".localized } return nil } 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 prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) { // Get the new view controller using segue.destinationViewController. // Pass the selected object to the new view controller. let selectedIndexPath = settingsTableView.indexPathForSelectedRow! let row = selectedIndexPath.row let section = selectedIndexPath.section if section == LANGUAGE_SECTION { } else if section == AUTOCOMPLETION_SECTION { if let destinationController = segue.destinationViewController as? ManageAutoCompletionHistoryViewController { if row == 0 { destinationController.manageItemNameCompletion = true } else /*if row == 1*/ { destinationController.manageItemNameCompletion = false } } } } @IBAction func unwindToSettings(sender: UIStoryboardSegue) { // this method is called, if a user selects "delete all" in the manage autocompletion history screen let autoCompletionHelper = AutoCompletionHelper.instance //settingsTableView.deselectRowAtIndexPath(settingsTableView.indexPathForSelectedRow()!, animated: true) if let sourceViewController = sender.sourceViewController as? ManageAutoCompletionHistoryViewController { if sourceViewController.manageItemNameCompletion! { autoCompletionHelper.deleteAllAutoCompletionData() } else { autoCompletionHelper.deleteAllAutoCompletionBrandData() } } } }
mit
9d9baa868d9a9dd54d4c5d7af87081d8
34.315789
132
0.624441
5.662447
false
false
false
false
eeschimosu/LicensingViewController
LicensingViewController/LicensingViewController.swift
2
2052
// // LicensingViewController.swift // LicensingViewController // // Created by Tiago Henriques on 07/07/2015. // import UIKit public class LicensingViewController: UITableViewController { // MARK: Constants private let reuseIdentifier = "LicensingItemCell" // MARK: Properties public var items: [LicensingItem] = [] { didSet { tableView.reloadData() } } public var titleFont = UIFont.boldSystemFontOfSize(18) { didSet { tableView.reloadData() } } public var titleColor = UIColor.blackColor() { didSet { tableView.reloadData() } } public var noticeFont = UIFont.systemFontOfSize(13) { didSet { tableView.reloadData() } } public var noticeColor = UIColor.darkGrayColor() { didSet { tableView.reloadData() } } // MARK: Lifecycle override public func viewDidLoad() { tableView.registerClass(LicensingItemCell.self, forCellReuseIdentifier: reuseIdentifier) tableView.estimatedRowHeight = 400 tableView.rowHeight = UITableViewAutomaticDimension tableView.tableFooterView = UIView() } } // MARK: UITableViewDataSource extension LicensingViewController { override public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let item = items[indexPath.row] as LicensingItem let cell = tableView.dequeueReusableCellWithIdentifier(reuseIdentifier) as? LicensingItemCell cell?.titleLabel.text = item.title cell?.titleLabel.font = titleFont cell?.titleLabel.textColor = titleColor cell?.noticeLabel.text = item.notice() cell?.noticeLabel.font = noticeFont cell?.noticeLabel.textColor = noticeColor cell?.userInteractionEnabled = false cell?.layoutIfNeeded() return cell ?? UITableViewCell() } }
mit
d825edd3fe799b99ee27ef10ab52e320
24.333333
125
0.681287
5.302326
false
false
false
false
liyanhuadev/ObjectMapper-Plugin
ObjectMapper-Plugin/RegexSwift/Regex.swift
2
6508
public struct Regex: CustomStringConvertible, CustomDebugStringConvertible { // MARK: Initialisation internal let regularExpression: NSRegularExpression /// Create a `Regex` based on a pattern string. /// /// If `pattern` is not a valid regular expression, an error is thrown /// describing the failure. /// /// - parameters: /// - pattern: A pattern string describing the regex. /// - options: Configure regular expression matching options. /// For details, see `Regex.Options`. /// /// - throws: A value of `ErrorType` describing the invalid regular expression. public init(string pattern: String, options: Options = []) throws { regularExpression = try NSRegularExpression( pattern: pattern, options: options.toNSRegularExpressionOptions()) } /// Create a `Regex` based on a static pattern string. /// /// Unlike `Regex.init(string:)` this initialiser is not failable. If `pattern` /// is an invalid regular expression, it is considered programmer error rather /// than a recoverable runtime error, so this initialiser instead raises a /// precondition failure. /// /// - requires: `pattern` is a valid regular expression. /// /// - parameters: /// - pattern: A pattern string describing the regex. /// - options: Configure regular expression matching options. /// For details, see `Regex.Options`. public init(_ pattern: StaticString, options: Options = []) { do { regularExpression = try NSRegularExpression( pattern: pattern.description, options: options.toNSRegularExpressionOptions()) } catch { preconditionFailure("unexpected error creating regex: \(error)") } } // MARK: Matching /// Returns `true` if the regex matches `string`, otherwise returns `false`. /// /// - parameter string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. /// /// - note: If the match is successful, `Regex.lastMatch` will be set with the /// result of the match. #if swift(>=3.0) public func matches(_ string: String) -> Bool { return _matches(self, string) } #else public func matches(string: String) -> Bool { return _matches(self, string) } #endif private let _matches: (Regex, String) -> Bool = { regex, string in return regex.match(string) != nil } /// If the regex matches `string`, returns a `MatchResult` describing the /// first matched string and any captures. If there are no matches, returns /// `nil`. /// /// - parameter string: The string to match against. /// /// - returns: An optional `MatchResult` describing the first match, or `nil`. /// /// - note: If the match is successful, the result is also stored in `Regex.lastMatch`. #if swift(>=3.0) public func match(_ string: String) -> MatchResult? { let match = regularExpression .firstMatch(in: string, range: string.entireRange) .map { MatchResult(string, $0) } Regex._lastMatch = match return match } #else public func match(string: String) -> MatchResult? { let match = regularExpression .firstMatchInString(string, options: [], range: string.entireRange) .map { MatchResult(string, $0) } Regex._lastMatch = match return match } #endif /// If the regex matches `string`, returns an array of `MatchResult`, describing /// every match inside `string`. If there are no matches, returns an empty /// array. /// /// - parameter string: The string to match against. /// /// - returns: An array of `MatchResult` describing every match in `string`. /// /// - note: If there is at least one match, the first is stored in `Regex.lastMatch`. #if swift(>=3.0) public func allMatches(_ string: String) -> [MatchResult] { let matches = regularExpression .matches(in: string, range: string.entireRange) .map { MatchResult(string, $0) } if let firstMatch = matches.first { Regex._lastMatch = firstMatch } return matches } #else public func allMatches(string: String) -> [MatchResult] { let matches = regularExpression .matchesInString(string, options: [], range: string.entireRange) .map { MatchResult(string, $0) } if let firstMatch = matches.first { Regex._lastMatch = firstMatch } return matches } #endif // MARK: Accessing the last match /// After any match, the result will be stored in this property for later use. /// This is useful when pattern matching: /// /// switch "hello" { /// case Regex("l+"): /// let count = Regex.lastMatch!.matchedString.characters.count /// print("matched \(count) characters") /// default: /// break /// } /// /// This property uses thread-local storage, and thus is thread safe. public static var lastMatch: MatchResult? { return _lastMatch } private static let _lastMatchKey = "me.sharplet.Regex.lastMatch" private static var _lastMatch: MatchResult? { get { return ThreadLocal(_lastMatchKey).value } set { ThreadLocal(_lastMatchKey).value = newValue } } // MARK: Describing public var description: String { return regularExpression.pattern } public var debugDescription: String { return "/\(description)/" } } // MARK: Pattern matching /// Match `regex` on the left with some `string` on the right. Equivalent to /// `regex.matches(string)`, and allows for the use of a `Regex` in pattern /// matching contexts, e.g.: /// /// switch Regex("hello (\\w+)") { /// case "hello world": /// // successful match /// } /// /// - parameters: /// - regex: The regular expression to match against. /// - string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. public func ~= (regex: Regex, string: String) -> Bool { return regex.matches(string) } /// Match `string` on the left with some `regex` on the right. Equivalent to /// `regex.matches(string)`, and allows for the use of a `Regex` in pattern /// matching contexts, e.g.: /// /// switch "hello world" { /// case Regex("hello (\\w+)"): /// // successful match /// } /// /// - parameters: /// - regex: The regular expression to match against. /// - string: The string to test. /// /// - returns: `true` if the regular expression matches, otherwise `false`. public func ~= (string: String, regex: Regex) -> Bool { return regex.matches(string) } import Foundation
mit
6c32ff47a761649ca62afaf1b2b60ef0
31.54
89
0.65335
4.217758
false
false
false
false
phimage/MomXML
Sources/Equatable/MomModel+Equatable.swift
1
653
// // MomModel+Equatable.swift // MomXML // // Created by anass talii on 12/06/2017. // Copyright © 2017 phimage. All rights reserved. // import Foundation extension MomModel: Equatable { public static func == (lhs: MomModel, rhs: MomModel) -> Bool { if lhs.entities.count != rhs.entities.count { return false } if lhs.elements.count != rhs.elements.count { return false } return lhs.entities.sorted { $0.name < $1.name } == rhs.entities.sorted { $0.name < $1.name } && lhs.elements.sorted { $0.name < $1.name } == rhs.elements.sorted { $0.name < $1.name } } }
mit
fe5ccc9a528de6d567a7269864ee554b
27.347826
104
0.58589
3.309645
false
false
false
false
malaonline/iOS
mala-ios/Model/UserMessage/UserExerciseMistake.swift
1
1143
// // UserExerciseMistake.swift // mala-ios // // Created by 王新宇 on 16/05/2017. // Copyright © 2017 Mala Online. All rights reserved. // import UIKit class UserExerciseMistake: NSObject, NSCoding { var total: Int = 0 var english: Int = 0 var math: Int = 0 override init() { super.init() } init(dict: [String: Any]) { super.init() setValuesForKeys(dict) } required public init(coder aDecoder: NSCoder) { self.total = aDecoder.decodeObject(forKey: "total") as? Int ?? 0 self.english = aDecoder.decodeObject(forKey: "english") as? Int ?? 0 self.math = aDecoder.decodeObject(forKey: "math") as? Int ?? 0 } // MARK: - Coding open func encode(with aCoder: NSCoder) { aCoder.encode(total, forKey: "total") aCoder.encode(english, forKey: "english") aCoder.encode(math, forKey: "math") } // MARK: - Description override open var description: String { let keys = ["total", "english", "math"] return "\n"+dictionaryWithValues(forKeys: keys).description+"\n" } }
mit
ac914c8a92e590c83ad86b4a755162bc
24.244444
76
0.59243
3.90378
false
false
false
false
wordpress-mobile/WordPress-Aztec-iOS
WordPressEditor/WordPressEditor/Classes/Plugins/WordPressPlugin/Gutenberg/GutenblockConverter.swift
2
1205
import Aztec import Foundation public extension Element { static let gutenblock = Element("gutenblock") } class GutenblockConverter: ElementConverter { // MARK: - ElementConverter func convert( _ element: ElementNode, inheriting attributes: [NSAttributedString.Key: Any], contentSerializer serialize: ContentSerializer) -> NSAttributedString { precondition(element.type == .gutenblock) let attributes = self.attributes(for: element, inheriting: attributes) return serialize(element, nil, attributes, false) } private func attributes(for element: ElementNode, inheriting attributes: [NSAttributedString.Key: Any]) -> [NSAttributedString.Key: Any] { let elementRepresentation = HTMLElementRepresentation(element) let representation = HTMLRepresentation(for: .element(elementRepresentation)) let paragraphStyle = attributes.paragraphStyle() paragraphStyle.appendProperty(Gutenblock(storing: representation)) var finalAttributes = attributes finalAttributes[.paragraphStyle] = paragraphStyle return finalAttributes } }
gpl-2.0
eb0963b9eff3c42879d0d7a6b46fcc37
33.428571
142
0.691286
5.502283
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Helpers/String+Fingerprint.swift
1
1610
// // Wire // Copyright (C) 2020 Wire Swiss GmbH // // 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 UIKit extension String { func split(every: Int) -> [String] { return stride(from: 0, to: count, by: every).map { i in let start = index(startIndex, offsetBy: i) let end = index(start, offsetBy: every, limitedBy: endIndex) ?? endIndex return String(self[start..<end]) } } var fingerprintStringWithSpaces: String { return split(every: 2).joined(separator: " ") } func fingerprintString(attributes: [NSAttributedString.Key: Any], boldAttributes: [NSAttributedString.Key: Any]) -> NSAttributedString { var bold = true return split { !$0.isHexDigit }.map { let attributedElement = String($0) && (bold ? boldAttributes : attributes) bold = !bold return attributedElement }.joined(separator: NSAttributedString(string: " ")) } }
gpl-3.0
929e4c0d946e05d398d20d67b2a12110
33.255319
97
0.654037
4.386921
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/ContactsUI/ContactsViewController+Constraints.swift
1
4788
// // Wire // Copyright (C) 2019 Wire Swiss GmbH // // 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 UIKit extension ContactsViewController { func setupLayout() { [searchHeaderViewController.view, separatorView, tableView, emptyResultsLabel, inviteOthersButton, noContactsLabel, bottomContainerSeparatorView, bottomContainerView].prepareForLayout() let standardOffset: CGFloat = 24.0 var constraints: [NSLayoutConstraint] = [] constraints += [ searchHeaderViewController.view.leadingAnchor.constraint(equalTo: view.leadingAnchor), searchHeaderViewController.view.trailingAnchor.constraint(equalTo: view.trailingAnchor), searchHeaderViewController.view.topAnchor.constraint(equalTo: view.topAnchor), searchHeaderViewController.view.bottomAnchor.constraint(equalTo: separatorView.topAnchor) ] constraints += [ separatorView.leadingAnchor.constraint(equalTo: separatorView.superview!.leadingAnchor, constant: standardOffset), separatorView.trailingAnchor.constraint(equalTo: separatorView.superview!.trailingAnchor, constant: -standardOffset), separatorView.heightAnchor.constraint(equalToConstant: 0.5), separatorView.bottomAnchor.constraint(equalTo: tableView.topAnchor), tableView.leadingAnchor.constraint(equalTo: tableView.superview!.leadingAnchor), tableView.trailingAnchor.constraint(equalTo: tableView.superview!.trailingAnchor), tableView.bottomAnchor.constraint(equalTo: bottomContainerView.topAnchor) ] constraints += [ emptyResultsLabel.centerXAnchor.constraint(equalTo: tableView.centerXAnchor), emptyResultsLabel.centerYAnchor.constraint(equalTo: tableView.centerYAnchor) ] constraints += [ noContactsLabel.topAnchor.constraint(equalTo: searchHeaderViewController.view.bottomAnchor, constant: standardOffset), noContactsLabel.leadingAnchor.constraint(equalTo: view.leadingAnchor, constant: standardOffset), noContactsLabel.trailingAnchor.constraint(equalTo: noContactsLabel.superview!.trailingAnchor) ] let bottomContainerBottomConstraint = bottomContainerView.bottomAnchor.constraint(equalTo: bottomContainerView.superview!.bottomAnchor) self.bottomContainerBottomConstraint = bottomContainerBottomConstraint constraints += [ bottomContainerBottomConstraint, bottomContainerView.leadingAnchor.constraint(equalTo: bottomContainerView.superview!.leadingAnchor), bottomContainerView.trailingAnchor.constraint(equalTo: bottomContainerView.superview!.trailingAnchor), bottomContainerSeparatorView.topAnchor.constraint(equalTo: bottomContainerSeparatorView.superview!.topAnchor), bottomContainerSeparatorView.leadingAnchor.constraint(equalTo: bottomContainerSeparatorView.superview!.leadingAnchor), bottomContainerSeparatorView.trailingAnchor.constraint(equalTo: bottomContainerSeparatorView.superview!.trailingAnchor), bottomContainerSeparatorView.heightAnchor.constraint(equalToConstant: 0.5) ] let bottomEdgeConstraint = inviteOthersButton.bottomAnchor.constraint(equalTo: inviteOthersButton.superview!.bottomAnchor, constant: -(standardOffset / 2.0 + UIScreen.safeArea.bottom)) self.bottomEdgeConstraint = bottomEdgeConstraint constraints += [ bottomEdgeConstraint, inviteOthersButton.topAnchor.constraint(equalTo: inviteOthersButton.superview!.topAnchor, constant: standardOffset / CGFloat(2)), inviteOthersButton.leadingAnchor.constraint(equalTo: inviteOthersButton.superview!.leadingAnchor, constant: standardOffset), inviteOthersButton.trailingAnchor.constraint(equalTo: inviteOthersButton.superview!.trailingAnchor, constant: -standardOffset) ] constraints += [inviteOthersButton.heightAnchor.constraint(equalToConstant: 56)] NSLayoutConstraint.activate(constraints) } }
gpl-3.0
48d43b0c3d972220fd7a9e0174182261
48.875
192
0.743734
5.747899
false
false
false
false
wireapp/wire-ios
Wire-iOS/Sources/UserInterface/Conversation/InputBar/ConversationInputBarViewController.swift
1
37293
// Wire // Copyright (C) 2020 Wire Swiss GmbH // // 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 MobileCoreServices import Photos import UIKit import WireSyncEngine import avs import AVFoundation enum ConversationInputBarViewControllerMode { case textInput case audioRecord case camera case timeoutConfguration } final class ConversationInputBarViewController: UIViewController, UIPopoverPresentationControllerDelegate, PopoverPresenter { let mediaShareRestrictionManager = MediaShareRestrictionManager(sessionRestriction: ZMUserSession.shared()) // MARK: PopoverPresenter var presentedPopover: UIPopoverPresentationController? var popoverPointToView: UIView? typealias ButtonColors = SemanticColors.Button let conversation: InputBarConversationType weak var delegate: ConversationInputBarViewControllerDelegate? private let classificationProvider: ClassificationProviding? private(set) var inputController: UIViewController? { willSet { inputController?.view.removeFromSuperview() } didSet { deallocateUnusedInputControllers() defer { inputBar.textView.reloadInputViews() } guard let inputController = inputController else { inputBar.textView.inputView = nil return } let inputViewSize = UIView.lastKeyboardSize let inputViewFrame: CGRect = CGRect(origin: .zero, size: inputViewSize) let inputView = UIInputView(frame: inputViewFrame, inputViewStyle: .keyboard) inputView.allowsSelfSizing = true inputView.autoresizingMask = .flexibleWidth inputController.view.frame = inputView.frame inputController.view.autoresizingMask = .flexibleWidth if let view = inputController.view { inputView.addSubview(view) } inputBar.textView.inputView = inputView } } var mentionsHandler: MentionsHandler? weak var mentionsView: (Dismissable & UserList & KeyboardCollapseObserver)? var textfieldObserverToken: Any? lazy var audioSession: AVAudioSessionType = AVAudioSession.sharedInstance() // MARK: buttons let photoButton: IconButton = { let button = IconButton() button.setIconColor(UIColor.accent(), for: UIControl.State.selected) return button }() lazy var ephemeralIndicatorButton: IconButton = { let button = IconButton(fontSpec: .smallSemiboldFont) button.layer.borderWidth = 0.5 button.accessibilityIdentifier = "ephemeralTimeIndicatorButton" button.adjustsTitleWhenHighlighted = true button.adjustsBorderColorWhenHighlighted = true button.setTitleColor(UIColor.lightGraphite, for: .disabled) button.setTitleColor(UIColor.accent(), for: .normal) configureEphemeralKeyboardButton(button) return button }() lazy var hourglassButton: IconButton = { let button = IconButton(style: .default) button.setIcon(.hourglass, size: .tiny, for: UIControl.State.normal) button.accessibilityIdentifier = "ephemeralTimeSelectionButton" configureEphemeralKeyboardButton(button) return button }() let markdownButton: IconButton = { let button = IconButton() button.layer.borderWidth = 1 button.layer.cornerRadius = 12 button.layer.masksToBounds = true button.contentEdgeInsets = UIEdgeInsets(top: 8, left: 12, bottom: 8, right: 12) return button }() let mentionButton: IconButton = IconButton() lazy var audioButton: IconButton = { let button = IconButton() button.setIconColor(UIColor.accent(), for: .selected) let longPressRecognizer = UILongPressGestureRecognizer(target: self, action: #selector(audioButtonLongPressed(_:))) longPressRecognizer.minimumPressDuration = 0.3 button.addGestureRecognizer(longPressRecognizer) let tapGestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(audioButtonPressed(_:))) tapGestureRecognizer.require(toFail: longPressRecognizer) button.addGestureRecognizer(tapGestureRecognizer) return button }() let uploadFileButton: IconButton = IconButton() let sketchButton: IconButton = IconButton() let pingButton: IconButton = IconButton() let locationButton: IconButton = IconButton() let gifButton: IconButton = IconButton() let sendButton: IconButton = { let button = IconButton.sendButton() button.hitAreaPadding = CGSize(width: 30, height: 30) return button }() let videoButton: IconButton = IconButton() // MARK: subviews lazy var inputBar: InputBar = { let inputBar = InputBar(buttons: inputBarButtons) if !mediaShareRestrictionManager.canUseSpellChecking { inputBar.textView.spellCheckingType = .no } if !mediaShareRestrictionManager.canUseAutoCorrect { inputBar.textView.autocorrectionType = .no } return inputBar }() lazy var typingIndicatorView: TypingIndicatorView = { let view = TypingIndicatorView() view.accessibilityIdentifier = "typingIndicator" view.typingUsers = conversation.typingUsers view.setHidden(true, animated: false) return view }() private let securityLevelView = SecurityLevelView() // MARK: custom keyboards var audioRecordViewController: AudioRecordViewController? var audioRecordViewContainer: UIView? var audioRecordKeyboardViewController: AudioRecordKeyboardViewController? var cameraKeyboardViewController: CameraKeyboardViewController? var ephemeralKeyboardViewController: EphemeralKeyboardViewController? // MARK: text input lazy var sendController: ConversationInputBarSendController = { return ConversationInputBarSendController(conversation: conversation) }() var editingMessage: ZMConversationMessage? var quotedMessage: ZMConversationMessage? var replyComposingView: ReplyComposingView? // MARK: feedback lazy var impactFeedbackGenerator: UIImpactFeedbackGenerator = UIImpactFeedbackGenerator(style: .light) private lazy var notificationFeedbackGenerator: UINotificationFeedbackGenerator = UINotificationFeedbackGenerator() var shouldRefocusKeyboardAfterImagePickerDismiss = false // Counter keeping track of calls being made when the audio keyboard ewas visible before. var callCountWhileCameraKeyboardWasVisible = 0 var callStateObserverToken: Any? var wasRecordingBeforeCall = false let sendButtonState: ConversationInputBarButtonState = ConversationInputBarButtonState() var inRotation = false private var singleTapGestureRecognizer: UITapGestureRecognizer = UITapGestureRecognizer() private var conversationObserverToken: Any? private var userObserverToken: Any? private var typingObserverToken: Any? private var inputBarButtons: [IconButton] { var buttonsArray: [IconButton] = [] switch mediaShareRestrictionManager.level { case .none: buttonsArray = [ mentionButton, photoButton, sketchButton, gifButton, audioButton, pingButton, uploadFileButton, locationButton, videoButton ] case .securityFlag: buttonsArray = [ photoButton, mentionButton, sketchButton, audioButton, pingButton, locationButton, videoButton ] case .APIFlag: buttonsArray = [ mentionButton, pingButton, locationButton ] } if !conversation.isSelfDeletingMessageSendingDisabled { buttonsArray.insert(hourglassButton, at: buttonsArray.startIndex) } return buttonsArray } var mode: ConversationInputBarViewControllerMode = .textInput { didSet { guard oldValue != mode else { return } let singleTapGestureRecognizerEnabled: Bool let selectedButton: IconButton? func config(viewController: UIViewController?, setupClosure: () -> UIViewController) { if inputController == nil || inputController != viewController { let newViewController: UIViewController if let viewController = viewController { newViewController = viewController } else { newViewController = setupClosure() } inputController = newViewController } } switch mode { case .textInput: inputController = nil singleTapGestureRecognizerEnabled = false selectedButton = nil case .audioRecord: clearTextInputAssistentItemIfNeeded() config(viewController: audioRecordKeyboardViewController) { let audioRecordKeyboardViewController = AudioRecordKeyboardViewController() audioRecordKeyboardViewController.delegate = self self.audioRecordKeyboardViewController = audioRecordKeyboardViewController return audioRecordKeyboardViewController } singleTapGestureRecognizerEnabled = true selectedButton = audioButton case .camera: clearTextInputAssistentItemIfNeeded() config(viewController: cameraKeyboardViewController) { return self.createCameraKeyboardViewController() } singleTapGestureRecognizerEnabled = true selectedButton = photoButton case .timeoutConfguration: clearTextInputAssistentItemIfNeeded() config(viewController: ephemeralKeyboardViewController) { return self.createEphemeralKeyboardViewController() } singleTapGestureRecognizerEnabled = true selectedButton = hourglassButton } singleTapGestureRecognizer.isEnabled = singleTapGestureRecognizerEnabled selectInputControllerButton(selectedButton) updateRightAccessoryView() } } // MARK: - Input views handling /// init with a InputBarConversationType object /// - Parameter conversation: provide nil only for tests init( conversation: InputBarConversationType, classificationProvider: ClassificationProviding? = ZMUserSession.shared() ) { self.conversation = conversation self.classificationProvider = classificationProvider super.init(nibName: nil, bundle: nil) if !ProcessInfo.processInfo.isRunningTests, let conversation = conversation as? ZMConversation { conversationObserverToken = ConversationChangeInfo.add(observer: self, for: conversation) typingObserverToken = conversation.addTypingObserver(self) } setupNotificationCenter() setupInputLanguageObserver() setupViews() } @available(*, unavailable) required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } // MARK: - view life cycle override func viewDidLoad() { super.viewDidLoad() setupCallStateObserver() setupSingleTapGestureRecognizer() if conversation.hasDraftMessage, let draftMessage = conversation.draftMessage { inputBar.textView.setDraftMessage(draftMessage) } configureMarkdownButton() configureMentionButton() sendButton.addTarget(self, action: #selector(sendButtonPressed(_:)), for: .touchUpInside) photoButton.addTarget(self, action: #selector(cameraButtonPressed(_:)), for: .touchUpInside) videoButton.addTarget(self, action: #selector(videoButtonPressed(_:)), for: .touchUpInside) sketchButton.addTarget(self, action: #selector(sketchButtonPressed(_:)), for: .touchUpInside) uploadFileButton.addTarget(self, action: #selector(docUploadPressed(_:)), for: .touchUpInside) pingButton.addTarget(self, action: #selector(pingButtonPressed(_:)), for: .touchUpInside) gifButton.addTarget(self, action: #selector(giphyButtonPressed(_:)), for: .touchUpInside) locationButton.addTarget(self, action: #selector(locationButtonPressed(_:)), for: .touchUpInside) updateAccessoryViews() updateInputBarVisibility() updateTypingIndicator() updateWritingState(animated: false) updateButtonIcons() updateAvailabilityPlaceholder() updateClassificationBanner() setInputLanguage() setupStyle() let interaction = UIDropInteraction(delegate: self) inputBar.textView.addInteraction(interaction) setupObservers() } private func setupObservers() { guard !ProcessInfo.processInfo.isRunningTests else { return } if conversationObserverToken == nil, let conversation = conversation as? ZMConversation { conversationObserverToken = ConversationChangeInfo.add(observer: self, for: conversation) } if let connectedUser = conversation.connectedUserType as? ZMUser, let userSession = ZMUserSession.shared() { userObserverToken = UserChangeInfo.add(observer: self, for: connectedUser, in: userSession) } NotificationCenter.default.addObserver(forName: .featureDidChangeNotification, object: nil, queue: .main) { [weak self] note in guard let change = note.object as? FeatureService.FeatureChange else { return } switch change { case .fileSharingEnabled, .fileSharingDisabled: self?.updateInputBarButtons() default: break } } } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) updateRightAccessoryView() inputBar.updateReturnKey() inputBar.updateEphemeralState() updateMentionList() } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) inputBar.textView.endEditing(true) } override func viewDidDisappear(_ animated: Bool) { super.viewDidDisappear(animated) endEditingMessageIfNeeded() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() ephemeralIndicatorButton.layer.cornerRadius = ephemeralIndicatorButton.bounds.width / 2 } override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator?) { guard let coordinator = coordinator else { return } super.viewWillTransition(to: size, with: coordinator) self.inRotation = true coordinator.animate(alongsideTransition: nil) { _ in self.inRotation = false self.updatePopoverSourceRect() } } override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) { super.traitCollectionDidChange(previousTraitCollection) guard traitCollection.horizontalSizeClass != previousTraitCollection?.horizontalSizeClass else { return } guard !inRotation else { return } updatePopoverSourceRect() } // MARK: - setup private func setupStyle() { ephemeralIndicatorButton.borderWidth = 0 hourglassButton.layer.borderWidth = 1 hourglassButton.setIconColor(SemanticColors.Button.textInputBarItemEnabled, for: .normal) hourglassButton.setBackgroundImageColor(SemanticColors.Button.backgroundInputBarItemEnabled, for: .normal) hourglassButton.setBorderColor(SemanticColors.Button.borderInputBarItemEnabled, for: .normal) } private func setupSingleTapGestureRecognizer() { singleTapGestureRecognizer.addTarget(self, action: #selector(onSingleTap(_:))) singleTapGestureRecognizer.isEnabled = false singleTapGestureRecognizer.delegate = self singleTapGestureRecognizer.cancelsTouchesInView = true view.addGestureRecognizer(singleTapGestureRecognizer) } func updateRightAccessoryView() { updateEphemeralIndicatorButtonTitle(ephemeralIndicatorButton) let trimmed = inputBar.textView.text.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) sendButtonState.update(textLength: trimmed.count, editing: nil != editingMessage, markingDown: inputBar.isMarkingDown, destructionTimeout: conversation.activeMessageDestructionTimeoutValue, mode: mode, syncedMessageDestructionTimeout: conversation.hasSyncedMessageDestructionTimeout, isEphemeralSendingDisabled: conversation.isSelfDeletingMessageSendingDisabled, isEphemeralTimeoutForced: conversation.isSelfDeletingMessageTimeoutForced) sendButton.isEnabled = sendButtonState.sendButtonEnabled ephemeralIndicatorButton.isHidden = sendButtonState.ephemeralIndicatorButtonHidden ephemeralIndicatorButton.isEnabled = sendButtonState.ephemeralIndicatorButtonEnabled ephemeralIndicatorButton.setBackgroundImage(conversation.timeoutImage, for: .normal) ephemeralIndicatorButton.setBackgroundImage(conversation.disabledTimeoutImage, for: .disabled) } func updateMentionList() { triggerMentionsIfNeeded(from: inputBar.textView) } func clearInputBar() { inputBar.textView.text = "" inputBar.markdownView.resetIcons() inputBar.textView.resetMarkdown() updateRightAccessoryView() conversation.setIsTyping(false) replyComposingView?.removeFromSuperview() replyComposingView = nil quotedMessage = nil } func updateNewButtonTitleLabel() { photoButton.titleLabel?.isHidden = inputBar.textView.isFirstResponder } func updateAccessoryViews() { updateRightAccessoryView() } func updateAvailabilityPlaceholder() { guard ZMUser.selfUser().hasTeam, conversation.conversationType == .oneOnOne, let connectedUser = conversation.connectedUserType else { return } inputBar.availabilityPlaceholder = AvailabilityStringBuilder.string(for: connectedUser, with: .placeholder, color: inputBar.placeholderColor) } func updateInputBarVisibility() { view.isHidden = conversation.isReadOnly } @objc func updateInputBarButtons() { inputBar.buttonsView.buttons = inputBarButtons inputBarButtons.forEach { $0.setIconColor(SemanticColors.Icon.foregroundDefaultBlack, for: .normal) } inputBar.buttonsView.setNeedsLayout() } // MARK: - Security Banner private func updateClassificationBanner() { securityLevelView.configure(with: conversation.participants, provider: classificationProvider) } // MARK: - Save draft message func draftMessage(from textView: MarkdownTextView) -> DraftMessage { let (text, mentions) = textView.preparedText return DraftMessage(text: text, mentions: mentions, quote: quotedMessage as? ZMMessage) } private func didEnterBackground() { if !inputBar.textView.text.isEmpty { conversation.setIsTyping(false) } let draft = draftMessage(from: inputBar.textView) delegate?.conversationInputBarViewControllerDidComposeDraft(message: draft) } private func updateButtonIcons() { audioButton.setIcon(.microphone, size: .tiny, for: .normal) videoButton.setIcon(.videoMessage, size: .tiny, for: .normal) photoButton.setIcon(.cameraLens, size: .tiny, for: .normal) uploadFileButton.setIcon(.paperclip, size: .tiny, for: .normal) sketchButton.setIcon(.brush, size: .tiny, for: .normal) pingButton.setIcon(.ping, size: .tiny, for: .normal) locationButton.setIcon(.locationPin, size: .tiny, for: .normal) gifButton.setIcon(.gif, size: .tiny, for: .normal) mentionButton.setIcon(.mention, size: .tiny, for: .normal) sendButton.setIcon(.send, size: .tiny, for: .normal) sendButton.setIcon(.send, size: .tiny, for: .disabled) } func selectInputControllerButton(_ button: IconButton?) { for otherButton in [photoButton, audioButton, hourglassButton] { otherButton.isSelected = button == otherButton } } func clearTextInputAssistentItemIfNeeded() { let item = inputBar.textView.inputAssistantItem item.leadingBarButtonGroups = [] item.trailingBarButtonGroups = [] } func postImage(_ image: MediaAsset) { guard let data = image.imageData else { return } sendController.sendMessage(withImageData: data) } func deallocateUnusedInputControllers() { if cameraKeyboardViewController != inputController { cameraKeyboardViewController = nil } if audioRecordKeyboardViewController != inputController { audioRecordKeyboardViewController = nil } if ephemeralKeyboardViewController != inputController { ephemeralKeyboardViewController = nil } } // MARK: - PingButton @objc private func pingButtonPressed(_ button: UIButton?) { appendKnock() } private func appendKnock() { guard let conversation = conversation as? ZMConversation else { return } notificationFeedbackGenerator.prepare() ZMUserSession.shared()?.enqueue({ do { try conversation.appendKnock() Analytics.shared.tagMediaActionCompleted(.ping, inConversation: conversation) AVSMediaManager.sharedInstance().playKnockSound() self.notificationFeedbackGenerator.notificationOccurred(.success) } catch { Logging.messageProcessing.warn("Failed to append knock. Reason: \(error.localizedDescription)") } }) pingButton.isEnabled = false delay(0.5) { self.pingButton.isEnabled = true } } // MARK: - SendButton @objc func sendButtonPressed(_ sender: Any?) { inputBar.textView.autocorrectLastWord() sendText() } // MARK: - Giphy @objc private func giphyButtonPressed(_ sender: Any?) { guard !AppDelegate.isOffline, let conversation = conversation as? ZMConversation else { return } let giphySearchViewController = GiphySearchViewController(searchTerm: "", conversation: conversation) giphySearchViewController.delegate = self ZClientViewController.shared?.present(giphySearchViewController.wrapInsideNavigationController(), animated: true) } // MARK: - Animations func bounceCameraIcon() { let scaleTransform = CGAffineTransform(scaleX: 1.3, y: 1.3) let scaleUp = { self.photoButton.transform = scaleTransform } let scaleDown = { self.photoButton.transform = CGAffineTransform.identity } UIView.animate(withDuration: 0.1, delay: 0, options: .curveEaseIn, animations: scaleUp) { _ in UIView.animate(withDuration: 0.3, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 0.6, options: .curveEaseOut, animations: scaleDown) } } // MARK: - Haptic Feedback func playInputHapticFeedback() { impactFeedbackGenerator.prepare() impactFeedbackGenerator.impactOccurred() } // MARK: - Input views handling @objc func onSingleTap(_ recognier: UITapGestureRecognizer?) { if recognier?.state == .recognized { mode = .textInput } } // MARK: - notification center private func setupNotificationCenter() { NotificationCenter.default.addObserver(forName: UIResponder.keyboardDidHideNotification, object: nil, queue: .main) { [weak self] _ in guard let weakSelf = self else { return } let inRotation = weakSelf.inRotation let isRecording = weakSelf.audioRecordKeyboardViewController?.isRecording ?? false if !inRotation && !isRecording { weakSelf.mode = .textInput } } NotificationCenter.default.addObserver(forName: UIApplication.didEnterBackgroundNotification, object: nil, queue: .main) { [weak self] _ in self?.didEnterBackground() } NotificationCenter.default.addObserver(forName: .featureDidChangeNotification, object: nil, queue: .main) { [weak self] _ in self?.updateViewsForSelfDeletingMessageChanges() } } // MARK: - Keyboard Shortcuts override var canBecomeFirstResponder: Bool { return true } } // MARK: - GiphySearchViewControllerDelegate extension ConversationInputBarViewController: GiphySearchViewControllerDelegate { func giphySearchViewController(_ giphySearchViewController: GiphySearchViewController, didSelectImageData imageData: Data, searchTerm: String) { clearInputBar() dismiss(animated: true) { let messageText: String if searchTerm == "" { messageText = String(format: "giphy.conversation.random_message".localized, searchTerm) } else { messageText = String(format: "giphy.conversation.message".localized, searchTerm) } self.sendController.sendTextMessage(messageText, mentions: [], withImageData: imageData) } } } // MARK: - UIImagePickerControllerDelegate extension ConversationInputBarViewController: UIImagePickerControllerDelegate { /// TODO: check this is still necessary on iOS 13? private func statusBarBlinksRedFix() { // Workaround http://stackoverflow.com/questions/26651355/ do { try AVAudioSession.sharedInstance().setActive(false) } catch { } } func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) { statusBarBlinksRedFix() let mediaType = info[UIImagePickerController.InfoKey.mediaType] as? String if mediaType == kUTTypeMovie as String { processVideo(info: info, picker: picker) } else if mediaType == kUTTypeImage as String { let image: UIImage? = (info[UIImagePickerController.InfoKey.editedImage] as? UIImage) ?? info[UIImagePickerController.InfoKey.originalImage] as? UIImage if let image = image, let jpegData = image.jpegData(compressionQuality: 0.9) { if picker.sourceType == UIImagePickerController.SourceType.camera { if mediaShareRestrictionManager.hasAccessToCameraRoll { UIImageWriteToSavedPhotosAlbum(image, self, #selector(image(_:didFinishSavingWithError:contextInfo:)), nil) } // In case of picking from the camera, the iOS controller is showing it's own confirmation screen. parent?.dismiss(animated: true) { self.sendController.sendMessage(withImageData: jpegData, completion: nil) } } else { parent?.dismiss(animated: true) { self.showConfirmationForImage(jpegData, isFromCamera: false, uti: mediaType) } } } } else { parent?.dismiss(animated: true) } } func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { statusBarBlinksRedFix() parent?.dismiss(animated: true) { if self.shouldRefocusKeyboardAfterImagePickerDismiss { self.shouldRefocusKeyboardAfterImagePickerDismiss = false self.mode = .camera self.inputBar.textView.becomeFirstResponder() } } } // MARK: - Sketch @objc func sketchButtonPressed(_ sender: Any?) { inputBar.textView.resignFirstResponder() let viewController = CanvasViewController() viewController.delegate = self viewController.navigationItem.setupNavigationBarTitle(title: conversation.displayName.capitalized) parent?.present(viewController.wrapInNavigationController(setBackgroundColor: true), animated: true) } } // MARK: - Informal TextView delegate methods extension ConversationInputBarViewController: InformalTextViewDelegate { func textView(_ textView: UITextView, hasImageToPaste image: MediaAsset) { let context = ConfirmAssetViewController.Context(asset: .image(mediaAsset: image), onConfirm: {[weak self] editedImage in self?.dismiss(animated: false) self?.postImage(editedImage ?? image) }, onCancel: { [weak self] in self?.dismiss(animated: false) } ) let confirmImageViewController = ConfirmAssetViewController(context: context) confirmImageViewController.previewTitle = conversation.displayName.uppercasedWithCurrentLocale present(confirmImageViewController, animated: false) } func textView(_ textView: UITextView, firstResponderChanged resigned: Bool) { updateAccessoryViews() updateNewButtonTitleLabel() } } // MARK: - ZMConversationObserver extension ConversationInputBarViewController: ZMConversationObserver { func conversationDidChange(_ change: ConversationChangeInfo) { if change.participantsChanged || change.connectionStateChanged || change.allowGuestsChanged { // Sometime participantsChanged is not observed after allowGuestsChanged updateInputBarVisibility() updateClassificationBanner() } if change.destructionTimeoutChanged { updateViewsForSelfDeletingMessageChanges() } } } // MARK: - ZMUserObserver extension ConversationInputBarViewController: ZMUserObserver { func userDidChange(_ changeInfo: UserChangeInfo) { if changeInfo.availabilityChanged { updateAvailabilityPlaceholder() } } } // MARK: - UIGestureRecognizerDelegate extension ConversationInputBarViewController: UIGestureRecognizerDelegate { func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool { return singleTapGestureRecognizer == gestureRecognizer || singleTapGestureRecognizer == otherGestureRecognizer } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldReceive touch: UITouch) -> Bool { if singleTapGestureRecognizer == gestureRecognizer { return true } return gestureRecognizer.view?.bounds.contains(touch.location(in: gestureRecognizer.view)) ?? false } func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRequireFailureOf otherGestureRecognizer: UIGestureRecognizer) -> Bool { return otherGestureRecognizer is UIPanGestureRecognizer } // MARK: setup views private func setupViews() { updateEphemeralIndicatorButtonTitle(ephemeralIndicatorButton) setupInputBar() inputBar.rightAccessoryStackView.addArrangedSubview(sendButton) inputBar.leftAccessoryView.addSubview(markdownButton) inputBar.rightAccessoryStackView.insertArrangedSubview(ephemeralIndicatorButton, at: 0) inputBar.addSubview(typingIndicatorView) view.addSubview(securityLevelView) createConstraints() } private func setupInputBar() { audioButton.accessibilityIdentifier = "audioButton" videoButton.accessibilityIdentifier = "videoButton" photoButton.accessibilityIdentifier = "photoButton" uploadFileButton.accessibilityIdentifier = "uploadFileButton" sketchButton.accessibilityIdentifier = "sketchButton" pingButton.accessibilityIdentifier = "pingButton" locationButton.accessibilityIdentifier = "locationButton" gifButton.accessibilityIdentifier = "gifButton" mentionButton.accessibilityIdentifier = "mentionButton" markdownButton.accessibilityIdentifier = "markdownButton" inputBarButtons.forEach { $0.hitAreaPadding = .zero } inputBar.textView.delegate = self inputBar.textView.informalTextViewDelegate = self registerForTextFieldSelectionChange() view.addSubview(inputBar) inputBar.editingView.delegate = self } private func createConstraints() { [securityLevelView, inputBar, markdownButton, typingIndicatorView].prepareForLayout() let bottomConstraint = inputBar.bottomAnchor.constraint(equalTo: inputBar.superview!.bottomAnchor) bottomConstraint.priority = .defaultLow let securityBannerHeight: CGFloat = securityLevelView.isHidden ? 0 : 24 let widthOfSendButton: CGFloat = 42 let heightOfSendButton: CGFloat = 32 NSLayoutConstraint.activate([ securityLevelView.topAnchor.constraint(equalTo: view.topAnchor), securityLevelView.leadingAnchor.constraint(equalTo: view.leadingAnchor), securityLevelView.trailingAnchor.constraint(equalTo: view.trailingAnchor), securityLevelView.heightAnchor.constraint(equalToConstant: securityBannerHeight), inputBar.topAnchor.constraint(equalTo: securityLevelView.bottomAnchor), inputBar.leadingAnchor.constraint(equalTo: inputBar.superview!.leadingAnchor), inputBar.trailingAnchor.constraint(equalTo: inputBar.superview!.trailingAnchor), bottomConstraint, sendButton.widthAnchor.constraint(equalToConstant: InputBar.rightIconSize), sendButton.heightAnchor.constraint(equalToConstant: InputBar.rightIconSize), ephemeralIndicatorButton.widthAnchor.constraint(equalToConstant: InputBar.rightIconSize), ephemeralIndicatorButton.heightAnchor.constraint(equalToConstant: InputBar.rightIconSize), markdownButton.centerXAnchor.constraint(equalTo: markdownButton.superview!.centerXAnchor), markdownButton.bottomAnchor.constraint(equalTo: markdownButton.superview!.bottomAnchor, constant: -14), markdownButton.widthAnchor.constraint(equalToConstant: widthOfSendButton), markdownButton.heightAnchor.constraint(equalToConstant: heightOfSendButton), typingIndicatorView.centerYAnchor.constraint(equalTo: inputBar.topAnchor), typingIndicatorView.centerXAnchor.constraint(equalTo: typingIndicatorView.superview!.centerXAnchor), typingIndicatorView.leftAnchor.constraint(greaterThanOrEqualTo: typingIndicatorView.superview!.leftAnchor, constant: 48), typingIndicatorView.rightAnchor.constraint(lessThanOrEqualTo: typingIndicatorView.superview!.rightAnchor, constant: 48) ]) } }
gpl-3.0
17112d3115d8f42ca8275f0b84adab78
36.822515
164
0.662859
5.912954
false
false
false
false
Holmusk/HMRequestFramework-iOS
HMRequestFrameworkTests/database/CoreDataTextSearchTest.swift
1
2894
// // CoreDataTextSearchTest.swift // HMRequestFrameworkTests // // Created by Hai Pham on 25/10/17. // Copyright © 2017 Holmusk. All rights reserved. // import RxSwift import SwiftFP import XCTest @testable import HMRequestFramework public final class CoreDataTextSearchTest: CoreDataRootTest { public func test_textSearchRequest_shouldBeCreatedCorrectly() { /// Setup let rq1 = HMCDTextSearchRequest.builder() .with(key: "Key1") .with(value: "Value1") .with(comparison: .contains) .add(modifier: .caseInsensitive) .add(modifier: .diacriticInsensitive) .build() /// When let predicate = try! rq1.textSearchPredicate() /// Then XCTAssertEqual(predicate.predicateFormat, "Key1 CONTAINS[cd] \"Value1\"") } public func test_fetchWithTextSearch_shouldWork( _ comparison: HMCDTextSearchRequest.Comparison, _ modifyText: (String, String) -> String, _ validate: (String, [Dummy1]) -> Void) { /// Setup let observer = scheduler.createObserver(Dummy1.self) let expect = expectation(description: "Should have completed") let dbProcessor = self.dbProcessor! let dummyCount = self.dummyCount! let additional = "viethai.pham" let requests: [HMCDTextSearchRequest] = [ HMCDTextSearchRequest.builder() .with(key: "id") .with(value: additional) .with(comparison: comparison) .with(modifiers: [.caseInsensitive, .diacriticInsensitive]) .build(), ] let dummies = (0..<dummyCount).map({_ -> Dummy1 in let dummy = Dummy1() if Bool.random() { let oldId = dummy.id! let newId = modifyText(oldId, additional) return dummy.cloneBuilder().with(id: newId).build() } else { return dummy } }) let qos: DispatchQoS.QoSClass = .background _ = try! dbProcessor .saveToMemory(Try.success(dummies), qos) .toBlocking() .first() /// When dbProcessor .fetchWithTextSearch(Try.success(()), Dummy1.self, requests, .and, qos) .map({try $0.getOrThrow()}) .flattenSequence() .doOnDispose(expect.fulfill) .subscribe(observer) .disposed(by: disposeBag) waitForExpectations(timeout: timeout, handler: nil) /// Then let nextElements = observer.nextElements() XCTAssertTrue(!nextElements.isEmpty) validate(additional, nextElements) print(nextElements.flatMap({$0.id})) } public func test_fetchWithContains_shouldWork() { test_fetchWithTextSearch_shouldWork( .contains, {"\($0)\($1)"}, {(text, dummies) in XCTAssertTrue(dummies.all({$0.id!.contains(text)}))}) } public func test_fetchWithBeginsWith_shouldWork() { test_fetchWithTextSearch_shouldWork( .contains, {"\($1)\($0)"}, {(text, dummies) in XCTAssertTrue(dummies.all({$0.id!.starts(with: text)}))}) } }
apache-2.0
2f85e5ccce1854e48524ef924544c151
27.362745
83
0.651227
3.936054
false
true
false
false
pablojotaguardiola/ParseQL-Swift-To-MySQL
Pruebas SceneKit Xcode8/Pruebas SceneKit Xcode8/GameViewController.swift
1
4019
// // GameViewController.swift // Pruebas SceneKit Xcode8 // // Created by Pablo Guardiola on 09/08/16. // Copyright © 2016 Pablo Guardiola. All rights reserved. // import UIKit import QuartzCore import SceneKit class GameViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // create a new scene let scene = SCNScene(named: "art.scnassets/ship.scn")! // create and add a camera to the scene let cameraNode = SCNNode() cameraNode.camera = SCNCamera() scene.rootNode.addChildNode(cameraNode) // place the camera cameraNode.position = SCNVector3(x: 0, y: 0, z: 15) // create and add a light to the scene let lightNode = SCNNode() lightNode.light = SCNLight() lightNode.light!.type = SCNLightTypeOmni lightNode.position = SCNVector3(x: 0, y: 10, z: 10) scene.rootNode.addChildNode(lightNode) // create and add an ambient light to the scene let ambientLightNode = SCNNode() ambientLightNode.light = SCNLight() ambientLightNode.light!.type = SCNLightTypeAmbient ambientLightNode.light!.color = UIColor.darkGray() scene.rootNode.addChildNode(ambientLightNode) // retrieve the ship node let ship = scene.rootNode.childNode(withName: "ship", recursively: true)! // animate the 3d object ship.run(SCNAction.repeatForever(SCNAction.rotateBy(x: 0, y: 2, z: 0, duration: 1))) // retrieve the SCNView let scnView = self.view as! SCNView // set the scene to the view scnView.scene = scene // allows the user to manipulate the camera scnView.allowsCameraControl = true // show statistics such as fps and timing information scnView.showsStatistics = true // configure the view scnView.backgroundColor = UIColor.black() // add a tap gesture recognizer let tapGesture = UITapGestureRecognizer(target: self, action: #selector(handleTap(_:))) scnView.addGestureRecognizer(tapGesture) } func handleTap(_ gestureRecognize: UIGestureRecognizer) { // retrieve the SCNView let scnView = self.view as! SCNView // check what nodes are tapped let p = gestureRecognize.location(in: scnView) let hitResults = scnView.hitTest(p, options: nil) // check that we clicked on at least one object if hitResults.count > 0 { // retrieved the first clicked object let result: AnyObject! = hitResults[0] // get its material let material = result.node!.geometry!.firstMaterial! // highlight it SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 // on completion - unhighlight SCNTransaction.completionBlock = { SCNTransaction.begin() SCNTransaction.animationDuration = 0.5 material.emission.contents = UIColor.black() SCNTransaction.commit() } material.emission.contents = UIColor.red() SCNTransaction.commit() } } override func shouldAutorotate() -> Bool { return true } override func prefersStatusBarHidden() -> Bool { return true } override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { if UIDevice.current().userInterfaceIdiom == .phone { return .allButUpsideDown } else { return .all } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Release any cached data, images, etc that aren't in use. } }
mit
6892ae218a46d693c22b6259c2adbf3e
31.144
95
0.588352
5.526823
false
false
false
false
BlenderSleuth/Unlokit
Unlokit/Scenes/TutorialScene.swift
1
11005
// // TutorialScene.swift // Unlokit // // Created by Ben Sutherland on 5/5/17. // Copyright © 2017 blendersleuthdev. All rights reserved. // import SpriteKit import UIKit // To keep track of which part the tutorial is enum TutStage: Int { case start = 0 case lock case key case goal case mtlBlock case spring case rubberBlock case bomb case breakableBlock case glue case glueBlock case fan case fanGlueBlock case gravity case gravityGlueBlock case load case rotate case fire case last var nextStep: TutStage? { return TutStage(rawValue: rawValue + 1) } } // For triggering different actions enum TriggerAction { case touch case loadKey case rotate case fire } class TutorialScene: GameScene { var animating = false var background: SKSpriteNode? var tutStage: TutStage = .start // The current helpnode var current: HelpNode! override func didMove(to view: SKView) { super.didMove(to: view) // Set the startingg angle of the controller controller.angle = 120 startTutorial() } override func moveController(_ location: CGPoint) { super.moveController(location) goToNextStage(action: .rotate) } func startTutorial() { // Dark background to fade out later background = SKSpriteNode(color: UIColor(red: 0.08, green: 0, blue: 0.08, alpha: 0.92), size: self.size) background?.zPosition = 240 background?.position = CGPoint(x: size.width/2, y: size.height/2) addChild(background!) let boxSize = CGSize(width: 1200, height: 200) let boxPos = CGPoint(x: size.width/2, y: size.height/2) current = HelpNode(position: boxPos, size: boxSize, text: "Welcome to Unlokit", nextAction: "Tap to continue") current.alpha = 0.7 current.zPosition = 250 addChild(current) // Setup nodes for the tutorial fireNode.isUserInteractionEnabled = false fireNode.zPosition = 210 key.isUserInteractionEnabled = true for (_, tool) in toolIcons { tool.isUserInteractionEnabled = true } // Make camera follow the nodeToFollow = current } func goToNextStage(action: TriggerAction) { // Make sure it is not animating guard !animating else { return } let nextStage: TutStage if let next = tutStage.nextStep { nextStage = next } else { print("Last Stage") nextStage = tutStage } // Default properties var size = CGSize(width: 700, height: 300) var arrowVector: CGPoint! let pos: CGPoint let text: String var nextAction = "Tap to continue" // Check which stage we are up to switch (nextStage, action) { case (.lock, .touch): arrowVector = CGPoint(x: 200, y: 200) let lockPos = convert(lock.position, from: lock.parent!) pos = CGPoint(x: lockPos.x - size.width/2 - arrowVector.x, y: lockPos.y - size.height/2 - arrowVector.y) text = "This is the lock" case (.key, .touch): arrowVector = CGPoint(x: -115, y: -115) pos = CGPoint(x: key.position.x + size.width/2 - arrowVector.x, y: key.position.y + size.height/2 - arrowVector.y) text = "This is the key" case (.goal, .touch): size.width = 2100 pos = CGPoint(x: self.size.width / 2, y: self.size.height / 2) text = "The goal of the game: shoot the key into the lock" //********************* TOOL SECTION ********************************************** case (.spring, .touch), (.bomb, .touch), (.glue, .touch), (.fan, .touch), (.gravity, .touch): let tool: ToolIcon // Only set different properties switch nextStage { case .spring: size.width = 1400 tool = toolIcons[.spring]! text = "The spring tool will turn blocks..." case .bomb: size.width = 1200 tool = toolIcons[.bomb]! text = "The bomb tool can destroy..." case .glue: size.width = 1200 tool = toolIcons[.glue]! text = "The glue tool will turn blocks..." case .fan: size.width = 1100 tool = toolIcons[.fan]! text = "The fan tool will stick to..." case .gravity: size.width = 1500 tool = toolIcons[.gravity]! text = "The black hole tool will create..." default: return } arrowVector = CGPoint(x: -110, y: -110) let toolPos = convert(tool.position, from: tool.parent!) pos = CGPoint(x: toolPos.x + size.width/2 - arrowVector.x, y: toolPos.y + size.height/2 - arrowVector.y) //********************* BLOCK SECTION ********************************************** case (.mtlBlock, .touch), (.rubberBlock, .touch), (.breakableBlock, .touch), (.glueBlock, .touch), (.fanGlueBlock, .touch), (.gravityGlueBlock, .touch): arrowVector = CGPoint(x: 130, y: -130) let block: SKNode switch nextStage { case .mtlBlock: block = childNode(withName: "blockShow")! arrowVector.x = -130 text = "This is a block" case .rubberBlock: size.width = 900 arrowVector.x = -130 block = childNode(withName: "rubberBlockShow")! text = "...into rubber blocks" case .breakableBlock: size.width = 900 block = childNode(withName: "breakableBlockShow")! text = "...breakable blocks" case .glueBlock: size.width = 900 block = childNode(withName: "glueBlockShow")! text = "...into glue blocks" case .fanGlueBlock: block = childNode(withName: "//breakableFan")! text = "...glue blocks" case .gravityGlueBlock: size.width = 800 block = childNode(withName: "gravityBlockShow")! text = "...a black hole" default: return } let blockPos = convert(block.position, from: block.parent!) if arrowVector.x < 0 { pos = CGPoint(x: blockPos.x + size.width/2 - arrowVector.x, y: blockPos.y + size.height/2 - arrowVector.y) } else { pos = CGPoint(x: blockPos.x - size.width/2 - arrowVector.x, y: blockPos.y + size.height/2 - arrowVector.y) } //********************* INTERACTIVE SECTION ********************************************** case (.load, .touch): size.width = 1000 arrowVector = CGPoint(x: -115, y: -115) pos = CGPoint(x: key.position.x + size.width/2 - arrowVector.x, y: key.position.y + size.height/2 - arrowVector.y) key.zPosition = 510 key.isUserInteractionEnabled = false text = "Tap the key to load it" nextAction = "Load key" case (.rotate, .loadKey): key.isUserInteractionEnabled = true size = CGSize(width: 1200, height: 600) arrowVector = CGPoint(x: -80, y: -900) let controllerPos = controller.scenePosition! pos = CGPoint(x: controllerPos.x + size.width/2 - arrowVector.x, y: controllerPos.y + size.height/2 - arrowVector.y) text = "Rotate the controller to aim" nextAction = "Rotate controller" case (.fire, .rotate): size.width = 800 arrowVector = CGPoint(x: 50, y: -280) let firePos = convert(fireNode.position, from: fireNode.parent!) pos = CGPoint(x: firePos.x - size.width/2 - arrowVector.x, y: firePos.y + size.height/2 - arrowVector.y) text = "Press this to fire" nextAction = "Fire!" fireNode.isUserInteractionEnabled = true case (.last, .fire): key.zPosition = 50 fireNode.zPosition = 50 // Hide the node current.run(SKAction.sequence([SKAction.fadeOut(withDuration: 0.3), SKAction.removeFromParent()])) return default: return } // Only set this after tutStage = nextStage // Set this to animating animating = true // Fadeout the arrow first, looks ugly otherwise current.arrowSprite?.run(SKAction.fadeOut(withDuration: 0.05)) background?.run(SKAction.sequence([SKAction.fadeOut(withDuration: 0.3), SKAction.removeFromParent()])) { weak var `self` = self self?.background = nil } // Fadeout last helpnode current.run(SKAction.sequence([SKAction.fadeOut(withDuration: 0.3), SKAction.removeFromParent()])) // Create a new helpnode current = HelpNode(position: pos, size: size, text: text, arrow: arrowVector, nextAction: nextAction) // Fade in the help node current.alpha = 0 addChild(current) current.run(SKAction.fadeIn(withDuration: 0.3)) { weak var `self` = self self?.animating = false } // Make the camera follow it nodeToFollow = current } override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesBegan(touches, with: event) for _ in touches { goToNextStage(action: .touch) } } override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) { super.touchesMoved(touches, with: event) // Don't go onto the next turorial } } class HelpNode: SKSpriteNode { var arrowSprite: SKSpriteNode? init(position: CGPoint, size: CGSize, text: String, arrow: CGPoint? = nil, nextAction: String) { super.init(texture: nil, color: .clear, size: size) self.alpha = 0 run(SKAction.fadeIn(withDuration: 0.3)) self.position = position self.anchorPoint = CGPoint(x: 0, y: 0) self.zPosition = 200 let box = SKShapeNode(rect: CGRect(origin: CGPoint(x: -size.width/2, y: -size.height/2), size: size), cornerRadius: 25) box.fillColor = .purple box.strokeColor = .black box.lineWidth = 3 box.glowWidth = 2 addChild(box) let label = SKLabelNode(fontNamed: neuropolFont) label.verticalAlignmentMode = .center label.fontSize = 64 label.text = text addChild(label) let tapToContinue = SKLabelNode(fontNamed: neuropolFont) label.verticalAlignmentMode = .center tapToContinue.text = nextAction tapToContinue.fontSize = 40 tapToContinue.position.y = -size.height / 3 // Close to the bottom of the box tapToContinue.alpha = 0 addChild(tapToContinue) // Actions let fadeIn = SKAction.fadeIn(withDuration: 1) fadeIn.timingMode = .easeInEaseOut let fadeOut = SKAction.fadeOut(withDuration: 1) fadeOut.timingMode = .easeInEaseOut let fadeInOut = SKAction.repeatForever(SKAction.sequence([fadeIn, fadeOut])) tapToContinue.run(SKAction.sequence([SKAction.wait(forDuration: 0.5), fadeInOut])) // Create an arrow to point at something if let arrow = arrow { let width = sqrt(pow(arrow.x, 2) + pow(arrow.y, 2)) let arrowSize = CGSize(width: width, height: 30) arrowSprite = SKSpriteNode(color: .purple, size: arrowSize) // Find the corner based on arrow vector let posX: CGFloat let posY: CGFloat if arrow.x < 0 { posX = -size.width/2 } else { posX = size.width/2 } if arrow.y < 0 { posY = -size.height/2 } else { posY = size.height/2 } arrowSprite!.position = CGPoint(x: posX, y: posY) arrowSprite!.zRotation = atan(arrow.y/arrow.x) addChild(arrowSprite!) let circle = SKShapeNode(circleOfRadius: width/2) circle.fillColor = .clear circle.strokeColor = .purple circle.lineWidth = 10 circle.position = CGPoint(x: posX + arrow.x, y: posY + arrow.y) addChild(circle) } } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
gpl-3.0
195ff726937aae24ba7e2d6d2d954722
28.111111
154
0.649037
3.369259
false
false
false
false
davidahouse/chute
chute/Output/DifferenceReport/DifferenceReportSummaryCodeCoverage.swift
1
4127
// // DifferenceReportSummaryCodeCoverage.swift // chute // // Created by David House on 11/16/17. // Copyright © 2017 David House. All rights reserved. // import Foundation struct DifferenceReportSummaryCodeCoverage: ChuteOutputDifferenceRenderable { enum Constants { static let Template = """ <div class="summary"> <div class="summary-item alert alert-info"> <div class="summary-item-text"><h1>{{average_coverage}} %</h1><span class="badge {{average_coverage_change_badge}}">{{average_coverage_change}}%</span></div> <div class="summary-item-text"><h3>Avg Coverage</h3></div> </div> <div class="summary-item alert alert-info"> <div class="summary-item-text"><h1>{{total_above_90}}</h1><span class="badge {{total_above_90_change_badge}}">{{total_above_90_change}}</span></div> <div class="summary-item-text"><h3>Above 90% Coverage</h3></div> </div> <div class="summary-item alert alert-info"> <div class="summary-item-text"><h1>{{total_no_coverage}}</h1><span class="badge {{total_no_coverage_change_badge}}">{{total_no_coverage_change}}</span></div> <div class="summary-item-text"><h3>No Coverage</h3></div> </div> </div> """ static let NoCodeCoverageTemplate = """ <div class="summary"> <div class="summary-item alert alert-info"> <div class="summary-item-text"><h1>{{average_coverage}} %</h1></div> <div class="summary-item-text"><h3>No coverage found</h3></div> </div> </div> """ } func render(difference: DataCaptureDifference) -> String { if difference.comparedTo.codeCoverage.lineCoverage > 0 { let average_coverage_change = difference.comparedTo.codeCoverageSummary.averageCoverage - difference.detail.codeCoverageSummary.averageCoverage let total_above_90_change = difference.comparedTo.codeCoverageSummary.filesAdequatelyCovered - difference.detail.codeCoverageSummary.filesAdequatelyCovered let total_no_coverage_change = difference.comparedTo.codeCoverageSummary.filesWithNoCoverage - difference.detail.codeCoverageSummary.filesWithNoCoverage let average_coverage_change_badge: String = { if average_coverage_change < 0.0 { return "badge-danger" } else { return "badge-success" } }() let total_above_90_change_badge: String = { if total_above_90_change < 0 { return "badge-danger" } else { return "badge-success" } }() let total_no_coverage_change_badge: String = { if total_no_coverage_change < 0 { return "badge-danger" } else { return "badge-success" } }() let parameters: [String: CustomStringConvertible] = [ "average_coverage": Int(round(difference.comparedTo.codeCoverageSummary.averageCoverage * 100)), "average_coverage_change": Int(round(average_coverage_change * 100)), "average_coverage_change_badge": average_coverage_change_badge, "total_above_90": difference.comparedTo.codeCoverageSummary.filesAdequatelyCovered, "total_above_90_change": total_above_90_change, "total_above_90_change_badge": total_above_90_change_badge, "total_no_coverage": difference.comparedTo.codeCoverageSummary.filesWithNoCoverage, "total_no_coverage_change": total_no_coverage_change, "total_no_coverage_change_badge": total_no_coverage_change_badge ] return Constants.Template.render(parameters: parameters) } else { return Constants.NoCodeCoverageTemplate.render(parameters: [:]) } } }
mit
2597d6e996697b0863b4cac0a9e162e7
43.847826
173
0.586282
4.293444
false
false
false
false
robertofrontado/RxGcm-iOS
iOS/Pods/Nimble/Sources/Nimble/Adapters/AssertionRecorder.swift
141
3800
import Foundation /// A data structure that stores information about an assertion when /// AssertionRecorder is set as the Nimble assertion handler. /// /// @see AssertionRecorder /// @see AssertionHandler public struct AssertionRecord: CustomStringConvertible { /// Whether the assertion succeeded or failed public let success: Bool /// The failure message the assertion would display on failure. public let message: FailureMessage /// The source location the expectation occurred on. public let location: SourceLocation public var description: String { return "AssertionRecord { success=\(success), message='\(message.stringValue)', location=\(location) }" } } /// An AssertionHandler that silently records assertions that Nimble makes. /// This is useful for testing failure messages for matchers. /// /// @see AssertionHandler public class AssertionRecorder : AssertionHandler { /// All the assertions that were captured by this recorder public var assertions = [AssertionRecord]() public init() {} public func assert(_ assertion: Bool, message: FailureMessage, location: SourceLocation) { assertions.append( AssertionRecord( success: assertion, message: message, location: location)) } } /// Allows you to temporarily replace the current Nimble assertion handler with /// the one provided for the scope of the closure. /// /// Once the closure finishes, then the original Nimble assertion handler is restored. /// /// @see AssertionHandler public func withAssertionHandler(_ tempAssertionHandler: AssertionHandler, closure: @escaping () throws -> Void) { let environment = NimbleEnvironment.activeInstance let oldRecorder = environment.assertionHandler let capturer = NMBExceptionCapture(handler: nil, finally: ({ environment.assertionHandler = oldRecorder })) environment.assertionHandler = tempAssertionHandler capturer.tryBlock { try! closure() } } /// Captures expectations that occur in the given closure. Note that all /// expectations will still go through to the default Nimble handler. /// /// This can be useful if you want to gather information about expectations /// that occur within a closure. /// /// @param silently expectations are no longer send to the default Nimble /// assertion handler when this is true. Defaults to false. /// /// @see gatherFailingExpectations public func gatherExpectations(silently: Bool = false, closure: @escaping () -> Void) -> [AssertionRecord] { let previousRecorder = NimbleEnvironment.activeInstance.assertionHandler let recorder = AssertionRecorder() let handlers: [AssertionHandler] if silently { handlers = [recorder] } else { handlers = [recorder, previousRecorder] } let dispatcher = AssertionDispatcher(handlers: handlers) withAssertionHandler(dispatcher, closure: closure) return recorder.assertions } /// Captures failed expectations that occur in the given closure. Note that all /// expectations will still go through to the default Nimble handler. /// /// This can be useful if you want to gather information about failed /// expectations that occur within a closure. /// /// @param silently expectations are no longer send to the default Nimble /// assertion handler when this is true. Defaults to false. /// /// @see gatherExpectations /// @see raiseException source for an example use case. public func gatherFailingExpectations(silently: Bool = false, closure: @escaping () -> Void) -> [AssertionRecord] { let assertions = gatherExpectations(silently: silently, closure: closure) return assertions.filter { assertion in !assertion.success } }
apache-2.0
1af97a5d458bf82a9d8ab825696a8b08
37
115
0.718158
5.05992
false
false
false
false
jonnguy/HSTracker
HSTracker/Logging/Enums/BnetGameType.swift
2
2632
// // BnetGameType.swift // HSTracker // // Created by Benjamin Michotte on 1/11/16. // Copyright © 2016 Benjamin Michotte. All rights reserved. // import Foundation enum BnetGameType: Int { case bgt_unknown = 0, bgt_friends = 1, bgt_ranked_standard = 2, bgt_arena = 3, bgt_vs_ai = 4, bgt_tutorial = 5, bgt_async = 6, bgt_newbie = 9, //bgt_casual_standard_newbie = 9, //bgt_casual_standard_normal = 10, bgt_casual_standard = 10, bgt_test1 = 11, bgt_test2 = 12, bgt_test3 = 13, bgt_tavernbrawl_pvp = 16, bgt_tavernbrawl_1p_versus_ai = 17, bgt_tavernbrawl_2p_coop = 18, bgt_ranked_wild = 30, bgt_casual_wild = 31, bgt_fsg_brawl_vs_friend = 40, bgt_fsg_brawl_pvp = 41, bgt_fsg_brawl_1p_versus_ai = 42, bgt_fsg_brawl_2p_coop = 43 static func getBnetGameType(gameType: GameType, format: Format?) -> BnetGameType { switch gameType { case .gt_vs_ai: return .bgt_vs_ai case .gt_vs_friend: return .bgt_friends case .gt_tutorial: return .bgt_tutorial case .gt_arena: return .bgt_arena case .gt_test: return .bgt_test1 case .gt_ranked: return format == .standard ? .bgt_ranked_standard : .bgt_ranked_wild case .gt_casual: return format == .standard ? .bgt_casual_standard : .bgt_casual_wild case .gt_tavernbrawl: return .bgt_tavernbrawl_pvp case .gt_tb_1p_vs_ai: return .bgt_tavernbrawl_1p_versus_ai case .gt_tb_2p_coop: return .bgt_tavernbrawl_2p_coop case .gt_fsg_brawl: return .bgt_fsg_brawl_vs_friend case .gt_fsg_brawl_1p_vs_ai: return .bgt_fsg_brawl_1p_versus_ai case .gt_fsg_brawl_2p_coop: return .bgt_fsg_brawl_2p_coop case .gt_fsg_brawl_vs_friend: return .bgt_fsg_brawl_vs_friend default: return .bgt_unknown } } static func getGameType(mode: GameMode, format: Format?) -> BnetGameType { switch mode { case .arena: return .bgt_arena case .ranked: return format == .standard ? .bgt_ranked_standard : .bgt_ranked_wild case .casual: return format == .standard ? .bgt_casual_standard : .bgt_casual_wild case .brawl: return .bgt_tavernbrawl_pvp case .friendly: return .bgt_friends case .practice: return .bgt_vs_ai default: return .bgt_unknown } } }
mit
fc70bb4ad5ca3042da28ce24aeba7021
28.561798
86
0.563284
3.066434
false
true
false
false
qvik/HelsinkiOS-IBD-Demo
HelsinkiOS-Demo/Views/ArticleList/ArticleListHeader.swift
1
1660
// // ArticleListHeader.swift // HelsinkiOS-Demo // // Created by Jerry Jalava on 28/09/15. // Copyright © 2015 Qvik. All rights reserved. // import UIKit @IBDesignable class ArticleListHeader: DesignableXib { @IBOutlet weak var categoryImage: UIImageView! @IBOutlet weak var categoryLabel: UILabel! @IBOutlet weak var followButton: FollowButton! @IBOutlet weak var followerCountLabel: UILabel! @IBInspectable var category: String = "Fashion" { didSet { setupView() } } @IBInspectable var following: Bool = false { didSet { setupView() } } // MARK: Default action handlers func followTapped(sender: AnyObject?) { followButton.following = !followButton.following } // MARK: Lifecycle override func initView() { followButton.addTarget(self, action: "followTapped:", forControlEvents: UIControlEvents.TouchUpInside) } override func setupView() { followButton.following = following categoryLabel.text = category.uppercaseString let bundle = NSBundle(forClass: self.dynamicType) categoryImage.image = UIImage(named: "Thumbnail_channel_\(category)", inBundle: bundle, compatibleWithTraitCollection: self.traitCollection) categoryLabel.textColor = UIColor.whiteColor() categoryLabel.layer.shadowColor = UIColor.appBlack().CGColor categoryLabel.layer.shadowRadius = 4.0 categoryLabel.layer.shadowOpacity = 2.9 categoryLabel.layer.shadowOffset = CGSizeZero categoryLabel.layer.masksToBounds = false } }
mit
5d3be94d659a24c508635fd93b1c43da
28.105263
148
0.666667
5.073394
false
false
false
false
arturjaworski/Colorizer
Sources/colorizer/Commands/GenerateCommand.swift
1
1890
import Foundation import SwiftCLI import PathKit import AppKit.NSColor class GenerateCommand: Command { let name = "generate" let shortDescription = "Generating CLR pallete (.clr file) from .txt file." let signature = "<InputFile> <OutputFile>" enum CommandError: Error { case noInputFile case invalidInputFile var description: String { switch self { case .noInputFile: return "InputFile do not exists. Please provide .txt file." case .invalidInputFile: return "InputFile is invalid. Please provide valid .txt file." } } } func execute(arguments: CommandArguments) throws { do { let inputFilePath = Path(arguments.requiredArgument("InputFile")) if !inputFilePath.isFile { throw CommandError.noInputFile } var colorFileParser: ColorFileParser? = nil do { switch inputFilePath.`extension` ?? "" { case "txt": colorFileParser = try TextColorFileParser(path: inputFilePath) default: () } } catch { throw CommandError.invalidInputFile } guard let parser = colorFileParser else { throw CommandError.invalidInputFile } let outputFileString = arguments.requiredArgument("OutputFile") let colorList = NSColorList(name: outputFileString) for (name, color) in parser.colors { colorList.setColor(color, forKey: name) } colorList.write(toFile: outputFileString) print("Generated successfully.") } catch let error as CommandError { print("Error: \(error.description)") } } }
mit
4fafec11ff32e90c2b17ffa6aa2490fd
30
98
0.562434
5.510204
false
false
false
false
amraboelela/swift-corelibs-foundation
Foundation/FileManager.swift
2
61016
// 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 // #if os(OSX) || os(iOS) import Darwin #elseif os(Linux) || CYGWIN import Glibc #endif #if os(Android) // struct stat.st_mode is UInt32 internal func &(left: UInt32, right: mode_t) -> mode_t { return mode_t(left) & right } #endif import CoreFoundation open class FileManager : NSObject { /* Returns the default singleton instance. */ private static let _default = FileManager() open class var `default`: FileManager { get { return _default } } /* Returns an NSArray of NSURLs locating the mounted volumes available on the computer. The property keys that can be requested are available in NSURL. */ open func mountedVolumeURLs(includingResourceValuesForKeys propertyKeys: [URLResourceKey]?, options: VolumeEnumerationOptions = []) -> [URL]? { NSUnimplemented() } /* Returns an NSArray of NSURLs identifying the the directory entries. If the directory contains no entries, this method will return the empty array. When an array is specified for the 'keys' parameter, the specified property values will be pre-fetched and cached with each enumerated URL. This method always does a shallow enumeration of the specified directory (i.e. it always acts as if NSDirectoryEnumerationSkipsSubdirectoryDescendants has been specified). If you need to perform a deep enumeration, use -[NSFileManager enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:]. If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'. */ open func contentsOfDirectory(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = []) throws -> [URL] { var error : Error? = nil let e = self.enumerator(at: url, includingPropertiesForKeys: keys, options: mask.union(.skipsSubdirectoryDescendants)) { (url, err) -> Bool in error = err return false } var result = [URL]() if let e = e { for url in e { result.append(url as! URL) } if let error = error { throw error } } return result } /* -URLsForDirectory:inDomains: is analogous to NSSearchPathForDirectoriesInDomains(), but returns an array of NSURL instances for use with URL-taking APIs. This API is suitable when you need to search for a file or files which may live in one of a variety of locations in the domains specified. */ open func urls(for directory: SearchPathDirectory, in domainMask: SearchPathDomainMask) -> [URL] { NSUnimplemented() } /* -URLForDirectory:inDomain:appropriateForURL:create:error: is a URL-based replacement for FSFindFolder(). It allows for the specification and (optional) creation of a specific directory for a particular purpose (e.g. the replacement of a particular item on disk, or a particular Library directory. You may pass only one of the values from the NSSearchPathDomainMask enumeration, and you may not pass NSAllDomainsMask. */ open func url(for directory: SearchPathDirectory, in domain: SearchPathDomainMask, appropriateFor url: URL?, create shouldCreate: Bool) throws -> URL { NSUnimplemented() } /* Sets 'outRelationship' to NSURLRelationshipContains if the directory at 'directoryURL' directly or indirectly contains the item at 'otherURL', meaning 'directoryURL' is found while enumerating parent URLs starting from 'otherURL'. Sets 'outRelationship' to NSURLRelationshipSame if 'directoryURL' and 'otherURL' locate the same item, meaning they have the same NSURLFileResourceIdentifierKey value. If 'directoryURL' is not a directory, or does not contain 'otherURL' and they do not locate the same file, then sets 'outRelationship' to NSURLRelationshipOther. If an error occurs, returns NO and sets 'error'. */ open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, ofDirectoryAt directoryURL: URL, toItemAt otherURL: URL) throws { NSUnimplemented() } /* Similar to -[NSFileManager getRelationship:ofDirectoryAtURL:toItemAtURL:error:], except that the directory is instead defined by an NSSearchPathDirectory and NSSearchPathDomainMask. Pass 0 for domainMask to instruct the method to automatically choose the domain appropriate for 'url'. For example, to discover if a file is contained by a Trash directory, call [fileManager getRelationship:&result ofDirectory:NSTrashDirectory inDomain:0 toItemAtURL:url error:&error]. */ open func getRelationship(_ outRelationship: UnsafeMutablePointer<URLRelationship>, of directory: SearchPathDirectory, in domainMask: SearchPathDomainMask, toItemAt url: URL) throws { NSUnimplemented() } /* createDirectoryAtURL:withIntermediateDirectories:attributes:error: creates a directory at the specified URL. If you pass 'NO' for withIntermediateDirectories, the directory must not exist at the time this call is made. Passing 'YES' for withIntermediateDirectories will create any necessary intermediate directories. This method returns YES if all directories specified in 'url' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference. */ open func createDirectory(at url: URL, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws { guard url.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url]) } try self.createDirectory(atPath: url.path, withIntermediateDirectories: createIntermediates, attributes: attributes) } /* createSymbolicLinkAtURL:withDestinationURL:error: returns YES if the symbolic link that point at 'destURL' was able to be created at the location specified by 'url'. 'destURL' is always resolved against its base URL, if it has one. If 'destURL' has no base URL and it's 'relativePath' is indeed a relative path, then a relative symlink will be created. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink. */ open func createSymbolicLink(at url: URL, withDestinationURL destURL: URL) throws { guard url.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url]) } guard destURL.scheme == nil || destURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : destURL]) } try self.createSymbolicLink(atPath: url.path, withDestinationPath: destURL.path) } /* Instances of FileManager may now have delegates. Each instance has one delegate, and the delegate is not retained. In versions of Mac OS X prior to 10.5, the behavior of calling [[NSFileManager alloc] init] was undefined. In Mac OS X 10.5 "Leopard" and later, calling [[NSFileManager alloc] init] returns a new instance of an FileManager. */ open weak var delegate: FileManagerDelegate? { NSUnimplemented() } /* setAttributes:ofItemAtPath:error: returns YES when the attributes specified in the 'attributes' dictionary are set successfully on the item specified by 'path'. If this method returns NO, a presentable NSError will be provided by-reference in the 'error' parameter. If no error is required, you may pass 'nil' for the error. This method replaces changeFileAttributes:atPath:. */ open func setAttributes(_ attributes: [FileAttributeKey : Any], ofItemAtPath path: String) throws { for attribute in attributes.keys { if attribute == .posixPermissions { guard let number = attributes[attribute] as? NSNumber else { fatalError("Can't set file permissions to \(attributes[attribute] as Any?)") } #if os(OSX) || os(iOS) let modeT = number.uint16Value #elseif os(Linux) || os(Android) || CYGWIN let modeT = number.uint32Value #endif if chmod(path, mode_t(modeT)) != 0 { fatalError("errno \(errno)") } } else { fatalError("Attribute type not implemented: \(attribute)") } } } /* createDirectoryAtPath:withIntermediateDirectories:attributes:error: creates a directory at the specified path. If you pass 'NO' for createIntermediates, the directory must not exist at the time this call is made. Passing 'YES' for 'createIntermediates' will create any necessary intermediate directories. This method returns YES if all directories specified in 'path' were created and attributes were set. Directories are created with attributes specified by the dictionary passed to 'attributes'. If no dictionary is supplied, directories are created according to the umask of the process. This method returns NO if a failure occurs at any stage of the operation. If an error parameter was provided, a presentable NSError will be returned by reference. This method replaces createDirectoryAtPath:attributes: */ open func createDirectory(atPath path: String, withIntermediateDirectories createIntermediates: Bool, attributes: [FileAttributeKey : Any]? = [:]) throws { if createIntermediates { var isDir: ObjCBool = false if !fileExists(atPath: path, isDirectory: &isDir) { let parent = path._nsObject.deletingLastPathComponent if !parent.isEmpty && !fileExists(atPath: parent, isDirectory: &isDir) { try createDirectory(atPath: parent, withIntermediateDirectories: true, attributes: attributes) } if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if let attr = attributes { try self.setAttributes(attr, ofItemAtPath: path) } } else if isDir.boolValue { return } else { throw _NSErrorWithErrno(EEXIST, reading: false, path: path) } } else { if mkdir(path, S_IRWXU | S_IRWXG | S_IRWXO) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if let attr = attributes { try self.setAttributes(attr, ofItemAtPath: path) } } } /** Performs a shallow search of the specified directory and returns the paths of any contained items. This method performs a shallow search of the directory and therefore does not traverse symbolic links or return the contents of any subdirectories. This method also does not return URLs for the current directory (“.”), parent directory (“..”) but it does return other hidden files (files that begin with a period character). The order of the files in the returned array is undefined. - Parameter path: The path to the directory whose contents you want to enumerate. - Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code. - Returns: An array of String each of which identifies a file, directory, or symbolic link contained in `path`. The order of the files returned is undefined. */ open func contentsOfDirectory(atPath path: String) throws -> [String] { var contents : [String] = [String]() let dir = opendir(path) if dir == nil { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: path]) } defer { closedir(dir!) } while let entry = readdir(dir!) { let entryName = withUnsafePointer(to: &entry.pointee.d_name) { String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self)) } // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. if entryName != "." && entryName != ".." { contents.append(entryName) } } return contents } /** Performs a deep enumeration of the specified directory and returns the paths of all of the contained subdirectories. This method recurses the specified directory and its subdirectories. The method skips the “.” and “..” directories at each level of the recursion. Because this method recurses the directory’s contents, you might not want to use it in performance-critical code. Instead, consider using the enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: or enumeratorAtPath: method to enumerate the directory contents yourself. Doing so gives you more control over the retrieval of items and more opportunities to abort the enumeration or perform other tasks at the same time. - Parameter path: The path of the directory to list. - Throws: `NSError` if the directory does not exist, this error is thrown with the associated error code. - Returns: An array of NSString objects, each of which contains the path of an item in the directory specified by path. If path is a symbolic link, this method traverses the link. This method returns nil if it cannot retrieve the device of the linked-to file. */ open func subpathsOfDirectory(atPath path: String) throws -> [String] { var contents : [String] = [String]() let dir = opendir(path) if dir == nil { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileReadNoSuchFile.rawValue, userInfo: [NSFilePathErrorKey: path]) } defer { closedir(dir!) } var entry = readdir(dir!) while entry != nil { let entryName = withUnsafePointer(to: &entry!.pointee.d_name) { String(cString: UnsafeRawPointer($0).assumingMemoryBound(to: CChar.self)) } // TODO: `entryName` should be limited in length to `entry.memory.d_namlen`. if entryName != "." && entryName != ".." { contents.append(entryName) let entryType = withUnsafePointer(to: &entry!.pointee.d_type) { (ptr) -> Int32 in return Int32(ptr.pointee) } #if os(OSX) || os(iOS) let tempEntryType = entryType #elseif os(Linux) || os(Android) || CYGWIN let tempEntryType = Int32(entryType) #endif if tempEntryType == Int32(DT_DIR) { let subPath: String = path + "/" + entryName let entries = try subpathsOfDirectory(atPath: subPath) contents.append(contentsOf: entries.map({file in "\(entryName)/\(file)"})) } } entry = readdir(dir!) } return contents } /* attributesOfItemAtPath:error: returns an NSDictionary of key/value pairs containing the attributes of the item (file, directory, symlink, etc.) at the path in question. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink. This method replaces fileAttributesAtPath:traverseLink:. */ open func attributesOfItem(atPath path: String) throws -> [FileAttributeKey : Any] { var s = stat() guard lstat(path, &s) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } var result = [FileAttributeKey : Any]() result[.size] = NSNumber(value: UInt64(s.st_size)) #if os(OSX) || os(iOS) let ti = (TimeInterval(s.st_mtimespec.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtimespec.tv_nsec)) #elseif os(Android) let ti = (TimeInterval(s.st_mtime) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtime_nsec)) #else let ti = (TimeInterval(s.st_mtim.tv_sec) - kCFAbsoluteTimeIntervalSince1970) + (1.0e-9 * TimeInterval(s.st_mtim.tv_nsec)) #endif result[.modificationDate] = Date(timeIntervalSinceReferenceDate: ti) result[.posixPermissions] = NSNumber(value: UInt64(s.st_mode & 0o7777)) result[.referenceCount] = NSNumber(value: UInt64(s.st_nlink)) result[.systemNumber] = NSNumber(value: UInt64(s.st_dev)) result[.systemFileNumber] = NSNumber(value: UInt64(s.st_ino)) if let pwd = getpwuid(s.st_uid), pwd.pointee.pw_name != nil { let name = String(cString: pwd.pointee.pw_name) result[.ownerAccountName] = name } if let grd = getgrgid(s.st_gid), grd.pointee.gr_name != nil { let name = String(cString: grd.pointee.gr_name) result[.groupOwnerAccountName] = name } var type : FileAttributeType switch s.st_mode & S_IFMT { case S_IFCHR: type = .typeCharacterSpecial case S_IFDIR: type = .typeDirectory case S_IFBLK: type = .typeBlockSpecial case S_IFREG: type = .typeRegular case S_IFLNK: type = .typeSymbolicLink case S_IFSOCK: type = .typeSocket default: type = .typeUnknown } result[.type] = type if type == .typeBlockSpecial || type == .typeCharacterSpecial { result[.deviceIdentifier] = NSNumber(value: UInt64(s.st_rdev)) } #if os(OSX) || os(iOS) if (s.st_flags & UInt32(UF_IMMUTABLE | SF_IMMUTABLE)) != 0 { result[.immutable] = NSNumber(value: true) } if (s.st_flags & UInt32(UF_APPEND | SF_APPEND)) != 0 { result[.appendOnly] = NSNumber(value: true) } #endif result[.ownerAccountID] = NSNumber(value: UInt64(s.st_uid)) result[.groupOwnerAccountID] = NSNumber(value: UInt64(s.st_gid)) return result } /* attributesOfFileSystemForPath:error: returns an NSDictionary of key/value pairs containing the attributes of the filesystem containing the provided path. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink. This method replaces fileSystemAttributesAtPath:. */ open func attributesOfFileSystem(forPath path: String) throws -> [FileAttributeKey : Any] { #if os(Android) NSUnimplemented() #else // statvfs(2) doesn't support 64bit inode on Darwin (apfs), fallback to statfs(2) #if os(OSX) || os(iOS) var s = statfs() guard statfs(path, &s) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } #else var s = statvfs() guard statvfs(path, &s) == 0 else { throw _NSErrorWithErrno(errno, reading: true, path: path) } #endif var result = [FileAttributeKey : Any]() #if os(OSX) || os(iOS) let blockSize = UInt64(s.f_bsize) result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid.val.0)) #else let blockSize = UInt64(s.f_frsize) result[.systemNumber] = NSNumber(value: UInt64(s.f_fsid)) #endif result[.systemSize] = NSNumber(value: blockSize * UInt64(s.f_blocks)) result[.systemFreeSize] = NSNumber(value: blockSize * UInt64(s.f_bavail)) result[.systemNodes] = NSNumber(value: UInt64(s.f_files)) result[.systemFreeNodes] = NSNumber(value: UInt64(s.f_ffree)) return result #endif } /* createSymbolicLinkAtPath:withDestination:error: returns YES if the symbolic link that point at 'destPath' was able to be created at the location specified by 'path'. If this method returns NO, the link was unable to be created and an NSError will be returned by reference in the 'error' parameter. This method does not traverse a terminal symlink. This method replaces createSymbolicLinkAtPath:pathContent: */ open func createSymbolicLink(atPath path: String, withDestinationPath destPath: String) throws { if symlink(destPath, path) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } /* destinationOfSymbolicLinkAtPath:error: returns an NSString containing the path of the item pointed at by the symlink specified by 'path'. If this method returns 'nil', an NSError will be returned by reference in the 'error' parameter. This method replaces pathContentOfSymbolicLinkAtPath: */ open func destinationOfSymbolicLink(atPath path: String) throws -> String { let bufSize = Int(PATH_MAX + 1) var buf = [Int8](repeating: 0, count: bufSize) let len = readlink(path, &buf, bufSize) if len < 0 { throw _NSErrorWithErrno(errno, reading: true, path: path) } return self.string(withFileSystemRepresentation: buf, length: Int(len)) } open func copyItem(atPath srcPath: String, toPath dstPath: String) throws { guard let attrs = try? attributesOfItem(atPath: srcPath), let fileType = attrs[.type] as? FileAttributeType else { return } if fileType == .typeDirectory { try createDirectory(atPath: dstPath, withIntermediateDirectories: false, attributes: nil) let subpaths = try subpathsOfDirectory(atPath: srcPath) for subpath in subpaths { try copyItem(atPath: srcPath + "/" + subpath, toPath: dstPath + "/" + subpath) } } else { if createFile(atPath: dstPath, contents: contents(atPath: srcPath), attributes: nil) == false { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnknown.rawValue, userInfo: [NSFilePathErrorKey : NSString(string: dstPath)]) } } } open func moveItem(atPath srcPath: String, toPath dstPath: String) throws { guard !self.fileExists(atPath: dstPath) else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteFileExists.rawValue, userInfo: [NSFilePathErrorKey : NSString(dstPath)]) } if rename(srcPath, dstPath) != 0 { if errno == EXDEV { // TODO: Copy and delete. NSUnimplemented("Cross-device moves not yet implemented") } else { throw _NSErrorWithErrno(errno, reading: false, path: srcPath) } } } open func linkItem(atPath srcPath: String, toPath dstPath: String) throws { var isDir: ObjCBool = false if self.fileExists(atPath: srcPath, isDirectory: &isDir) { if !isDir.boolValue { // TODO: Symlinks should be copied instead of hard-linked. if link(srcPath, dstPath) == -1 { throw _NSErrorWithErrno(errno, reading: false, path: srcPath) } } else { // TODO: Recurse through directories, copying them. NSUnimplemented("Recursive linking not yet implemented") } } } open func removeItem(atPath path: String) throws { if rmdir(path) == 0 { return } else if errno == ENOTEMPTY { let fsRep = FileManager.default.fileSystemRepresentation(withPath: path) let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2) ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) let stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil) ps.deinitialize(count: 2) ps.deallocate() if stream != nil { defer { fts_close(stream) } var current = fts_read(stream) while current != nil { switch Int32(current!.pointee.fts_info) { case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE: if unlink(current!.pointee.fts_path) == -1 { let str = NSString(bytes: current!.pointee.fts_path, length: Int(strlen(current!.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject throw _NSErrorWithErrno(errno, reading: false, path: str) } case FTS_DP: if rmdir(current!.pointee.fts_path) == -1 { let str = NSString(bytes: current!.pointee.fts_path, length: Int(strlen(current!.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject throw _NSErrorWithErrno(errno, reading: false, path: str) } default: break } current = fts_read(stream) } } else { let _ = _NSErrorWithErrno(ENOTEMPTY, reading: false, path: path) } // TODO: Error handling if fts_read fails. } else if errno != ENOTDIR { throw _NSErrorWithErrno(errno, reading: false, path: path) } else if unlink(path) != 0 { throw _NSErrorWithErrno(errno, reading: false, path: path) } } open func copyItem(at srcURL: URL, to dstURL: URL) throws { guard srcURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL]) } guard dstURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL]) } try copyItem(atPath: srcURL.path, toPath: dstURL.path) } open func moveItem(at srcURL: URL, to dstURL: URL) throws { guard srcURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL]) } guard dstURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL]) } try moveItem(atPath: srcURL.path, toPath: dstURL.path) } open func linkItem(at srcURL: URL, to dstURL: URL) throws { guard srcURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : srcURL]) } guard dstURL.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : dstURL]) } try linkItem(atPath: srcURL.path, toPath: dstURL.path) } open func removeItem(at url: URL) throws { guard url.isFileURL else { throw NSError(domain: NSCocoaErrorDomain, code: CocoaError.fileWriteUnsupportedScheme.rawValue, userInfo: [NSURLErrorKey : url]) } try self.removeItem(atPath: url.path) } /* Process working directory management. Despite the fact that these are instance methods on FileManager, these methods report and change (respectively) the working directory for the entire process. Developers are cautioned that doing so is fraught with peril. */ open var currentDirectoryPath: String { let length = Int(PATH_MAX) + 1 var buf = [Int8](repeating: 0, count: length) getcwd(&buf, length) let result = self.string(withFileSystemRepresentation: buf, length: Int(strlen(buf))) return result } @discardableResult open func changeCurrentDirectoryPath(_ path: String) -> Bool { return chdir(path) == 0 } /* The following methods are of limited utility. Attempting to predicate behavior based on the current state of the filesystem or a particular file on the filesystem is encouraging odd behavior in the face of filesystem race conditions. It's far better to attempt an operation (like loading a file or creating a directory) and handle the error gracefully than it is to try to figure out ahead of time whether the operation will succeed. */ open func fileExists(atPath path: String) -> Bool { return self.fileExists(atPath: path, isDirectory: nil) } open func fileExists(atPath path: String, isDirectory: UnsafeMutablePointer<ObjCBool>?) -> Bool { var s = stat() if lstat(path, &s) >= 0 { if let isDirectory = isDirectory { if (s.st_mode & S_IFMT) == S_IFLNK { if stat(path, &s) >= 0 { isDirectory.pointee = ObjCBool((s.st_mode & S_IFMT) == S_IFDIR) } else { return false } } else { let isDir = (s.st_mode & S_IFMT) == S_IFDIR isDirectory.pointee = ObjCBool(isDir) } } // don't chase the link for this magic case -- we might be /Net/foo // which is a symlink to /private/Net/foo which is not yet mounted... if (s.st_mode & S_IFMT) == S_IFLNK { if (s.st_mode & S_ISVTX) == S_ISVTX { return true } // chase the link; too bad if it is a slink to /Net/foo stat(path, &s) } } else { return false } return true } open func isReadableFile(atPath path: String) -> Bool { return access(path, R_OK) == 0 } open func isWritableFile(atPath path: String) -> Bool { return access(path, W_OK) == 0 } open func isExecutableFile(atPath path: String) -> Bool { return access(path, X_OK) == 0 } open func isDeletableFile(atPath path: String) -> Bool { NSUnimplemented() } /* -contentsEqualAtPath:andPath: does not take into account data stored in the resource fork or filesystem extended attributes. */ open func contentsEqual(atPath path1: String, andPath path2: String) -> Bool { NSUnimplemented() } /* displayNameAtPath: returns an NSString suitable for presentation to the user. For directories which have localization information, this will return the appropriate localized string. This string is not suitable for passing to anything that must interact with the filesystem. */ open func displayName(atPath path: String) -> String { NSUnimplemented() } /* componentsToDisplayForPath: returns an NSArray of display names for the path provided. Localization will occur as in displayNameAtPath: above. This array cannot and should not be reassembled into an usable filesystem path for any kind of access. */ open func componentsToDisplay(forPath path: String) -> [String]? { NSUnimplemented() } /* enumeratorAtPath: returns an NSDirectoryEnumerator rooted at the provided path. If the enumerator cannot be created, this returns NULL. Because NSDirectoryEnumerator is a subclass of NSEnumerator, the returned object can be used in the for...in construct. */ open func enumerator(atPath path: String) -> DirectoryEnumerator? { return NSPathDirectoryEnumerator(path: path) } /* enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: returns an NSDirectoryEnumerator rooted at the provided directory URL. The NSDirectoryEnumerator returns NSURLs from the -nextObject method. The optional 'includingPropertiesForKeys' parameter indicates which resource properties should be pre-fetched and cached with each enumerated URL. The optional 'errorHandler' block argument is invoked when an error occurs. Parameters to the block are the URL on which an error occurred and the error. When the error handler returns YES, enumeration continues if possible. Enumeration stops immediately when the error handler returns NO. If you wish to only receive the URLs and no other attributes, then pass '0' for 'options' and an empty NSArray ('[NSArray array]') for 'keys'. If you wish to have the property caches of the vended URLs pre-populated with a default set of attributes, then pass '0' for 'options' and 'nil' for 'keys'. */ // Note: Because the error handler is an optional block, the compiler treats it as @escaping by default. If that behavior changes, the @escaping will need to be added back. open func enumerator(at url: URL, includingPropertiesForKeys keys: [URLResourceKey]?, options mask: DirectoryEnumerationOptions = [], errorHandler handler: (/* @escaping */ (URL, Error) -> Bool)? = nil) -> DirectoryEnumerator? { if mask.contains(.skipsPackageDescendants) || mask.contains(.skipsHiddenFiles) { NSUnimplemented("Enumeration options not yet implemented") } return NSURLDirectoryEnumerator(url: url, options: mask, errorHandler: handler) } /* subpathsAtPath: returns an NSArray of all contents and subpaths recursively from the provided path. This may be very expensive to compute for deep filesystem hierarchies, and should probably be avoided. */ open func subpaths(atPath path: String) -> [String]? { NSUnimplemented() } /* These methods are provided here for compatibility. The corresponding methods on NSData which return NSErrors should be regarded as the primary method of creating a file from an NSData or retrieving the contents of a file as an NSData. */ open func contents(atPath path: String) -> Data? { do { return try Data(contentsOf: URL(fileURLWithPath: path)) } catch { return nil } } open func createFile(atPath path: String, contents data: Data?, attributes attr: [FileAttributeKey : Any]? = nil) -> Bool { do { try (data ?? Data()).write(to: URL(fileURLWithPath: path), options: .atomic) if let attr = attr { try self.setAttributes(attr, ofItemAtPath: path) } return true } catch _ { return false } } /* fileSystemRepresentationWithPath: returns an array of characters suitable for passing to lower-level POSIX style APIs. The string is provided in the representation most appropriate for the filesystem in question. */ open func fileSystemRepresentation(withPath path: String) -> UnsafePointer<Int8> { precondition(path != "", "Empty path argument") let len = CFStringGetMaximumSizeOfFileSystemRepresentation(path._cfObject) if len == kCFNotFound { fatalError("string could not be converted") } let buf = UnsafeMutablePointer<Int8>.allocate(capacity: len) for i in 0..<len { buf.advanced(by: i).initialize(to: 0) } if !path._nsObject.getFileSystemRepresentation(buf, maxLength: len) { buf.deinitialize(count: len) buf.deallocate() fatalError("string could not be converted") } return UnsafePointer(buf) } /* stringWithFileSystemRepresentation:length: returns an NSString created from an array of bytes that are in the filesystem representation. */ open func string(withFileSystemRepresentation str: UnsafePointer<Int8>, length len: Int) -> String { return NSString(bytes: str, length: len, encoding: String.Encoding.utf8.rawValue)!._swiftObject } /* -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: is for developers who wish to perform a safe-save without using the full NSDocument machinery that is available in the AppKit. The `originalItemURL` is the item being replaced. `newItemURL` is the item which will replace the original item. This item should be placed in a temporary directory as provided by the OS, or in a uniquely named directory placed in the same directory as the original item if the temporary directory is not available. If `backupItemName` is provided, that name will be used to create a backup of the original item. The backup is placed in the same directory as the original item. If an error occurs during the creation of the backup item, the operation will fail. If there is already an item with the same name as the backup item, that item will be removed. The backup item will be removed in the event of success unless the `NSFileManagerItemReplacementWithoutDeletingBackupItem` option is provided in `options`. For `options`, pass `0` to get the default behavior, which uses only the metadata from the new item while adjusting some properties using values from the original item. Pass `NSFileManagerItemReplacementUsingNewMetadataOnly` in order to use all possible metadata from the new item. */ /// - Experiment: This is a draft API currently under consideration for official import into Foundation as a suitable alternative /// - Note: Since this API is under consideration it may be either removed or revised in the near future open func replaceItem(at originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String?, options: ItemReplacementOptions = []) throws { NSUnimplemented() } internal func _tryToResolveTrailingSymlinkInPath(_ path: String) -> String? { guard _pathIsSymbolicLink(path) else { return nil } guard let destination = try? FileManager.default.destinationOfSymbolicLink(atPath: path) else { return nil } return _appendSymlinkDestination(destination, toPath: path) } internal func _appendSymlinkDestination(_ dest: String, toPath: String) -> String { if dest.hasPrefix("/") { return dest } else { let temp = toPath._bridgeToObjectiveC().deletingLastPathComponent return temp._bridgeToObjectiveC().appendingPathComponent(dest) } } internal func _pathIsSymbolicLink(_ path: String) -> Bool { guard let attrs = try? attributesOfItem(atPath: path), let fileType = attrs[.type] as? FileAttributeType else { return false } return fileType == .typeSymbolicLink } } extension FileManager { public func replaceItemAt(_ originalItemURL: URL, withItemAt newItemURL: URL, backupItemName: String? = nil, options: ItemReplacementOptions = []) throws -> NSURL? { NSUnimplemented() } } extension FileManager { open var homeDirectoryForCurrentUser: URL { return homeDirectory(forUser: NSUserName())! } open var temporaryDirectory: URL { return URL(fileURLWithPath: NSTemporaryDirectory()) } open func homeDirectory(forUser userName: String) -> URL? { guard !userName.isEmpty else { return nil } guard let url = CFCopyHomeDirectoryURLForUser(userName._cfObject) else { return nil } return url.takeRetainedValue()._swiftObject } } extension FileManager { public struct VolumeEnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } /* The mounted volume enumeration will skip hidden volumes. */ public static let skipHiddenVolumes = VolumeEnumerationOptions(rawValue: 1 << 1) /* The mounted volume enumeration will produce file reference URLs rather than path-based URLs. */ public static let produceFileReferenceURLs = VolumeEnumerationOptions(rawValue: 1 << 2) } public struct DirectoryEnumerationOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } /* NSDirectoryEnumerationSkipsSubdirectoryDescendants causes the NSDirectoryEnumerator to perform a shallow enumeration and not descend into directories it encounters. */ public static let skipsSubdirectoryDescendants = DirectoryEnumerationOptions(rawValue: 1 << 0) /* NSDirectoryEnumerationSkipsPackageDescendants will cause the NSDirectoryEnumerator to not descend into packages. */ public static let skipsPackageDescendants = DirectoryEnumerationOptions(rawValue: 1 << 1) /* NSDirectoryEnumerationSkipsHiddenFiles causes the NSDirectoryEnumerator to not enumerate hidden files. */ public static let skipsHiddenFiles = DirectoryEnumerationOptions(rawValue: 1 << 2) } public struct ItemReplacementOptions : OptionSet { public let rawValue : UInt public init(rawValue: UInt) { self.rawValue = rawValue } /* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to use metadata from the new item only and not to attempt to preserve metadata from the original item. */ public static let usingNewMetadataOnly = ItemReplacementOptions(rawValue: 1 << 0) /* Causes -replaceItemAtURL:withItemAtURL:backupItemName:options:resultingItemURL:error: to leave the backup item in place after a successful replacement. The default behavior is to remove the item. */ public static let withoutDeletingBackupItem = ItemReplacementOptions(rawValue: 1 << 1) } public enum URLRelationship : Int { case contains case same case other } } public struct FileAttributeKey : RawRepresentable, Equatable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: FileAttributeKey, _ rhs: FileAttributeKey) -> Bool { return lhs.rawValue == rhs.rawValue } public static let type = FileAttributeKey(rawValue: "NSFileType") public static let size = FileAttributeKey(rawValue: "NSFileSize") public static let modificationDate = FileAttributeKey(rawValue: "NSFileModificationDate") public static let referenceCount = FileAttributeKey(rawValue: "NSFileReferenceCount") public static let deviceIdentifier = FileAttributeKey(rawValue: "NSFileDeviceIdentifier") public static let ownerAccountName = FileAttributeKey(rawValue: "NSFileOwnerAccountName") public static let groupOwnerAccountName = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountName") public static let posixPermissions = FileAttributeKey(rawValue: "NSFilePosixPermissions") public static let systemNumber = FileAttributeKey(rawValue: "NSFileSystemNumber") public static let systemFileNumber = FileAttributeKey(rawValue: "NSFileSystemFileNumber") public static let extensionHidden = FileAttributeKey(rawValue: "NSFileExtensionHidden") public static let hfsCreatorCode = FileAttributeKey(rawValue: "NSFileHFSCreatorCode") public static let hfsTypeCode = FileAttributeKey(rawValue: "NSFileHFSTypeCode") public static let immutable = FileAttributeKey(rawValue: "NSFileImmutable") public static let appendOnly = FileAttributeKey(rawValue: "NSFileAppendOnly") public static let creationDate = FileAttributeKey(rawValue: "NSFileCreationDate") public static let ownerAccountID = FileAttributeKey(rawValue: "NSFileOwnerAccountID") public static let groupOwnerAccountID = FileAttributeKey(rawValue: "NSFileGroupOwnerAccountID") public static let busy = FileAttributeKey(rawValue: "NSFileBusy") public static let systemSize = FileAttributeKey(rawValue: "NSFileSystemSize") public static let systemFreeSize = FileAttributeKey(rawValue: "NSFileSystemFreeSize") public static let systemNodes = FileAttributeKey(rawValue: "NSFileSystemNodes") public static let systemFreeNodes = FileAttributeKey(rawValue: "NSFileSystemFreeNodes") } public struct FileAttributeType : RawRepresentable, Equatable, Hashable { public let rawValue: String public init(_ rawValue: String) { self.rawValue = rawValue } public init(rawValue: String) { self.rawValue = rawValue } public var hashValue: Int { return self.rawValue.hashValue } public static func ==(_ lhs: FileAttributeType, _ rhs: FileAttributeType) -> Bool { return lhs.rawValue == rhs.rawValue } public static let typeDirectory = FileAttributeType(rawValue: "NSFileTypeDirectory") public static let typeRegular = FileAttributeType(rawValue: "NSFileTypeRegular") public static let typeSymbolicLink = FileAttributeType(rawValue: "NSFileTypeSymbolicLink") public static let typeSocket = FileAttributeType(rawValue: "NSFileTypeSocket") public static let typeCharacterSpecial = FileAttributeType(rawValue: "NSFileTypeCharacterSpecial") public static let typeBlockSpecial = FileAttributeType(rawValue: "NSFileTypeBlockSpecial") public static let typeUnknown = FileAttributeType(rawValue: "NSFileTypeUnknown") } public protocol FileManagerDelegate : NSObjectProtocol { /* fileManager:shouldCopyItemAtPath:toPath: gives the delegate an opportunity to filter the resulting copy. Returning YES from this method will allow the copy to happen. Returning NO from this method causes the item in question to be skipped. If the item skipped was a directory, no children of that directory will be copied, nor will the delegate be notified of those children. */ func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldCopyItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: gives the delegate an opportunity to recover from or continue copying after an error. If an error occurs, the error object will contain an NSError indicating the problem. The source path and destination paths are also provided. If this method returns YES, the FileManager instance will continue as if the error had not occurred. If this method returns NO, the FileManager instance will stop copying, return NO from copyItemAtPath:toPath:error: and the error will be provied there. */ func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldMoveItemAtPath:toPath: gives the delegate an opportunity to not move the item at the specified path. If the source path and the destination path are not on the same device, a copy is performed to the destination path and the original is removed. If the copy does not succeed, an error is returned and the incomplete copy is removed, leaving the original in place. */ func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldMoveItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldProceedAfterError:movingItemAtPath:toPath: functions much like fileManager:shouldProceedAfterError:copyingItemAtPath:toPath: above. The delegate has the opportunity to remedy the error condition and allow the move to continue. */ func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldLinkItemAtPath:toPath: acts as the other "should" methods, but this applies to the file manager creating hard links to the files in question. */ func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldLinkItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldProceedAfterError:linkingItemAtPath:toPath: allows the delegate an opportunity to remedy the error which occurred in linking srcPath to dstPath. If the delegate returns YES from this method, the linking will continue. If the delegate returns NO from this method, the linking operation will stop and the error will be returned via linkItemAtPath:toPath:error:. */ func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAt srcURL: URL, to dstURL: URL) -> Bool /* fileManager:shouldRemoveItemAtPath: allows the delegate the opportunity to not remove the item at path. If the delegate returns YES from this method, the FileManager instance will attempt to remove the item. If the delegate returns NO from this method, the remove skips the item. If the item is a directory, no children of that item will be visited. */ func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool func fileManager(_ fileManager: FileManager, shouldRemoveItemAt URL: URL) -> Bool /* fileManager:shouldProceedAfterError:removingItemAtPath: allows the delegate an opportunity to remedy the error which occurred in removing the item at the path provided. If the delegate returns YES from this method, the removal operation will continue. If the delegate returns NO from this method, the removal operation will stop and the error will be returned via linkItemAtPath:toPath:error:. */ func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAt URL: URL) -> Bool } extension FileManagerDelegate { func fileManager(_ fileManager: FileManager, shouldCopyItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldCopyItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, copyingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldMoveItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldMoveItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, movingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldLinkItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldLinkItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtPath srcPath: String, toPath dstPath: String) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, linkingItemAtURL srcURL: URL, toURL dstURL: URL) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldRemoveItemAtPath path: String) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldRemoveItemAtURL url: URL) -> Bool { return true } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtPath path: String) -> Bool { return false } func fileManager(_ fileManager: FileManager, shouldProceedAfterError error: Error, removingItemAtURL url: URL) -> Bool { return false } } extension FileManager { open class DirectoryEnumerator : NSEnumerator { /* For NSDirectoryEnumerators created with -enumeratorAtPath:, the -fileAttributes and -directoryAttributes methods return an NSDictionary containing the keys listed below. For NSDirectoryEnumerators created with -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler:, these two methods return nil. */ open var fileAttributes: [FileAttributeKey : Any]? { NSRequiresConcreteImplementation() } open var directoryAttributes: [FileAttributeKey : Any]? { NSRequiresConcreteImplementation() } /* This method returns the number of levels deep the current object is in the directory hierarchy being enumerated. The directory passed to -enumeratorAtURL:includingPropertiesForKeys:options:errorHandler: is considered to be level 0. */ open var level: Int { NSRequiresConcreteImplementation() } open func skipDescendants() { NSRequiresConcreteImplementation() } } internal class NSPathDirectoryEnumerator: DirectoryEnumerator { let baseURL: URL let innerEnumerator : DirectoryEnumerator override var fileAttributes: [FileAttributeKey : Any]? { NSUnimplemented() } override var directoryAttributes: [FileAttributeKey : Any]? { NSUnimplemented() } override var level: Int { NSUnimplemented() } override func skipDescendants() { NSUnimplemented() } init?(path: String) { let url = URL(fileURLWithPath: path) self.baseURL = url guard let ie = FileManager.default.enumerator(at: url, includingPropertiesForKeys: nil, options: [], errorHandler: nil) else { return nil } self.innerEnumerator = ie } override func nextObject() -> Any? { let o = innerEnumerator.nextObject() guard let url = o as? URL else { return nil } let path = url.path.replacingOccurrences(of: baseURL.path+"/", with: "") return path } } internal class NSURLDirectoryEnumerator : DirectoryEnumerator { var _url : URL var _options : FileManager.DirectoryEnumerationOptions var _errorHandler : ((URL, Error) -> Bool)? var _stream : UnsafeMutablePointer<FTS>? = nil var _current : UnsafeMutablePointer<FTSENT>? = nil var _rootError : Error? = nil var _gotRoot : Bool = false // See @escaping comments above. init(url: URL, options: FileManager.DirectoryEnumerationOptions, errorHandler: (/* @escaping */ (URL, Error) -> Bool)?) { _url = url _options = options _errorHandler = errorHandler if FileManager.default.fileExists(atPath: _url.path) { let fsRep = FileManager.default.fileSystemRepresentation(withPath: _url.path) let ps = UnsafeMutablePointer<UnsafeMutablePointer<Int8>?>.allocate(capacity: 2) ps.initialize(to: UnsafeMutablePointer(mutating: fsRep)) ps.advanced(by: 1).initialize(to: nil) _stream = fts_open(ps, FTS_PHYSICAL | FTS_XDEV | FTS_NOCHDIR, nil) ps.deinitialize(count: 2) ps.deallocate() } else { _rootError = _NSErrorWithErrno(ENOENT, reading: true, url: url) } } deinit { if let stream = _stream { fts_close(stream) } } override func nextObject() -> Any? { if let stream = _stream { if !_gotRoot { _gotRoot = true // Skip the root. _current = fts_read(stream) } _current = fts_read(stream) while let current = _current { switch Int32(current.pointee.fts_info) { case FTS_D: if _options.contains(.skipsSubdirectoryDescendants) { fts_set(_stream, _current, FTS_SKIP) } fallthrough case FTS_DEFAULT, FTS_F, FTS_NSOK, FTS_SL, FTS_SLNONE: let str = NSString(bytes: current.pointee.fts_path, length: Int(strlen(current.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject return URL(fileURLWithPath: str) case FTS_DNR, FTS_ERR, FTS_NS: let keepGoing : Bool if let handler = _errorHandler { let str = NSString(bytes: current.pointee.fts_path, length: Int(strlen(current.pointee.fts_path)), encoding: String.Encoding.utf8.rawValue)!._swiftObject keepGoing = handler(URL(fileURLWithPath: str), _NSErrorWithErrno(current.pointee.fts_errno, reading: true)) } else { keepGoing = true } if !keepGoing { fts_close(stream) _stream = nil return nil } default: break } _current = fts_read(stream) } // TODO: Error handling if fts_read fails. } else if let error = _rootError { // Was there an error opening the stream? if let handler = _errorHandler { let _ = handler(_url, error) } } return nil } override var directoryAttributes : [FileAttributeKey : Any]? { return nil } override var fileAttributes: [FileAttributeKey : Any]? { return nil } override var level: Int { return Int(_current?.pointee.fts_level ?? 0) } override func skipDescendants() { if let stream = _stream, let current = _current { fts_set(stream, current, FTS_SKIP) } } } }
apache-2.0
8fc1f3e878d77892f1ac2577cda4329b
53.4625
771
0.660333
5.125021
false
false
false
false
SwiftOnTheServer/DrinkChooser
actions/slackDrink.swift
1
3121
import KituraNet import SwiftyJSON func main(args: [String:Any]) -> [String:Any] { print ("slackDrinkProcessor called") // validate args guard let command = args["command"] as? String, let channelId = args["channel_id"] as? String, let channelName = args["channel_name"] as? String, let userId = args["user_id"] as? String, let username = args["user_name"] as? String, let responseUrl = args["response_url"] as? String, let token = args["token"] as? String, let text = args["text"] as? String else { return createResponse(["error": "Missing argument. Must have command, channel_id, channel_name, user_id, user_name, response_url, token, text"], code: 400) } if (token != args["slack_verification_token"] as! String) { return createResponse(["response_type": "ephemeral", "text": "Missing Slack verification token"]) } // "command" must be "drink" if command != "/drink" { return createResponse(["response_type": "ephemeral", "text": "You didn't ask for a drink!"]) } // text must be "please" if text != "please" { return createResponse(["response_type": "ephemeral", "text": "You didn't ask nicely!"]) } print("Calling choose action") // call choose action let env = ProcessInfo.processInfo.environment let namespace : String = env["__OW_NAMESPACE"] ?? "" let incrementAction = "/" + namespace + "/DC/choose" let result = Whisk.invoke(actionNamed: incrementAction, withParameters: [ "username": username ]) let jsonResult = JSON(result) if jsonResult["response"]["success"].boolValue == false { return createResponse(["response_type": "ephemeral", "text": "I couldn't select a drink for you at this time, sorry!"]) } let drink = jsonResult["response"]["result"]["recommendation"].stringValue print("How about \(drink), \(username)?") let body: [String:Any] = [ "response_type": "in_channel", "text" : "How about \(drink), \(username)?" ] // This was needed when Swift actions were too slow at cold start // if responseUrl != "" { // print("posting to \(responseUrl)") // postJsonTo(responseUrl, data: body) { response in // } // } return createResponse(body) } func postJsonTo(_ url: String, data: [String:Any], callback: @escaping ClientRequest.Callback) { let jsonBody = WhiskJsonUtils.dictionaryToJsonString(jsonDict: data) ?? "" let base64Body = Data(jsonBody.utf8) postTo(url, body: base64Body, headers: ["Content-Type": "application/json"], callback: callback) } func postTo(_ url: String, body: Data, headers: [String: String], callback: @escaping ClientRequest.Callback) { var options: [ClientRequest.Options] = [ .schema(""), .method("POST"), .hostname(url), .headers(headers) ] var result: [String:Any] = ["result": "No response"] let request = HTTP.request(options, callback: callback) request.write(from: body) request.end() // send request }
mit
4b05545106e94998a41b90bd389eadf9
34.465909
163
0.623839
3.985951
false
false
false
false
cozkurt/coframework
COFramework/COFramework/Swift/Components/GeoLocation/GeoLocationManager.swift
1
4050
// // GeoLocationManager.swift // COLibrary // // Created by Cenker Ozkurt on 07/14/16. // Copyright (c) 2015 Cenker Ozkurt. All rights reserved. // import Foundation import MapKit import CoreLocation public class GeoLocationManager: NSObject, CLLocationManagerDelegate { /// Location objects public var locationManager: CLLocationManager? public var location: CLLocation? // // MARK: - sharedInstance for singleton access // public static let sharedInstance: GeoLocationManager = GeoLocationManager() //MARK: LocationManager Functions public override init() { super.init() self.locationManager = CLLocationManager() self.locationManager?.delegate = self self.locationManager?.desiredAccuracy = kCLLocationAccuracyKilometer self.locationManagerStart() } public func requestWhenInUseAuthorization() { // request when in use authorizatioin self.locationManager?.requestWhenInUseAuthorization() } public func locationManagerStart() { //start updating location self.locationManager?.startUpdatingLocation() Logger.sharedInstance.LogDebug("Location services started...") } public func locationManagerStop() { self.locationManager?.stopUpdatingLocation() Logger.sharedInstance.LogDebug("Location services stopped...") } //MARK: clLocationManager Delegate Function public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) { if status == .restricted || status == .denied { self.showAlert() } } public func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { if let lastLocation = locations.last { self.location = lastLocation } } //MARK: helper Functions public func isLocationAvailable() -> Bool { if CLLocationManager.locationServicesEnabled() { switch CLLocationManager.authorizationStatus() { case .notDetermined: self.requestWhenInUseAuthorization() return false case .restricted, .denied: Logger.sharedInstance.LogDebug("Location services denied/restricted by user...") return false case .authorizedWhenInUse, .authorizedAlways: Logger.sharedInstance.LogDebug("Location services granted by user..") return true default: Logger.sharedInstance.LogDebug("Location services undefined response..") return false } } self.showAlert() return false } // // Not in use for now // public func showAlert() { let alert = UIAlertController(title: "Location sharing required".localize(), message: "You need to allow Location Services to continue".localize(), preferredStyle: .alert) alert.addAction(UIAlertAction(title: "Settings".localize(), style: .default) { (_) in #if targetEnvironment(macCatalyst) let settingsURL = URL(fileURLWithPath: "x-apple.systempreferences:com.apple.preference") UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) #else if let settingsURL = URL(string: UIApplication.openSettingsURLString) { UIApplication.shared.open(settingsURL, options: [:], completionHandler: nil) } #endif }) alert.addAction(UIAlertAction(title: "OK".localize(), style: .cancel, handler: nil)) NotificationsCenterManager.sharedInstance.post("PRESENT", userInfo: ["viewController": alert]) } }
gpl-3.0
62ed4ed44443a259aabca6731658ed8f
33.033613
117
0.609136
6.17378
false
false
false
false
soulfly/guinea-pig-smart-bot
node_modules/quickblox/samples/cordova/video_chat/plugins/cordova-plugin-iosrtc/src/PluginRTCPeerConnection.swift
4
18094
import Foundation class PluginRTCPeerConnection : NSObject, RTCPeerConnectionDelegate, RTCSessionDescriptionDelegate { var rtcPeerConnectionFactory: RTCPeerConnectionFactory var rtcPeerConnection: RTCPeerConnection! var pluginRTCPeerConnectionConfig: PluginRTCPeerConnectionConfig var pluginRTCPeerConnectionConstraints: PluginRTCPeerConnectionConstraints // PluginRTCDataChannel dictionary. var pluginRTCDataChannels: [Int : PluginRTCDataChannel] = [:] // PluginRTCDTMFSender dictionary. var pluginRTCDTMFSenders: [Int : PluginRTCDTMFSender] = [:] var eventListener: (data: NSDictionary) -> Void var eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void var eventListenerForRemoveStream: (id: String) -> Void var onCreateDescriptionSuccessCallback: ((rtcSessionDescription: RTCSessionDescription) -> Void)! var onCreateDescriptionFailureCallback: ((error: NSError) -> Void)! var onSetDescriptionSuccessCallback: (() -> Void)! var onSetDescriptionFailureCallback: ((error: NSError) -> Void)! init( rtcPeerConnectionFactory: RTCPeerConnectionFactory, pcConfig: NSDictionary?, pcConstraints: NSDictionary?, eventListener: (data: NSDictionary) -> Void, eventListenerForAddStream: (pluginMediaStream: PluginMediaStream) -> Void, eventListenerForRemoveStream: (id: String) -> Void ) { NSLog("PluginRTCPeerConnection#init()") self.rtcPeerConnectionFactory = rtcPeerConnectionFactory self.pluginRTCPeerConnectionConfig = PluginRTCPeerConnectionConfig(pcConfig: pcConfig) self.pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: pcConstraints) self.eventListener = eventListener self.eventListenerForAddStream = eventListenerForAddStream self.eventListenerForRemoveStream = eventListenerForRemoveStream } deinit { NSLog("PluginRTCPeerConnection#deinit()") self.pluginRTCDTMFSenders = [:] } func run() { NSLog("PluginRTCPeerConnection#run()") self.rtcPeerConnection = self.rtcPeerConnectionFactory.peerConnectionWithICEServers( self.pluginRTCPeerConnectionConfig.getIceServers(), constraints: self.pluginRTCPeerConnectionConstraints.getConstraints(), delegate: self ) } func createOffer( options: NSDictionary?, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#createOffer()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options) self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in NSLog("PluginRTCPeerConnection#createOffer() | success callback") let data = [ "type": rtcSessionDescription.type, "sdp": rtcSessionDescription.description ] callback(data: data) } self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#createOffer() | failure callback: %@", String(error)) errback(error: error) } self.rtcPeerConnection.createOfferWithDelegate(self, constraints: pluginRTCPeerConnectionConstraints.getConstraints()) } func createAnswer( options: NSDictionary?, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#createAnswer()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCPeerConnectionConstraints = PluginRTCPeerConnectionConstraints(pcConstraints: options) self.onCreateDescriptionSuccessCallback = { (rtcSessionDescription: RTCSessionDescription) -> Void in NSLog("PluginRTCPeerConnection#createAnswer() | success callback") let data = [ "type": rtcSessionDescription.type, "sdp": rtcSessionDescription.description ] callback(data: data) } self.onCreateDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#createAnswer() | failure callback: %@", String(error)) errback(error: error) } self.rtcPeerConnection.createAnswerWithDelegate(self, constraints: pluginRTCPeerConnectionConstraints.getConstraints()) } func setLocalDescription( desc: NSDictionary, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#setLocalDescription()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let type = desc.objectForKey("type") as? String ?? "" let sdp = desc.objectForKey("sdp") as? String ?? "" let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp) self.onSetDescriptionSuccessCallback = { [unowned self] () -> Void in NSLog("PluginRTCPeerConnection#setLocalDescription() | success callback") let data = [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] callback(data: data) } self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#setLocalDescription() | failure callback: %@", String(error)) errback(error: error) } self.rtcPeerConnection.setLocalDescriptionWithDelegate(self, sessionDescription: rtcSessionDescription ) } func setRemoteDescription( desc: NSDictionary, callback: (data: NSDictionary) -> Void, errback: (error: NSError) -> Void ) { NSLog("PluginRTCPeerConnection#setRemoteDescription()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let type = desc.objectForKey("type") as? String ?? "" let sdp = desc.objectForKey("sdp") as? String ?? "" let rtcSessionDescription = RTCSessionDescription(type: type, sdp: sdp) self.onSetDescriptionSuccessCallback = { [unowned self] () -> Void in NSLog("PluginRTCPeerConnection#setRemoteDescription() | success callback") let data = [ "type": self.rtcPeerConnection.remoteDescription.type, "sdp": self.rtcPeerConnection.remoteDescription.description ] callback(data: data) } self.onSetDescriptionFailureCallback = { (error: NSError) -> Void in NSLog("PluginRTCPeerConnection#setRemoteDescription() | failure callback: %@", String(error)) errback(error: error) } self.rtcPeerConnection.setRemoteDescriptionWithDelegate(self, sessionDescription: rtcSessionDescription ) } func addIceCandidate( candidate: NSDictionary, callback: (data: NSDictionary) -> Void, errback: () -> Void ) { NSLog("PluginRTCPeerConnection#addIceCandidate()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let sdpMid = candidate.objectForKey("sdpMid") as? String ?? "" let sdpMLineIndex = candidate.objectForKey("sdpMLineIndex") as? Int ?? 0 let candidate = candidate.objectForKey("candidate") as? String ?? "" let result: Bool = self.rtcPeerConnection.addICECandidate(RTCICECandidate( mid: sdpMid, index: sdpMLineIndex, sdp: candidate )) var data: NSDictionary if result == true { if self.rtcPeerConnection.remoteDescription != nil { data = [ "remoteDescription": [ "type": self.rtcPeerConnection.remoteDescription.type, "sdp": self.rtcPeerConnection.remoteDescription.description ] ] } else { data = [ "remoteDescription": false ] } callback(data: data) } else { errback() } } func addStream(pluginMediaStream: PluginMediaStream) -> Bool { NSLog("PluginRTCPeerConnection#addStream()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return false } return self.rtcPeerConnection.addStream(pluginMediaStream.rtcMediaStream) } func removeStream(pluginMediaStream: PluginMediaStream) { NSLog("PluginRTCPeerConnection#removeStream()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.rtcPeerConnection.removeStream(pluginMediaStream.rtcMediaStream) } func createDataChannel( dcId: Int, label: String, options: NSDictionary?, eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCPeerConnection#createDataChannel()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDataChannel = PluginRTCDataChannel( rtcPeerConnection: rtcPeerConnection, label: label, options: options, eventListener: eventListener, eventListenerForBinaryMessage: eventListenerForBinaryMessage ) // Store the pluginRTCDataChannel into the dictionary. self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel // Run it. pluginRTCDataChannel.run() } func RTCDataChannel_setListener( dcId: Int, eventListener: (data: NSDictionary) -> Void, eventListenerForBinaryMessage: (data: NSData) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_setListener()") let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } // Set the eventListener. pluginRTCDataChannel!.setListener(eventListener, eventListenerForBinaryMessage: eventListenerForBinaryMessage ) } func createDTMFSender( dsId: Int, track: PluginMediaStreamTrack, eventListener: (data: NSDictionary) -> Void ) { NSLog("PluginRTCPeerConnection#createDTMFSender()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDTMFSender = PluginRTCDTMFSender( rtcPeerConnection: rtcPeerConnection, track: track.rtcMediaStreamTrack, eventListener: eventListener ) // Store the pluginRTCDTMFSender into the dictionary. self.pluginRTCDTMFSenders[dsId] = pluginRTCDTMFSender // Run it. pluginRTCDTMFSender.run() } func close() { NSLog("PluginRTCPeerConnection#close()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.rtcPeerConnection.close() } func RTCDataChannel_sendString( dcId: Int, data: String, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_sendString()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.sendString(data, callback: callback) } func RTCDataChannel_sendBinary( dcId: Int, data: NSData, callback: (data: NSDictionary) -> Void ) { NSLog("PluginRTCPeerConnection#RTCDataChannel_sendBinary()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.sendBinary(data, callback: callback) } func RTCDataChannel_close(dcId: Int) { NSLog("PluginRTCPeerConnection#RTCDataChannel_close()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDataChannel = self.pluginRTCDataChannels[dcId] if pluginRTCDataChannel == nil { return; } pluginRTCDataChannel!.close() // Remove the pluginRTCDataChannel from the dictionary. self.pluginRTCDataChannels[dcId] = nil } func RTCDTMFSender_insertDTMF( dsId: Int, tones: String, duration: Int, interToneGap: Int ) { NSLog("PluginRTCPeerConnection#RTCDTMFSender_insertDTMF()") if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } let pluginRTCDTMFSender = self.pluginRTCDTMFSenders[dsId] if pluginRTCDTMFSender == nil { return } pluginRTCDTMFSender!.insertDTMF(tones, duration: duration, interToneGap: interToneGap) } /** * Methods inherited from RTCPeerConnectionDelegate. */ func peerConnection(peerConnection: RTCPeerConnection!, signalingStateChanged newState: RTCSignalingState) { let state_str = PluginRTCTypes.signalingStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | onsignalingstatechange [signalingState:%@]", String(state_str)) self.eventListener(data: [ "type": "signalingstatechange", "signalingState": state_str ]) } func peerConnection(peerConnection: RTCPeerConnection!, iceGatheringChanged newState: RTCICEGatheringState) { let state_str = PluginRTCTypes.iceGatheringStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | onicegatheringstatechange [iceGatheringState:%@]", String(state_str)) self.eventListener(data: [ "type": "icegatheringstatechange", "iceGatheringState": state_str ]) if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } // Emit an empty candidate if iceGatheringState is "complete". if newState.rawValue == RTCICEGatheringComplete.rawValue && self.rtcPeerConnection.localDescription != nil { self.eventListener(data: [ "type": "icecandidate", // NOTE: Cannot set null as value. "candidate": false, "localDescription": [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] ]) } } func peerConnection(peerConnection: RTCPeerConnection!, gotICECandidate candidate: RTCICECandidate!) { NSLog("PluginRTCPeerConnection | onicecandidate [sdpMid:%@, sdpMLineIndex:%@, candidate:%@]", String(candidate.sdpMid), String(candidate.sdpMLineIndex), String(candidate.sdp)) if self.rtcPeerConnection.signalingState.rawValue == RTCSignalingClosed.rawValue { return } self.eventListener(data: [ "type": "icecandidate", "candidate": [ "sdpMid": candidate.sdpMid, "sdpMLineIndex": candidate.sdpMLineIndex, "candidate": candidate.sdp ], "localDescription": [ "type": self.rtcPeerConnection.localDescription.type, "sdp": self.rtcPeerConnection.localDescription.description ] ]) } func peerConnection(peerConnection: RTCPeerConnection!, iceConnectionChanged newState: RTCICEConnectionState) { let state_str = PluginRTCTypes.iceConnectionStates[newState.rawValue] as String! NSLog("PluginRTCPeerConnection | oniceconnectionstatechange [iceConnectionState:%@]", String(state_str)) self.eventListener(data: [ "type": "iceconnectionstatechange", "iceConnectionState": state_str ]) } func peerConnection(rtcPeerConnection: RTCPeerConnection!, addedStream rtcMediaStream: RTCMediaStream!) { NSLog("PluginRTCPeerConnection | onaddstream") let pluginMediaStream = PluginMediaStream(rtcMediaStream: rtcMediaStream) pluginMediaStream.run() // Let the plugin store it in its dictionary. self.eventListenerForAddStream(pluginMediaStream: pluginMediaStream) // Fire the 'addstream' event so the JS will create a new MediaStream. self.eventListener(data: [ "type": "addstream", "stream": pluginMediaStream.getJSON() ]) } func peerConnection(rtcPeerConnection: RTCPeerConnection!, removedStream rtcMediaStream: RTCMediaStream!) { NSLog("PluginRTCPeerConnection | onremovestream") // Let the plugin remove it from its dictionary. self.eventListenerForRemoveStream(id: rtcMediaStream.label) self.eventListener(data: [ "type": "removestream", "streamId": rtcMediaStream.label // NOTE: No "id" property yet. ]) } func peerConnectionOnRenegotiationNeeded(peerConnection: RTCPeerConnection!) { NSLog("PluginRTCPeerConnection | onnegotiationeeded") self.eventListener(data: [ "type": "negotiationneeded" ]) } func peerConnection(peerConnection: RTCPeerConnection!, didOpenDataChannel rtcDataChannel: RTCDataChannel!) { NSLog("PluginRTCPeerConnection | ondatachannel") let dcId = PluginUtils.randomInt(10000, max:99999) let pluginRTCDataChannel = PluginRTCDataChannel( rtcDataChannel: rtcDataChannel ) // Store the pluginRTCDataChannel into the dictionary. self.pluginRTCDataChannels[dcId] = pluginRTCDataChannel // Run it. pluginRTCDataChannel.run() // Fire the 'datachannel' event so the JS will create a new RTCDataChannel. self.eventListener(data: [ "type": "datachannel", "channel": [ "dcId": dcId, "label": rtcDataChannel.label, "ordered": rtcDataChannel.isOrdered, "maxPacketLifeTime": rtcDataChannel.maxRetransmitTime, "maxRetransmits": rtcDataChannel.maxRetransmits, "protocol": rtcDataChannel.`protocol`, "negotiated": rtcDataChannel.isNegotiated, "id": rtcDataChannel.streamId, "readyState": PluginRTCTypes.dataChannelStates[rtcDataChannel.state.rawValue] as String!, "bufferedAmount": rtcDataChannel.bufferedAmount ] ]) } /** * Methods inherited from RTCSessionDescriptionDelegate. */ func peerConnection(rtcPeerConnection: RTCPeerConnection!, didCreateSessionDescription rtcSessionDescription: RTCSessionDescription!, error: NSError!) { if error == nil { self.onCreateDescriptionSuccessCallback(rtcSessionDescription: rtcSessionDescription) } else { self.onCreateDescriptionFailureCallback(error: error) } } func peerConnection(peerConnection: RTCPeerConnection!, didSetSessionDescriptionWithError error: NSError!) { if error == nil { self.onSetDescriptionSuccessCallback() } else { self.onSetDescriptionFailureCallback(error: error) } } }
apache-2.0
82963450e1be6cd7185dc753ae9f444f
27.090032
110
0.728695
4.092739
false
false
false
false
recruit-lifestyle/RippleCell
Pod/Classes/RippleCell.swift
1
4984
// // RippleCell.swift // RippleCell // // Copyright 2015 RECRUIT LIFESTYLE CO., LTD. // import UIKit public class RippleCell: UITableViewCell { var targetColor = UIColor(red: 101.0/255.0, green: 198.0/255.0, blue: 187.0/255.0, alpha: 0.9) var targetBackGroundColor = UIColor(red: 200.0/255.0, green: 247.0/255.0, blue: 197.0/255.0, alpha: 1.0) var showDuration: NSTimeInterval! private var touchedPoint = CGPointZero private var targetView = UIView() private var targetBackGroundView = UIView() private var isFinishBackgroundAnimation = true private var isFinishTargetAnimaiton = true var radiusSmallLength = CGFloat(0.0) var radiusLargeLength = CGFloat(0.0) override init(style: UITableViewCellStyle, reuseIdentifier: String!) { super.init(style: style, reuseIdentifier: reuseIdentifier) setLayout() } required public init(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override public func awakeFromNib() { super.awakeFromNib() } override public func setSelected(selected: Bool, animated: Bool) { super.setSelected(selected, animated: animated) } override public func setHighlighted(highlighted: Bool, animated: Bool) { super.setHighlighted(highlighted, animated: animated) } override public func touchesBegan(touches: Set<NSObject>, withEvent event: UIEvent) { let touch = touches.first as! UITouch touchedPoint = touch.locationInView(self) super.touchesBegan(touches, withEvent: event) } override public func touchesCancelled(touches: Set<NSObject>!, withEvent event: UIEvent!) { super.touchesCancelled(touches, withEvent: event) } override public func touchesEnded(touches: Set<NSObject>, withEvent event: UIEvent) { if(isFinishTargetAnimaiton && isFinishBackgroundAnimation){ isFinishBackgroundAnimation = false isFinishTargetAnimaiton = false animationWithCircleStart() } super.touchesEnded(touches, withEvent: event) } private func setLayout(){ targetBackGroundView = UIView(frame: CGRectMake(0, 0, self.frame.size.width, self.frame.size.height)) targetBackGroundView.clipsToBounds = true targetBackGroundView.layer.masksToBounds = true backgroundView = targetBackGroundView self.textLabel?.backgroundColor = UIColor.clearColor() touchedPoint = self.contentView.center showDuration = 0.6 self.layer.masksToBounds = true radiusSmallLength = self.frame.size.height * 5 radiusLargeLength = self.frame.size.width * 10 } func animationWithCircleStart(){ showTargetView() showFadeBackgroundIn() } func animationWithCirleEnd(){ self.removeFadeBackgroundOut() self.removeTargetView() } private func showTargetView(){ targetView = UIView(frame: CGRectMake(0, 0, radiusLargeLength, radiusLargeLength)) targetView.center = touchedPoint targetView.layer.cornerRadius = radiusLargeLength / 2 targetView.layer.masksToBounds = true targetView.backgroundColor = targetColor self.selectedBackgroundView.addSubview(targetView) targetView.transform = CGAffineTransformMakeScale(0, 0) UIView.animateWithDuration(showDuration, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.targetView.center = self.touchedPoint self.targetView.transform = CGAffineTransformIdentity }, completion: nil) } private func removeTargetView(){ UIView.animateWithDuration(showDuration, delay: 0, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in self.targetView.alpha = 0.0 self.targetView.layer.cornerRadius = self.frame.size.width / 3 self.targetView.frame = CGRectMake(self.touchedPoint.x - self.radiusLargeLength / 2, self.touchedPoint.y - self.radiusLargeLength / 2, self.radiusLargeLength, self.radiusLargeLength) }) { (animated) -> Void in self.targetView.removeFromSuperview() self.isFinishTargetAnimaiton = true } } private func showFadeBackgroundIn(){ targetBackGroundView.backgroundColor = targetBackGroundColor targetBackGroundView.alpha = 0.0 UIView.animateWithDuration(showDuration, animations: { () -> Void in self.targetBackGroundView.alpha = 1.0 }) { (animated) -> Void in self.animationWithCirleEnd() } } private func removeFadeBackgroundOut(){ self.targetBackGroundView.alpha = 0.0 self.isFinishBackgroundAnimation = true } }
apache-2.0
1c0523cd93d83108b4d14129a1cc0294
36.19403
198
0.657303
4.848249
false
false
false
false
CooperRS/RMActionController
RMActionController-SwiftDemo/ViewController.swift
1
6999
// // MasterViewController.swift // RMActionController-SwiftDemo // // Created by Roland Moers on 19.08.15. // Copyright (c) 2015 Roland Moers. All rights reserved. // import UIKit import RMActionController import MapKit class ViewController: UITableViewController { //MARK: Properties @IBOutlet weak var blackSwitch: UISwitch! @IBOutlet weak var blurSwitch: UISwitch! @IBOutlet weak var blurActionSwitch: UISwitch! @IBOutlet weak var motionSwitch: UISwitch! @IBOutlet weak var bouncingSwitch: UISwitch! // MARK: Actions func openCustomActionController() { var style = RMActionControllerStyle.white if self.blackSwitch.isOn { style = RMActionControllerStyle.black } let selectAction = RMAction<UIView>(title: "Select", style: RMActionStyle.done) { controller in print("Custom action controller finished successfully") } let cancelAction = RMAction<UIView>(title: "Cancel", style: RMActionStyle.cancel) { _ in print("custom action controller was canceled") } let actionController = CustomViewActionController(style: style) actionController.title = "Test" actionController.message = "This is a test message.\nPlease choose a date and press 'Select' or 'Cancel'." actionController.addAction(selectAction) actionController.addAction(cancelAction) present(actionController: actionController); } func openExportActionController() { var style = RMActionControllerStyle.white if self.blackSwitch.isOn { style = RMActionControllerStyle.black } let action1 = RMImageAction<UIView>(title: "File", image: UIImage(named: "File")!, style: .done) let action2 = RMImageAction<UIView>(title: "Mail", image: UIImage(named: "Mail")!, style: .done) let action3 = RMImageAction<UIView>(title: "Server", image: UIImage(named: "Server")!, style: .done) let action4 = RMImageAction<UIView>(title: "Calendar", image: UIImage(named: "Calendar")!, style: .done) let selectAction = RMScrollableGroupedAction<UIView>(style: .done, actionWidth: 100, andActions: [action1, action2, action3, action4]) let cancelAction = RMAction<UIView>(title: "Cancel", style: RMActionStyle.cancel) { _ in print("custom action controller was canceled") } let actionController = CustomViewActionController(style: style) actionController.title = "Export" actionController.message = "Please choose an export format or tap 'Cancel'." actionController.addAction(selectAction) actionController.addAction(cancelAction) present(actionController: actionController); } func openMapActionController() { var style = RMActionControllerStyle.white if self.blackSwitch.isOn { style = RMActionControllerStyle.black } let selectAction = RMAction<MKMapView>(title: "Select", style: RMActionStyle.done) { controller in print("Map action controller finished successfully") } let cancelAction = RMAction<MKMapView>(title: "Cancel", style: RMActionStyle.cancel) { _ in print("Map action controller was canceled") } let actionController = MapActionController(style: style) actionController.title = "Test" actionController.message = "This is a map action controller.\nPlease choose a date and press 'Select' or 'Cancel'." actionController.addAction(selectAction) actionController.addAction(cancelAction) present(actionController: actionController); } func openCustomSheetController() { var style = RMActionControllerStyle.sheetWhite if self.blackSwitch.isOn { style = RMActionControllerStyle.sheetBlack } let selectAction = RMAction<UIView>(title: "Select", style: RMActionStyle.done) { controller in print("Custom action controller finished successfully") } let cancelAction = RMAction<UIView>(title: "Cancel", style: RMActionStyle.cancel) { _ in print("custom action controller was canceled") } let actionController = CustomViewActionController(style: style) actionController.title = "Test" actionController.message = "This is a test message.\nPlease choose a date and press 'Select' or 'Cancel'." actionController.addAction(selectAction) actionController.addAction(cancelAction) present(actionController: actionController); } func present<T>(actionController: RMActionController<T>) { //You can enable or disable blur, bouncing and motion effects actionController.disableBouncingEffects = !self.bouncingSwitch.isOn actionController.disableMotionEffects = !self.motionSwitch.isOn actionController.disableBlurEffects = !self.blurSwitch.isOn actionController.disableBlurEffectsForActions = !self.blurActionSwitch.isOn //On the iPad we want to show the date selection view controller within a popover. Fortunately, we can use iOS 8 API for this! :) //(Of course only if we are running on iOS 8 or later) if actionController.responds(to: Selector(("popoverPresentationController:"))) && UIDevice.current.userInterfaceIdiom == UIUserInterfaceIdiom.pad { //First we set the modal presentation style to the popover style actionController.modalPresentationStyle = UIModalPresentationStyle.popover //Then we tell the popover presentation controller, where the popover should appear if let popoverPresentationController = actionController.popoverPresentationController { popoverPresentationController.sourceView = self.tableView popoverPresentationController.sourceRect = self.tableView.rectForRow(at: IndexPath(row: 0, section: 0)) } } //Now just present the date selection controller using the standard iOS presentation method present(actionController, animated: true, completion: nil) } // MARK: UITableView Delegates override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { if(indexPath.section != 0) { return } switch indexPath.row { case 0: openCustomActionController() break; case 1: openExportActionController() break; case 2: openMapActionController() break; case 3: openCustomSheetController() break; default: break; } tableView.deselectRow(at: indexPath, animated: true) } }
mit
a59b25b81d997f3791f8960268b7d0d8
39.69186
155
0.657523
5.254505
false
false
false
false
mirrorinf/Mathematicus
MathematicusTests/MathematicusTests.swift
1
1900
// Licensed to the Apache Software Foundation (ASF) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The ASF licenses this file // to you 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 XCTest @testable import Mathematicus class MathematicusTests: 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. // Use XCTAssert and related functions to verify your tests produce the correct results. let p = Polynomial<Int>(coffcient: [3 : 1, 2 : -5, 1 : 8, 0 : -4], maxexp: 3) let (q, r) = p.exactReduce(atRoot: 1) XCTAssert(r == 1) let s = q * Polynomial<Int>(coffcient: [1 : 1, 0 : -1], maxexp: 1) let sb = s + (-1) * p XCTAssert(sb.isZeroPolynomial()) } func testPerformanceExample() { // This is an example of a performance test case. self.measure { // Put the code you want to measure the time of here. } } }
apache-2.0
548cdc6f8740d290bcc660bf3e9220f6
35.538462
111
0.674737
4.059829
false
true
false
false
ikesyo/Commandant
Sources/Commandant/Argument.swift
3
2864
// // Argument.swift // Commandant // // Created by Syo Ikeda on 12/14/15. // Copyright (c) 2015 Carthage. All rights reserved. // import Result /// Describes an argument that can be provided on the command line. public struct Argument<T> { /// The default value for this argument. This is the value that will be used /// if the argument is never explicitly specified on the command line. /// /// If this is nil, this argument is always required. public let defaultValue: T? /// A human-readable string describing the purpose of this argument. This will /// be shown in help messages. public let usage: String public init(defaultValue: T? = nil, usage: String) { self.defaultValue = defaultValue self.usage = usage } fileprivate func invalidUsageError<ClientError>(_ value: String) -> CommandantError<ClientError> { let description = "Invalid value for '\(self)': \(value)" return .usageError(description: description) } } /// Evaluates the given argument in the given mode. /// /// If parsing command line arguments, and no value was specified on the command /// line, the argument's `defaultValue` is used. public func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<T>) -> Result<T, CommandantError<ClientError>> { switch mode { case let .arguments(arguments): guard let stringValue = arguments.consumePositionalArgument() else { if let defaultValue = argument.defaultValue { return .success(defaultValue) } else { return .failure(missingArgumentError(argument.usage)) } } if let value = T.from(string: stringValue) { return .success(value) } else { return .failure(argument.invalidUsageError(stringValue)) } case .usage: return .failure(informativeUsageError(argument)) } } /// Evaluates the given argument list in the given mode. /// /// If parsing command line arguments, and no value was specified on the command /// line, the argument's `defaultValue` is used. public func <| <T: ArgumentProtocol, ClientError>(mode: CommandMode, argument: Argument<[T]>) -> Result<[T], CommandantError<ClientError>> { switch mode { case let .arguments(arguments): guard let firstValue = arguments.consumePositionalArgument() else { if let defaultValue = argument.defaultValue { return .success(defaultValue) } else { return .failure(missingArgumentError(argument.usage)) } } var values = [T]() guard let value = T.from(string: firstValue) else { return .failure(argument.invalidUsageError(firstValue)) } values.append(value) while let nextValue = arguments.consumePositionalArgument() { guard let value = T.from(string: nextValue) else { return .failure(argument.invalidUsageError(nextValue)) } values.append(value) } return .success(values) case .usage: return .failure(informativeUsageError(argument)) } }
mit
d637e5bd6be2c3101eaafc1912d13e12
28.833333
140
0.719972
3.891304
false
false
false
false
tkremenek/swift
test/IRGen/protocol_conformance_records.swift
4
7419
// RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-library-evolution -enable-source-import -I %S/../Inputs | %FileCheck %s // RUN: %target-swift-frontend %s -emit-ir -num-threads 8 -enable-library-evolution -enable-source-import -I %S/../Inputs | %FileCheck %s import resilient_struct import resilient_protocol public protocol Associate { associatedtype X } public struct Dependent<T> {} public protocol Runcible { func runce() } // CHECK-LABEL: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE:@"\$s28protocol_conformance_records8RuncibleMp"]] // -- type metadata // CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVMn" // -- witness table // CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 }, public struct NativeValueType: Runcible { public func runce() {} } // CHECK-LABEL: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- class metadata // CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCMn" // -- witness table // CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 }, public class NativeClassType: Runcible { public func runce() {} } // CHECK-LABEL: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- nominal type descriptor // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn" // -- witness table // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAWP" // -- flags // CHECK-SAME: i32 0 }, public struct NativeGenericType<T>: Runcible { public func runce() {} } // CHECK-LABEL: @"$sSi28protocol_conformance_records8RuncibleAAMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- type metadata // CHECK-SAME: @"{{got.|\\01__imp__?}}$sSiMn" // -- witness table // CHECK-SAME: @"$sSi28protocol_conformance_records8RuncibleAAWP" // -- reserved // CHECK-SAME: i32 8 // CHECK-SAME: } extension Int: Runcible { public func runce() {} } // For a resilient struct, reference the NominalTypeDescriptor // CHECK-LABEL: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" ={{ dllexport | protected | }}constant %swift.protocol_conformance_descriptor { // -- protocol descriptor // CHECK-SAME: [[RUNCIBLE]] // -- nominal type descriptor // CHECK-SAME: @"{{got.|\\01__imp__?}}$s16resilient_struct4SizeVMn" // -- witness table // CHECK-SAME: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADWP" // -- reserved // CHECK-SAME: i32 8 // CHECK-SAME: } extension Size: Runcible { public func runce() {} } // A non-dependent type conforming to a protocol with associated conformances // does not require a generic witness table. public protocol Simple {} public protocol AssociateConformance { associatedtype X : Simple } public struct Other : Simple {} public struct Concrete : AssociateConformance { public typealias X = Other } // CHECK-LABEL: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAMc" ={{ dllexport | protected | }}constant // -- protocol descriptor // CHECK-SAME: @"$s28protocol_conformance_records20AssociateConformanceMp" // -- nominal type descriptor // CHECK-SAME: @"$s28protocol_conformance_records8ConcreteVMn" // -- witness table // CHECK-SAME: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAWP" // -- no flags are set, and no generic witness table follows // CHECK-SAME: i32 0 } public protocol Spoon { } // Conditional conformances // CHECK-LABEL: {{^}}@"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" ={{ dllexport | protected | }}constant // -- protocol descriptor // CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp" // -- nominal type descriptor // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVMn" // -- witness table accessor // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5Spoon // -- flags // CHECK-SAME: i32 131328 // -- conditional requirement #1 // CHECK-SAME: i32 128, // CHECK-SAME: i32 0, // CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp" // CHECK-SAME: } extension NativeGenericType : Spoon where T: Spoon { public func runce() {} } // Retroactive conformance // CHECK-LABEL: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc" ={{ dllexport | protected | }}constant // -- protocol descriptor // CHECK-SAME: @"{{got.|\\01__imp__?}}$s18resilient_protocol22OtherResilientProtocolMp" // -- nominal type descriptor // CHECK-SAME: @"{{got.|\\01__imp__?}}$sSiMn" // -- witness table pattern // CHECK-SAME: i32 0, // -- flags // CHECK-SAME: i32 131144, // -- module context for retroactive conformance // CHECK-SAME: @"$s28protocol_conformance_recordsMXM" // CHECK-SAME: } extension Int : OtherResilientProtocol { } // Dependent conformance // CHECK-LABEL: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAMc" ={{ dllexport | protected | }}constant // -- protocol descriptor // CHECK-SAME: @"$s28protocol_conformance_records9AssociateMp" // -- nominal type descriptor // CHECK-SAME: @"$s28protocol_conformance_records9DependentVMn" // -- witness table pattern // CHECK-SAME: @"$s28protocol_conformance_records9DependentVyxGAA9AssociateAAWp" // -- flags // CHECK-SAME: i32 131072, // -- number of words in witness table // CHECK-SAME: i16 2, // -- number of private words in witness table + bit for "needs instantiation" // CHECK-SAME: i16 1 // CHECK-SAME: } extension Dependent : Associate { public typealias X = (T, T) } // CHECK-LABEL: @"\01l_protocols" // CHECK-SAME: @"$s28protocol_conformance_records8RuncibleMp" // CHECK-SAME: @"$s28protocol_conformance_records5SpoonMp" // CHECK-LABEL: @"\01l_protocol_conformances" = private constant // CHECK-SAME: @"$s28protocol_conformance_records15NativeValueTypeVAA8RuncibleAAMc" // CHECK-SAME: @"$s28protocol_conformance_records15NativeClassTypeCAA8RuncibleAAMc" // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA8RuncibleAAMc" // CHECK-SAME: @"$s16resilient_struct4SizeV28protocol_conformance_records8RuncibleADMc" // CHECK-SAME: @"$s28protocol_conformance_records8ConcreteVAA20AssociateConformanceAAMc" // CHECK-SAME: @"$s28protocol_conformance_records17NativeGenericTypeVyxGAA5SpoonA2aERzlMc" // CHECK-SAME: @"$sSi18resilient_protocol22OtherResilientProtocol0B20_conformance_recordsMc"
apache-2.0
1cfe62e959e4a7285e4aaa077811343c
40.915254
177
0.698477
4.047463
false
false
false
false
yeahdongcn/RSBarcodes_Swift
Source/RSEANGenerator.swift
1
3979
// // RSEANGenerator.swift // RSBarcodesSample // // Created by R0CKSTAR on 6/11/14. // Copyright (c) 2014 P.D.Q. All rights reserved. // import UIKit public let RSBarcodesTypeISBN13Code = "com.pdq.rsbarcodes.isbn13" public let RSBarcodesTypeISSN13Code = "com.pdq.rsbarcodes.issn13" // http://blog.sina.com.cn/s/blog_4015406e0100bsqk.html @available(macCatalyst 14.0, *) open class RSEANGenerator: RSAbstractCodeGenerator { var length = 0 // 'O' for odd and 'E' for even let lefthandParities = [ "OOOOOO", "OOEOEE", "OOEEOE", "OOEEEO", "OEOOEE", "OEEOOE", "OEEEOO", "OEOEOE", "OEOEEO", "OEEOEO" ] // 'R' for right-hand let parityEncodingTable = [ ["O" : "0001101", "E" : "0100111", "R" : "1110010"], ["O" : "0011001", "E" : "0110011", "R" : "1100110"], ["O" : "0010011", "E" : "0011011", "R" : "1101100"], ["O" : "0111101", "E" : "0100001", "R" : "1000010"], ["O" : "0100011", "E" : "0011101", "R" : "1011100"], ["O" : "0110001", "E" : "0111001", "R" : "1001110"], ["O" : "0101111", "E" : "0000101", "R" : "1010000"], ["O" : "0111011", "E" : "0010001", "R" : "1000100"], ["O" : "0110111", "E" : "0001001", "R" : "1001000"], ["O" : "0001011", "E" : "0010111", "R" : "1110100"] ] init(length:Int) { self.length = length } override open func isValid(_ contents: String) -> Bool { if super.isValid(contents) && self.length == contents.length() { var sum_odd = 0 var sum_even = 0 for i in 0..<(self.length - 1) { let digit = Int(contents[i])! if i % 2 == (self.length == 13 ? 0 : 1) { sum_even += digit } else { sum_odd += digit } } let checkDigit = (10 - (sum_even + sum_odd * 3) % 10) % 10 return Int(contents[contents.length() - 1]) == checkDigit } return false } override open func initiator() -> String { return "101" } override open func terminator() -> String { return "101" } func centerGuardPattern() -> String { return "01010" } override open func barcode(_ contents: String) -> String { var lefthandParity = "OOOO" var newContents = contents if self.length == 13 { lefthandParity = self.lefthandParities[Int(contents[0])!] newContents = contents.substring(1, length: contents.length() - 1) } var barcode = "" for i in 0..<newContents.length() { let digit = Int(newContents[i])! if i < lefthandParity.length() { barcode += self.parityEncodingTable[digit][lefthandParity[i]]! if i == lefthandParity.length() - 1 { barcode += self.centerGuardPattern() } } else { barcode += self.parityEncodingTable[digit]["R"]! } } return barcode } } @available(macCatalyst 14.0, *) class RSEAN8Generator: RSEANGenerator { init() { super.init(length: 8) } } @available(macCatalyst 14.0, *) class RSEAN13Generator: RSEANGenerator { init() { super.init(length: 13) } } @available(macCatalyst 14.0, *) class RSISBN13Generator: RSEAN13Generator { override func isValid(_ contents: String) -> Bool { // http://www.appsbarcode.com/ISBN.php return super.isValid(contents) && contents.substring(0, length: 3) == "978" } } @available(macCatalyst 14.0, *) class RSISSN13Generator: RSEAN13Generator { override func isValid(_ contents: String) -> Bool { // http://www.appsbarcode.com/ISSN.php return super.isValid(contents) && contents.substring(0, length: 3) == "977" } }
mit
af12904bf82a2b548351f44b135df487
29.143939
83
0.522996
3.487292
false
false
false
false
TouchInstinct/LeadKit
TITransitions/Sources/PanelTransition/Controllers/PanelPresentationController.swift
1
4510
// // Copyright (c) 2020 Touch Instinct // // 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 open class PanelPresentationController: PresentationController { private let config: Configuration private lazy var backView: UIView = { let view = UIView() view.backgroundColor = config.backgroundColor view.alpha = 0 return view }() public init(config: Configuration, driver: TransitionDriver?, presentStyle: PresentStyle, presentedViewController: UIViewController, presenting: UIViewController?) { self.config = config super.init(driver: driver, presentStyle: presentStyle, presentedViewController: presentedViewController, presenting: presenting) if config.onTapDismissEnabled { configureOnTapClose() } } override open func presentationTransitionWillBegin() { super.presentationTransitionWillBegin() containerView?.insertSubview(backView, at: 0) performAlongsideTransitionIfPossible { [weak self] in self?.backView.alpha = 1 } } override open func containerViewDidLayoutSubviews() { super.containerViewDidLayoutSubviews() backView.frame = containerView?.frame ?? .zero } override open func presentationTransitionDidEnd(_ completed: Bool) { super.presentationTransitionDidEnd(completed) if !completed { backView.removeFromSuperview() } } override open func dismissalTransitionWillBegin() { super.dismissalTransitionWillBegin() performAlongsideTransitionIfPossible { [weak self] in self?.backView.alpha = .zero } } override open func dismissalTransitionDidEnd(_ completed: Bool) { super.dismissalTransitionDidEnd(completed) if completed { backView.removeFromSuperview() } } private func configureOnTapClose() { let tapGesture = UITapGestureRecognizer(target: self, action: #selector(onTapClose)) backView.addGestureRecognizer(tapGesture) } @objc private func onTapClose() { presentedViewController.dismiss(animated: true, completion: config.onTapDismissCompletion) } private func performAlongsideTransitionIfPossible(_ block: @escaping () -> Void) { guard let coordinator = presentedViewController.transitionCoordinator else { block() return } coordinator.animate(alongsideTransition: { _ in block() }) } } extension PanelPresentationController { public struct Configuration { public let backgroundColor: UIColor public let onTapDismissEnabled: Bool public let onTapDismissCompletion: VoidClosure? public init(backgroundColor: UIColor = UIColor.black.withAlphaComponent(0.4), onTapDismissEnabled: Bool = true, onTapDismissCompletion: VoidClosure? = nil) { self.backgroundColor = backgroundColor self.onTapDismissEnabled = onTapDismissEnabled self.onTapDismissCompletion = onTapDismissCompletion } public static let `default`: Configuration = .init() } }
apache-2.0
080e89e4b7a98a02224ce4adfc8e1fb7
34.234375
98
0.656541
5.672956
false
true
false
false
hawkfalcon/SpaceEvaders
SpaceEvaders/Alien.swift
1
1394
import SpriteKit class Alien: Sprite { var startAtTop: Bool! var disabled: Bool = false let vel: CGFloat = 4 init(x: CGFloat, y: CGFloat, startAtTop: Bool) { super.init(named: "alien", x: x, y: y) self.startAtTop = startAtTop self.run(SKAction.repeatForever(SKAction.rotate(byAngle: 1, duration: 1))) } func setDisabled() { disabled = true self.texture = SKTexture(imageNamed: "aliendisabled") } func isDisabled() -> Bool { return disabled } func moveTo(point: CGPoint) { let height = parent?.scene?.size.height if height == nil { return } if isDisabled() || position.y > height! - 200 || position.y < 200 { move() } else { var dx = point.x - self.position.x var dy = point.y - self.position.y let mag = sqrt(dx * dx + dy * dy) // Normalize and scale dx = dx / mag * vel dy = dy / mag * vel moveBy(dx: dx, dy: dy) } } func move() { //let dy = startAtTop ? -vel : vel moveBy(dx: 0, dy: vel) } func moveBy(dx: CGFloat, dy: CGFloat) { self.position = CGPoint(x: self.position.x + dx, y: self.position.y + dy) } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } }
mit
acb7944e1748337f1a1a19fe77e8a894
25.301887
82
0.527977
3.788043
false
false
false
false
victorpimentel/SwiftLint
Source/SwiftLintFramework/Rules/ObjectLiteralRule.swift
2
4425
// // ObjectLiteralRule.swift // SwiftLint // // Created by Marcelo Fabri on 12/25/16. // Copyright © 2016 Realm. All rights reserved. // import Foundation import SourceKittenFramework public struct ObjectLiteralRule: ASTRule, ConfigurationProviderRule, OptInRule { public var configuration = SeverityConfiguration(.warning) public init() {} public static let description = RuleDescription( identifier: "object_literal", name: "Object Literal", description: "Prefer object literals over image and color inits.", nonTriggeringExamples: [ "let image = #imageLiteral(resourceName: \"image.jpg\")", "let color = #colorLiteral(red: 0.9607843161, green: 0.7058823705, blue: 0.200000003, alpha: 1)", "let image = UIImage(named: aVariable)", "let image = UIImage(named: \"interpolated \\(variable)\")", "let color = UIColor(red: value, green: value, blue: value, alpha: 1)", "let image = NSImage(named: aVariable)", "let image = NSImage(named: \"interpolated \\(variable)\")", "let color = NSColor(red: value, green: value, blue: value, alpha: 1)" ], triggeringExamples: ["", ".init"].flatMap { (method: String) -> [String] in ["UI", "NS"].flatMap { (prefix: String) -> [String] in [ "let image = ↓\(prefix)Image\(method)(named: \"foo\")", "let color = ↓\(prefix)Color\(method)(red: 0.3, green: 0.3, blue: 0.3, alpha: 1)", "let color = ↓\(prefix)Color\(method)(red: 100 / 255.0, green: 50 / 255.0, blue: 0, alpha: 1)", "let color = ↓\(prefix)Color\(method)(white: 0.5, alpha: 1)" ] } } ) public func validate(file: File, kind: SwiftExpressionKind, dictionary: [String: SourceKitRepresentable]) -> [StyleViolation] { guard kind == .call, let offset = dictionary.offset, isImageNamedInit(dictionary: dictionary, file: file) || isColorInit(dictionary: dictionary, file: file) else { return [] } return [ StyleViolation(ruleDescription: type(of: self).description, severity: configuration.severity, location: Location(file: file, byteOffset: offset)) ] } private func isImageNamedInit(dictionary: [String: SourceKitRepresentable], file: File) -> Bool { guard let name = dictionary.name, inits(forClasses: ["UIImage", "NSImage"]).contains(name), case let arguments = dictionary.enclosedArguments, arguments.flatMap({ $0.name }) == ["named"], let argument = arguments.first, case let kinds = kinds(forArgument: argument, file: file), kinds == [.string] else { return false } return true } private func isColorInit(dictionary: [String: SourceKitRepresentable], file: File) -> Bool { guard let name = dictionary.name, inits(forClasses: ["UIColor", "NSColor"]).contains(name), case let arguments = dictionary.enclosedArguments, case let argumentsNames = arguments.flatMap({ $0.name }), argumentsNames == ["red", "green", "blue", "alpha"] || argumentsNames == ["white", "alpha"], validateColorKinds(arguments: arguments, file: file) else { return false } return true } private func inits(forClasses names: [String]) -> [String] { return names.flatMap { name in [ name, name + ".init" ] } } private func validateColorKinds(arguments: [[String: SourceKitRepresentable]], file: File) -> Bool { for dictionary in arguments where kinds(forArgument: dictionary, file: file) != [.number] { return false } return true } private func kinds(forArgument argument: [String: SourceKitRepresentable], file: File) -> Set<SyntaxKind> { guard let offset = argument.bodyOffset, let length = argument.bodyLength else { return [] } let range = NSRange(location: offset, length: length) return Set(file.syntaxMap.kinds(inByteRange: range)) } }
mit
b7b6e547117172339c146ef50d4fedc7
38.428571
115
0.573143
4.663147
false
false
false
false
SwiftScream/ScreamRefreshControl
Example/ViewController.swift
1
2414
// Copyright 2017 Alex Deem // // 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 UIKit import Dispatch import ScreamRefreshControl class ViewController: UIViewController { private var tableView: UITableView? override func loadView() { let view = UIView(frame: UIScreen.main.bounds) let tableView = UITableView(frame: view.bounds, style: .grouped) tableView.autoresizingMask = [.flexibleWidth, .flexibleHeight] tableView.dataSource = self tableView.delegate = self tableView.register(UITableViewCell.self, forCellReuseIdentifier: "Cell") tableView.refreshControl = ModernRefreshControl() tableView.refreshControl?.addTarget(self, action: #selector(ViewController.didPullToRefresh), for: .valueChanged) self.tableView = tableView view.addSubview(tableView) self.view = view } @objc func didPullToRefresh() { let duration = DispatchTimeInterval.milliseconds(Int(arc4random_uniform(4000))) DispatchQueue.main.asyncAfter(deadline: .now() + duration) { self.tableView?.refreshControl?.endRefreshing() } } override func viewDidLoad() { super.viewDidLoad() } } extension ViewController : UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return 20 } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) cell.textLabel?.text = "Cell \(indexPath.row)" return cell } } extension ViewController : UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.refreshControl?.beginRefreshing() self.didPullToRefresh() } }
apache-2.0
80b18d993c5cec3b34b93e7c978a177d
35.029851
121
0.703397
4.916497
false
false
false
false
omochi/numsw
Sources/numsw/NDArray/NDArrayUtils.swift
1
3752
func apply<T, R>(_ arg: NDArray<T>, _ handler: (T)->R) -> NDArray<R> { var inPointer = UnsafePointer(arg.elements) let outPointer = UnsafeMutablePointer<R>.allocate(capacity: arg.elements.count) defer { outPointer.deallocate(capacity: arg.elements.count) } var p = outPointer for _ in 0..<arg.elements.count { p.pointee = handler(inPointer.pointee) p += 1 inPointer += 1 } return NDArray(shape: arg.shape, elements: Array(UnsafeBufferPointer(start: outPointer, count: arg.elements.count))) } func combine<T, U, R>(_ lhs: NDArray<T>, _ rhs: NDArray<U>, _ handler: (T, U) -> R) -> NDArray<R> { precondition(lhs.shape==rhs.shape, "Two NDArrays have incompatible shape.") var lhsPointer = UnsafePointer(lhs.elements) var rhsPointer = UnsafePointer(rhs.elements) let outPointer = UnsafeMutablePointer<R>.allocate(capacity: lhs.elements.count) defer { outPointer.deallocate(capacity: lhs.elements.count) } var p = outPointer for _ in 0..<rhs.elements.count { p.pointee = handler(lhsPointer.pointee, rhsPointer.pointee) p += 1 lhsPointer += 1 rhsPointer += 1 } return NDArray(shape: lhs.shape, elements: Array(UnsafeBufferPointer(start: outPointer, count: lhs.elements.count))) } // index calculation func calculateIndex(_ shape: [Int], _ index: [Int]) -> Int { /* calculate index in elelemnts from index in NDArray * * example: * - arguments: * + array.shape = [3, 4, 5] * + index = [1, 2, 3] * - return: * + ((3)*4+2)*5+3 = 73 */ precondition(index.count == shape.count, "Invalid index.") // minus index var index = index for i in 0..<index.count { precondition(-shape[i] <= index[i] && index[i] < shape[i], "Invalid index.") if index[i] < 0 { index[i] += shape[i] } } // calculate let elementIndex = zip(index, Array(shape.dropFirst()) + [1]).reduce(0) { acc, x in return (acc + x.0) * x.1 } return elementIndex } func calculateIndices(_ indicesInAxes: [[Int]]) -> [[Int]] { /* calculate indices in NDArray from indices in axes * * example: * - arguments: * + array.shape = [3, 4, 5] * + indices = [[1, 2], [2, 3], [3]] * - return: * + [[1, 2, 3], [1, 3, 3], [2, 2, 3], [2, 3, 3]] */ guard indicesInAxes.count > 0 else { return [[]] } let head = indicesInAxes[0] let tail = Array(indicesInAxes.dropFirst()) let appended = head.flatMap { h -> [[Int]] in calculateIndices(tail).map { list in [h] + list } } return appended } func formatIndicesInAxes(_ shape: [Int], _ indicesInAxes: [[Int]?]) -> [[Int]] { /* Format subarray's indices * - fulfill shortage * - nil turns into full indices * * example: * - arguments: * + array.shape = [3, 4, 5] * + indices = [[1, 2], [2, 3]] * - return: * + [[1, 2], [2, 3], [0, 1, 2, 3, 4]] */ var padIndices = indicesInAxes if padIndices.count < shape.count { padIndices = indicesInAxes + [[Int]?](repeating: nil, count: shape.count - padIndices.count) } let indices = padIndices.enumerated().map { i, indexArray in indexArray ?? Array(0..<shape[i]) } return indices } extension Array { func removed(at index: Int) -> Array { var array = self array.remove(at: index) return array } func replaced(with newElement: Element, at index: Int) -> Array { var array = self array[index] = newElement return array } }
mit
c625a2feab7aeb342fef8684b9097aea
28.543307
102
0.561834
3.586998
false
false
false
false
itaen/30DaysSwift
006_iLocation/iLocation/iLocation/ViewController.swift
1
2849
// // ViewController.swift // iLocation // // Created by itaen on 25/07/2017. // Copyright © 2017 itaen. All rights reserved. // import UIKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } var locationManager: CLLocationManager! @IBOutlet weak var locationLabel: UILabel! @IBOutlet weak var findButton: UIButton! @IBAction func findMyLocationPressed(_ sender:UIButton!) { locationManager = CLLocationManager() locationManager.delegate = self locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.requestAlwaysAuthorization() locationManager.startUpdatingLocation() } //MARK: CLLocationManagerDelegate func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { locationLabel.text = "更新位置出错" + error.localizedDescription } func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { CLGeocoder().reverseGeocodeLocation(manager.location!) { (placemarks, error) in if (error != nil) { self.locationLabel.text = "更新位置出错" + error!.localizedDescription return } if placemarks!.count > 0 { let pm = placemarks![0] self.displayLocationInfo(pm) } else { self.locationLabel.text = "位置数据有误" } } } private func displayLocationInfo(_ placemark: CLPlacemark?) { if let containsPlacemark = placemark { locationManager.startUpdatingLocation() let subThoroughfare = (containsPlacemark.subThoroughfare != nil) ? containsPlacemark.subThoroughfare : "" let thoroughfare = (containsPlacemark.thoroughfare != nil) ? containsPlacemark.thoroughfare : "" let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : "" let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : "" let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : "" let country = (containsPlacemark.country != nil) ? containsPlacemark.country : "" locationLabel.text = postalCode! + "" + locality! + "" + thoroughfare! + "" + subThoroughfare! locationLabel.text?.append("\n" + administrativeArea! + "," + country!) } } }
mit
3814625340262e3af3f57b46e44e696a
39.171429
126
0.653627
5.635271
false
false
false
false
SusanDoggie/Doggie
Sources/DoggieGraphics/Font/Font.swift
1
19745
// // Font.swift // // The MIT License // Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved. // // 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. // protocol FontFaceBase { var table: [Signature<BEUInt32>: Data] { get } var isVariationSelectors: Bool { get } var isGraphic: Bool { get } func shape(forGlyph glyph: Int) -> [Shape.Component] func graphic(forGlyph glyph: Int) -> [Font.Graphic]? func glyph(with unicode: UnicodeScalar) -> Int func glyph(with unicode: UnicodeScalar, _ uvs: UnicodeScalar) -> Int? func substitution(glyphs: [Int], layout: Font.LayoutSetting, features: [FontFeature: Int]) -> [Int] func availableFeatures() -> Set<FontFeature> func metric(glyph: Int) -> Font.Metric func verticalMetric(glyph: Int) -> Font.Metric var isVertical: Bool { get } var numberOfGlyphs: Int { get } var coveredCharacterSet: CharacterSet { get } var ascender: Double { get } var descender: Double { get } var lineGap: Double { get } var verticalAscender: Double? { get } var verticalDescender: Double? { get } var verticalLineGap: Double? { get } var unitsPerEm: Double { get } var boundingRectForFont: Rect { get } var italicAngle: Double { get } var weight: Int? { get } var stretch: Int? { get } var xHeight: Double? { get } var capHeight: Double? { get } var isFixedPitch: Bool { get } var isItalic: Bool { get } var isBold: Bool { get } var isExpanded: Bool { get } var isCondensed: Bool { get } var strikeoutPosition: Double? { get } var strikeoutThickness: Double? { get } var underlinePosition: Double { get } var underlineThickness: Double { get } var fontName: String? { get } var displayName: String? { get } var uniqueName: String? { get } var familyName: String? { get } var faceName: String? { get } var familyClass: Font.FamilyClass? { get } var names: Set<Int> { get } var languages: Set<String> { get } func queryName(_ id: Int, _ language: String?) -> String? } public struct Font { private let details: Details private let base: FontFaceBase public var pointSize: Double public var features: [FontFeature: Int] private let cache: Cache init?(_ base: FontFaceBase) { guard base.numberOfGlyphs > 0 else { return nil } guard let details = Details(base) else { return nil } self.details = details self.base = base self.pointSize = 0 self.features = [:] self.cache = Cache() } public init(font: Font, size: Double, features: [FontFeature: Int] = [:]) { self.details = font.details self.base = font.base self.pointSize = size self.features = features self.cache = font.cache } } extension Font: Hashable { public func hash(into hasher: inout Hasher) { hasher.combine(pointSize) hasher.combine(features) hasher.combine(fontName) } public static func ==(lhs: Font, rhs: Font) -> Bool { return lhs.pointSize == rhs.pointSize && lhs.features == rhs.features && lhs.fontName == rhs.fontName } } extension Font { private class Cache { let lck = NSLock() var coveredCharacterSet: CharacterSet? var glyphs: [Int: [Shape.Component]] = [:] } public func clearCaches() { cache.lck.synchronized { cache.coveredCharacterSet = nil cache.glyphs = [:] } } } extension Font { private struct Details { let fontName: String let displayName: String? let uniqueName: String? let familyName: String? let faceName: String? let familyClass: FamilyClass? init?(_ base: FontFaceBase) { guard let fontName = base.fontName else { return nil } self.fontName = fontName self.displayName = base.displayName self.uniqueName = base.uniqueName self.familyName = base.familyName self.faceName = base.faceName self.familyClass = base.familyClass } } } extension Font { public enum FamilyClass: CaseIterable { case oldStyleSerifs case transitionalSerifs case modernSerifs case clarendonSerifs case slabSerifs case freeformSerifs case sansSerif case ornamentals case scripts case symbolic } } extension Font: CustomStringConvertible { public var description: String { return "Font(name: \(self.fontName), pointSize: \(self.pointSize))" } } extension Font { public enum PropertyKey: CaseIterable { case deflateLevel } public func representation(using storageType: MediaType, properties: [PropertyKey: Any]) -> Data? { let Encoder: FontFaceEncoder.Type switch storageType { case .ttf, .otf: Encoder = OTFEncoder.self case .woff: Encoder = WOFFEncoder.self default: return nil } return Encoder.encode(table: base.table, properties: properties) } } extension Font { public func with(size pointSize: Double) -> Font { return Font(font: self, size: pointSize, features: features) } public func with(features: [FontFeature: Int]) -> Font { return Font(font: self, size: pointSize, features: features) } public func with(size pointSize: Double, features: [FontFeature: Int]) -> Font { return Font(font: self, size: pointSize, features: features) } } extension Font { @frozen public struct GraphicType: SignatureProtocol { public var rawValue: BEUInt32 public init(rawValue: BEUInt32) { self.rawValue = rawValue } public static let jpeg: GraphicType = "jpg " public static let png: GraphicType = "png " public static let tiff: GraphicType = "tiff" public static let pdf: GraphicType = "pdf " public static let svg: GraphicType = "svg " } public struct Graphic { public var type: GraphicType public var unitsPerEm: Double public var resolution: Double public var origin: Point public var data: Data } private func _shape(glyph: Int) -> [Shape.Component] { let glyph = 0..<base.numberOfGlyphs ~= glyph ? glyph : 0 return cache.lck.synchronized { if cache.glyphs[glyph] == nil { cache.glyphs[glyph] = base.shape(forGlyph: glyph).filter { !$0.isEmpty } } return cache.glyphs[glyph]! } } public func shape(forGlyph glyph: Int) -> Shape { return Shape(self._shape(glyph: glyph).map { $0 * SDTransform.scale(_pointScale) }) } public func graphic(forGlyph glyph: Int) -> [Font.Graphic]? { let glyph = 0..<base.numberOfGlyphs ~= glyph ? glyph : 0 return base.graphic(forGlyph: glyph) } } protocol FontFeatureBase: Hashable, CustomStringConvertible { var defaultSetting: Int { get } var availableSettings: Set<Int> { get } func name(for setting: Int) -> String? } public struct FontFeature: Hashable, CustomStringConvertible { var base: any FontFeatureBase init(_ base: any FontFeatureBase) { self.base = base } public var defaultSetting: Int { return base.defaultSetting } public var availableSettings: Set<Int> { return base.availableSettings } public var description: String { return base.description } public func name(for setting: Int) -> String? { return base.name(for: setting) } } extension FontFeature { public func hash(into hasher: inout Hasher) { base.hash(into: &hasher) } public static func ==(lhs: FontFeature, rhs: FontFeature) -> Bool { return lhs.base._equalTo(rhs.base) } } extension Font { public func availableFeatures() -> Set<FontFeature> { return base.availableFeatures() } } extension Font { public enum LayoutDirection: CaseIterable { case leftToRight case rightToLeft } public struct LayoutSetting { public var direction: LayoutDirection public var isVertical: Bool public init(direction: LayoutDirection = .leftToRight, vertical: Bool = false) { self.direction = direction self.isVertical = vertical } } public var numberOfGlyphs: Int { return base.numberOfGlyphs } public func glyph(with unicode: UnicodeScalar) -> Int { return base.glyph(with: unicode) } public func glyphs<S: Sequence>(with unicodes: S, layout: LayoutSetting = LayoutSetting()) -> [Int] where S.Element == UnicodeScalar { var result: [Int] = [] if base.isVariationSelectors { result.reserveCapacity(unicodes.underestimatedCount) var last: UnicodeScalar? for unicode in unicodes { if let _last = last { if let glyph = base.glyph(with: _last, unicode) { result.append(glyph) last = nil } else { result.append(base.glyph(with: _last)) last = unicode } } else { last = unicode } } if let last = last { result.append(base.glyph(with: last)) } } else { result = unicodes.map { base.glyph(with: $0) } } return base.substitution(glyphs: result, layout: layout, features: features) } public func glyphs<S: StringProtocol>(with string: S, layout: LayoutSetting = LayoutSetting()) -> [Int] { return self.glyphs(with: string.unicodeScalars, layout: layout) } } extension Font { public struct Metric { public var advance: Double public var bearing: Double } public func metric(forGlyph glyph: Int) -> Metric { let glyph = 0..<base.numberOfGlyphs ~= glyph ? glyph : 0 let metric = base.metric(glyph: glyph) return Metric(advance: metric.advance * _pointScale, bearing: metric.bearing * _pointScale) } public func verticalMetric(forGlyph glyph: Int) -> Metric { let glyph = 0..<base.numberOfGlyphs ~= glyph ? glyph : 0 let metric = base.verticalMetric(glyph: glyph) return Metric(advance: metric.advance * _pointScale, bearing: metric.bearing * _pointScale) } public func advance(forGlyph glyph: Int) -> Double { return metric(forGlyph: glyph).advance } public func verticalAdvance(forGlyph glyph: Int) -> Double { return verticalMetric(forGlyph: glyph).advance } public func bearing(forGlyph glyph: Int) -> Double { return metric(forGlyph: glyph).bearing } public func verticalBearing(forGlyph glyph: Int) -> Double { return verticalMetric(forGlyph: glyph).bearing } public var coveredCharacterSet: CharacterSet { return cache.lck.synchronized { if cache.coveredCharacterSet == nil { cache.coveredCharacterSet = base.coveredCharacterSet } return cache.coveredCharacterSet! } } } extension Font { private var _pointScale: Double { return pointSize / unitsPerEm } public var isVariationSelectors: Bool { return base.isVariationSelectors } public var isGraphic: Bool { return base.isGraphic } public var ascender: Double { return base.ascender * _pointScale } public var descender: Double { return base.descender * _pointScale } public var lineGap: Double { return base.lineGap * _pointScale } public var verticalAscender: Double? { return base.verticalAscender.map { $0 * _pointScale } } public var verticalDescender: Double? { return base.verticalDescender.map { $0 * _pointScale } } public var verticalLineGap: Double? { return base.verticalLineGap.map { $0 * _pointScale } } public var unitsPerEm: Double { return base.unitsPerEm } public var boundingRectForFont: Rect { let _pointScale = self._pointScale let bound = base.boundingRectForFont return bound * _pointScale } public var italicAngle: Double { return base.italicAngle } public var weight: Int? { return base.weight } public var stretch: Int? { return base.stretch } public var xHeight: Double? { return base.xHeight.map { $0 * _pointScale } } public var capHeight: Double? { return base.capHeight.map { $0 * _pointScale } } public var isVertical: Bool { return base.isVertical } public var isFixedPitch: Bool { return base.isFixedPitch } public var isItalic: Bool { return base.isItalic } public var isBold: Bool { return base.isBold } public var isExpanded: Bool { return base.isExpanded } public var isCondensed: Bool { return base.isCondensed } public var strikeoutPosition: Double? { return base.strikeoutPosition.map { $0 * _pointScale } } public var strikeoutThickness: Double? { return base.strikeoutThickness.map { $0 * _pointScale } } public var underlinePosition: Double { return base.underlinePosition * _pointScale } public var underlineThickness: Double { return base.underlineThickness * _pointScale } } extension Font { public var fontName: String { return details.fontName } public var displayName: String? { return details.displayName } public var uniqueName: String? { return details.uniqueName } public var familyName: String? { return details.familyName } public var faceName: String? { return details.faceName } public var familyClass: FamilyClass? { return details.familyClass } } extension Font { @frozen public struct Name: RawRepresentable, Hashable { public var rawValue: Int @inlinable public init(rawValue: Int) { self.rawValue = rawValue } public static var copyright = Font.Name(rawValue: 0) public static var familyName = Font.Name(rawValue: 1) public static var faceName = Font.Name(rawValue: 2) public static var uniqueName = Font.Name(rawValue: 3) public static var displayName = Font.Name(rawValue: 4) public static var version = Font.Name(rawValue: 5) public static var fontName = Font.Name(rawValue: 6) public static var trademark = Font.Name(rawValue: 7) public static var manufacturer = Font.Name(rawValue: 8) public static var designer = Font.Name(rawValue: 9) public static var license = Font.Name(rawValue: 13) public static var preferredFamilyName = Font.Name(rawValue: 16) public static var preferredFaceName = Font.Name(rawValue: 17) } public var names: Set<Name> { return Set(base.names.map { Name(rawValue: $0) }) } public var languages: Set<String> { return base.languages } public func queryName(for name: Font.Name, language: String? = nil) -> String? { return base.queryName(name.rawValue, language) } public var designer: String? { return self.queryName(for: .designer) } public var version: String? { return self.queryName(for: .version) } public var trademark: String? { return self.queryName(for: .trademark) } public var manufacturer: String? { return self.queryName(for: .manufacturer) } public var license: String? { return self.queryName(for: .license) } public var copyright: String? { return self.queryName(for: .copyright) } } extension Font { public func localizedName(for name: Font.Name) -> String? { let locales = Locale.preferredLanguages.map { Locale(identifier: $0) } for locale in locales { guard let languageCode = locale.languageCode else { continue } let scriptCode = locale.scriptCode let regionCode = locale.regionCode if let scriptCode = scriptCode, let regionCode = regionCode, let string = self.queryName(for: name, language: "\(languageCode)-\(scriptCode)_\(regionCode)") { return string } if let regionCode = regionCode, let string = self.queryName(for: name, language: "\(languageCode)_\(regionCode)") { return string } if let scriptCode = scriptCode, let string = self.queryName(for: name, language: "\(languageCode)-\(scriptCode)") { return string } if let string = self.queryName(for: name, language: languageCode) { return string } } return nil } public var localizedFamilyName: String? { return self.localizedName(for: .preferredFamilyName) ?? self.queryName(for: .preferredFamilyName) ?? self.localizedName(for: .familyName) ?? self.queryName(for: .familyName) } public var localizedFaceName: String? { return self.localizedName(for: .preferredFaceName) ?? self.queryName(for: .preferredFaceName) ?? self.localizedName(for: .faceName) ?? self.queryName(for: .faceName) } public var localizedDisplayName: String? { return self.localizedName(for: .displayName) ?? self.displayName } }
mit
2c43b707df390db57d2f02f8f9aaebb0
28.470149
170
0.595341
4.584397
false
false
false
false
hackstock/instagram_clone
Instagram Clone/Instagram Clone/UILoginViewController.swift
1
3386
// // UILoginViewController.swift // Instagram Clone // // Created by Edward Pie on 26/01/2017. // Copyright © 2017 Hubtel. All rights reserved. // import UIKit class UILoginViewController: UIViewController, UIWebViewDelegate { var activityIndicator: UIActivityIndicatorView! var hasFinishedAuthorization = false let webView: UIWebView = { let webView = UIWebView() webView.translatesAutoresizingMaskIntoConstraints = false return webView }() override func viewDidLoad() { super.viewDidLoad() self.initializeViews() self.applyLayoutConstraints() self.loadInstagramLoginPage() } func initializeViews(){ self.webView.delegate = self self.activityIndicator = UIActivityIndicatorView() self.activityIndicator.center = self.view.center self.activityIndicator.hidesWhenStopped = true self.activityIndicator.activityIndicatorViewStyle = .gray } func applyLayoutConstraints(){ self.view.addSubview(self.webView) self.webView.anchorToTop(top: view.topAnchor, left: view.leftAnchor, bottom: view.bottomAnchor, right: view.rightAnchor) } func loadInstagramLoginPage(){ let clientId = AppConfig.TargetApiEnvironment.getEnvironmentConfiguration().clientID let redirectUrl = AppConfig.TargetApiEnvironment.getEnvironmentConfiguration().redirectUrl let authenticationUrl = "https://api.instagram.com/oauth/authorize/?client_id=\(clientId)&redirect_uri=\(redirectUrl)&response_type=token" self.webView.loadRequest(URLRequest(url: URL(string: authenticationUrl)!)) } func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { let urlString = request.url?.absoluteString var urlComponents = urlString?.components(separatedBy: "#") if (urlComponents?.count)! > 1{ self.hasFinishedAuthorization = true let accessToken = urlComponents?[1].components(separatedBy: "=")[1] AppConfig.storeAccessToken(token: accessToken!) } return true } func webViewDidStartLoad(_ webView: UIWebView) { self.view.addSubview(self.activityIndicator) self.activityIndicator.startAnimating() UIApplication.shared.beginIgnoringInteractionEvents() } func webViewDidFinishLoad(_ webView: UIWebView) { self.activityIndicator.stopAnimating() UIApplication.shared.endIgnoringInteractionEvents() if(self.hasFinishedAuthorization){ self.present(UINavigationController(rootViewController: UIDashboardViewController()), animated: true, completion: nil) } } 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
6279db0d574ff3d1542440145fccbe8d
32.85
146
0.677696
5.604305
false
false
false
false
izrie/DKImagePickerController
DKImagePickerController/DKImagePickerController.swift
1
9088
// // DKImagePickerController.swift // DKImagePickerController // // Created by ZhangAo on 14-10-2. // Copyright (c) 2014年 ZhangAo. All rights reserved. // import UIKit import AssetsLibrary // MARK: - Public DKAsset /** * An `DKAsset` object represents a photo or a video managed by the `DKImagePickerController`. */ public class DKAsset: NSObject { /// Returns a CGImage of the representation that is appropriate for displaying full screen. public private(set) lazy var fullScreenImage: UIImage? = { return UIImage(CGImage: (self.originalAsset?.defaultRepresentation().fullScreenImage().takeUnretainedValue())!) }() /// Returns a CGImage representation of the asset. public private(set) lazy var fullResolutionImage: UIImage? = { return UIImage(CGImage: (self.originalAsset?.defaultRepresentation().fullResolutionImage().takeUnretainedValue())!) }() /// The url uniquely identifies an asset that is an image or a video. public private(set) var url: NSURL? /// It's a square thumbnail of the asset. public private(set) var thumbnailImage: UIImage? /// When the asset was an image, it's false. Otherwise true. public private(set) var isVideo: Bool = false /// play time duration(seconds) of a video. public private(set) var duration: Double? internal var isFromCamera: Bool = false internal var originalAsset: ALAsset? internal init(originalAsset: ALAsset) { super.init() self.thumbnailImage = UIImage(CGImage:originalAsset.thumbnail().takeUnretainedValue()) self.url = originalAsset.valueForProperty(ALAssetPropertyAssetURL) as? NSURL self.originalAsset = originalAsset let assetType = originalAsset.valueForProperty(ALAssetPropertyType) as! NSString if assetType == ALAssetTypeVideo { let duration = originalAsset.valueForProperty(ALAssetPropertyDuration) as! NSNumber self.isVideo = true self.duration = duration.doubleValue } } internal init(image: UIImage) { super.init() self.isFromCamera = true self.fullScreenImage = image self.fullResolutionImage = image self.thumbnailImage = image } // Compare two DKAssets override public func isEqual(object: AnyObject?) -> Bool { let another = object as! DKAsset! if let url = self.url, anotherUrl = another.url { return url.isEqual(anotherUrl) } else { return false } } } /** * allPhotos: Get all photos assets in the assets group. * allVideos: Get all video assets in the assets group. * allAssets: Get all assets in the group. */ public enum DKImagePickerControllerAssetType : Int { case allPhotos, allVideos, allAssets } public struct DKImagePickerControllerSourceType : OptionSetType { private var value: UInt = 0 init(_ value: UInt) { self.value = value } // MARK: _RawOptionSetType public init(rawValue value: UInt) { self.value = value } // MARK: NilLiteralConvertible public init(nilLiteral: ()) { self.value = 0 } // MARK: RawRepresentable public var rawValue: UInt { return self.value } // MARK: BitwiseOperationsType public static var allZeros: DKImagePickerControllerSourceType { return self.init(0) } public static var Camera: DKImagePickerControllerSourceType { return self.init(1 << 0) } public static var Photo: DKImagePickerControllerSourceType { return self.init(1 << 1) } } // MARK: - Public DKImagePickerController /** * The `DKImagePickerController` class offers the all public APIs which will affect the UI. */ public class DKImagePickerController: UINavigationController { /// Forces selction of tapped image immediatly public var singleSelect = false /// The maximum count of assets which the user will be able to select. public var maxSelectableCount = 999 // The types of ALAssetsGroups to display in the picker public var assetGroupTypes: UInt32 = ALAssetsGroupAll /// The type of picker interface to be displayed by the controller. public var assetType = DKImagePickerControllerAssetType.allAssets /// If sourceType is Camera will cause the assetType & maxSelectableCount & allowMultipleTypes & defaultSelectedAssets to be ignored. public var sourceType: DKImagePickerControllerSourceType = [.Camera, .Photo] /// Whether allows to select photos and videos at the same time. public var allowMultipleTypes = true /// The callback block is executed when user pressed the select button. public var didSelectAssets: ((assets: [DKAsset]) -> Void)? /// The callback block is executed when user pressed the cancel button. public var didCancel: (() -> Void)? /// It will have selected the specific assets. public var defaultSelectedAssets: [DKAsset]? { didSet { if let defaultSelectedAssets = self.defaultSelectedAssets { for (index, asset) in defaultSelectedAssets.enumerate() { if asset.isFromCamera { self.defaultSelectedAssets!.removeAtIndex(index) } } self.selectedAssets = defaultSelectedAssets self.updateDoneButtonTitle() } } } internal var selectedAssets = [DKAsset]() private lazy var doneButton: UIButton = { let button = UIButton(type: UIButtonType.Custom) button.setTitle("", forState: UIControlState.Normal) button.setTitleColor(self.navigationBar.tintColor, forState: UIControlState.Normal) button.reversesTitleShadowWhenHighlighted = true button.addTarget(self, action: "done", forControlEvents: UIControlEvents.TouchUpInside) return button }() public convenience init() { let rootVC = DKAssetGroupDetailVC() self.init(rootViewController: rootVC) rootVC.navigationItem.rightBarButtonItem = UIBarButtonItem(customView: self.doneButton) rootVC.navigationItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Cancel, target: self, action: "dismiss") } deinit { NSNotificationCenter.defaultCenter().removeObserver(self) } override public func viewDidLoad() { super.viewDidLoad() NSNotificationCenter.defaultCenter().addObserver(self, selector: "selectedImage:", name: DKImageSelectedNotification, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "unselectedImage:", name: DKImageUnselectedNotification, object: nil) } private func updateDoneButtonTitle() { if self.selectedAssets.count > 0 { self.doneButton.setTitle(DKImageLocalizedString.localizedStringForKey("select") + "(\(selectedAssets.count))", forState: UIControlState.Normal) } else { self.doneButton.setTitle("", forState: UIControlState.Normal) } self.doneButton.sizeToFit() } internal func dismiss() { self.dismissViewControllerAnimated(true, completion: nil) self.didCancel?() } internal func done() { self.dismissViewControllerAnimated(true, completion: nil) self.didSelectAssets?(assets: self.selectedAssets) } // MARK: - Notifications internal func selectedImage(noti: NSNotification) { if let asset = noti.object as? DKAsset { selectedAssets.append(asset) if asset.isFromCamera { self.done() } else if self.singleSelect { self.done() } else { updateDoneButtonTitle() } } } internal func unselectedImage(noti: NSNotification) { if let asset = noti.object as? DKAsset { selectedAssets.removeAtIndex(selectedAssets.indexOf(asset)!) updateDoneButtonTitle() } } // MARK: - Handles Orientation public override func shouldAutorotate() -> Bool { return false } public override func supportedInterfaceOrientations() -> UIInterfaceOrientationMask { return UIInterfaceOrientationMask.Portrait } } // MARK: - Utilities internal extension UIViewController { var imagePickerController: DKImagePickerController? { get { let nav = self.navigationController if nav is DKImagePickerController { return nav as? DKImagePickerController } else { return nil } } } }
mit
fbd3279b11f4e62e924fc9594aa16e2d
33.812261
155
0.635153
5.563993
false
false
false
false
goblinr/omim
iphone/Maps/Core/Ads/Google/GoogleFallbackBanner.swift
7
4791
import GoogleMobileAds @objc(MWMGoogleFallbackBannerDynamicSizeDelegate) protocol GoogleFallbackBannerDynamicSizeDelegate { func dynamicSizeUpdated(banner: GoogleFallbackBanner) } @objc(MWMGoogleFallbackBanner) final class GoogleFallbackBanner: GADSearchBannerView, Banner { private enum Limits { static let minTimeSinceLastRequest: TimeInterval = 5 } fileprivate var success: Banner.Success! fileprivate var failure: Banner.Failure! fileprivate var click: Banner.Click! private var requestDate: Date? var isBannerOnScreen: Bool = false var isNeedToRetain: Bool { return true } var isPossibleToReload: Bool { if let date = requestDate { return Date().timeIntervalSince(date) > Limits.minTimeSinceLastRequest } return true } var type: BannerType { return .google(bannerID, query) } var mwmType: MWMBannerType { return type.mwmType } var bannerID: String! { return adUnitID } var statisticsDescription: [String: String] { return [kStatBanner: bannerID, kStatProvider: kStatGoogle] } let query: String @objc var dynamicSizeDelegate: GoogleFallbackBannerDynamicSizeDelegate? fileprivate(set) var dynamicSize = CGSize.zero { didSet { dynamicSizeDelegate?.dynamicSizeUpdated(banner: self) } } @objc var cellIndexPath: IndexPath! init(bannerID: String, query: String) { self.query = query super.init(adSize: kGADAdSizeFluid) adUnitID = bannerID frame = CGRect.zero delegate = self adSizeDelegate = self } required init?(coder _: NSCoder) { fatalError("init(coder:) has not been implemented") } func reload(success: @escaping Success, failure: @escaping Failure, click: @escaping Click) { self.success = success self.failure = failure self.click = click let searchRequest = GADDynamicHeightSearchRequest() searchRequest.query = query searchRequest.numberOfAds = 1 if let loc = MWMLocationManager.lastLocation() { searchRequest.setLocationWithLatitude(CGFloat(loc.coordinate.latitude), longitude: CGFloat(loc.coordinate.longitude), accuracy: CGFloat(loc.horizontalAccuracy)) } searchRequest.cssWidth = "100%" let isNightMode = UIColor.isNightMode() searchRequest.adBorderCSSSelections = "bottom" searchRequest.adBorderColor = isNightMode ? "#53575A" : "#E0E0E0" searchRequest.adjustableLineHeight = 18 searchRequest.annotationFontSize = 12 searchRequest.annotationTextColor = isNightMode ? "#C8C9CA" : "#75726D" searchRequest.attributionBottomSpacing = 4 searchRequest.attributionFontSize = 12 searchRequest.attributionTextColor = isNightMode ? "#C8C9CA" : "#75726D" searchRequest.backgroundColor = isNightMode ? "#484B50" : "#FFF9EF" searchRequest.boldTitleEnabled = true searchRequest.clickToCallExtensionEnabled = true searchRequest.descriptionFontSize = 12 searchRequest.domainLinkColor = isNightMode ? "#51B5E6" : "#1E96F0" searchRequest.domainLinkFontSize = 12 searchRequest.locationExtensionEnabled = true searchRequest.locationExtensionFontSize = 12 searchRequest.locationExtensionTextColor = isNightMode ? "#C8C9CA" : "#75726D" searchRequest.sellerRatingsExtensionEnabled = false searchRequest.siteLinksExtensionEnabled = false searchRequest.textColor = isNightMode ? "#C8C9CA" : "#75726D" searchRequest.titleFontSize = 12 searchRequest.titleLinkColor = isNightMode ? "#FFFFFF" : "#21201E" searchRequest.titleUnderlineHidden = true load(searchRequest) requestDate = Date() } func unregister() {} static func ==(lhs: GoogleFallbackBanner, rhs: GoogleFallbackBanner) -> Bool { return lhs.adUnitID == rhs.adUnitID && lhs.query == rhs.query } } extension GoogleFallbackBanner: GADBannerViewDelegate { func adViewDidReceiveAd(_ bannerView: GADBannerView) { guard let banner = bannerView as? GoogleFallbackBanner, banner == self else { return } success(self) } func adView(_ bannerView: GADBannerView, didFailToReceiveAdWithError error: GADRequestError) { guard let banner = bannerView as? GoogleFallbackBanner, banner == self else { return } var params: [String: Any] = statisticsDescription params[kStatErrorCode] = error.code failure(type, kStatPlacePageBannerError, params, error) } func adViewWillPresentScreen(_: GADBannerView) { click(self) } func adViewWillLeaveApplication(_: GADBannerView) { click(self) } } extension GoogleFallbackBanner: GADAdSizeDelegate { func adView(_: GADBannerView, willChangeAdSizeTo size: GADAdSize) { var newFrame = frame newFrame.size.height = size.size.height frame = newFrame dynamicSize = size.size } }
apache-2.0
0554f59605d1c5c29c4ffd95f54d939f
33.970803
96
0.728032
4.427911
false
false
false
false
roelspruit/RSMetronome
Sources/RSMetronome/PatternPlayer.swift
1
2393
// // PatternPlayer.swift // RSMetronomeExample // // Created by Roel Spruit on 03/12/15. // Copyright © 2015 DinkyWonder. All rights reserved. // import Foundation class PatternPlayer { var settings = Settings() var soundSet: SoundSet private var iterator = -1 var beatListener: ((_ beatType: BeatType, _ index: Int) -> ())? var stateListener: ((_ playing: Bool) -> ())? private var thread: Thread? init(settings: Settings, soundSet: SoundSet){ self.settings = settings self.soundSet = soundSet } func play(){ thread = Thread(target: self, selector: #selector(loop), object: nil) thread?.start() notifyStateListener() } func stop(){ thread?.cancel() thread = nil notifyStateListener() } var isPlaying: Bool { if let t = thread { return !t.isCancelled } return false } private func notifyStateListener(){ if let listener = stateListener { listener(isPlaying) } } private func nextElement() -> PlayableElement? { iterator += 1 if iterator >= settings.pattern.elements.count { iterator = 0 } return settings.pattern.elements[iterator] } @objc private func loop() { while(true && !Thread.current.isCancelled) { guard let element = nextElement() else{ stop() continue } if element is Note && settings.audioEnabled { playElement(element: element) } if let listener = beatListener { listener(element.beatType, iterator) } waitForElement(element: element) } Thread.exit() } private func playElement(element: PlayableElement){ soundSet.soundForBeatType(beatType: element.beatType).play() } private func waitForElement(element: PlayableElement){ let timeInterval = element.value.timeIntervalWithTempo(tempo: settings.tempo, tempoNote: settings.tempoNote) mach_wait_until(mach_absolute_time() + timeInterval) } }
mit
fef3a578d3b1be822553d7000c53d2ee
22.92
116
0.534699
4.952381
false
false
false
false
teamVCH/sway
sway/TabBarController.swift
1
3664
// // TabBarController.swift // sway // // Created by Hina Sakazaki on 10/17/15. // Copyright © 2015 VCH. All rights reserved. // import UIKit let recordTabTitle = "Record" let recordModalSegue = "RecordModalSegue" let savedDraft = "savedDraft" let publishedTune = "publishedTune" let loggedOut = "loggedOut" class TabBarController: UITabBarController, UITabBarControllerDelegate { var lastIndex = 0 override func viewDidLoad() { super.viewDidLoad() delegate = self NSNotificationCenter.defaultCenter().addObserver(self, selector: "onSavedDraft", name: savedDraft, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "onPublishedTune:", name: publishedTune, object: nil) NSNotificationCenter.defaultCenter().addObserver(self, selector: "logout", name: loggedOut, object: nil) for tabBarItem in self.tabBar.items! { tabBarItem.image = tabBarItem.image!.imageWithRenderingMode(.AlwaysOriginal) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } /* override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) { if (item.title == recordTabTitle) { performSegueWithIdentifier(recordModalSegue, sender: nil) } else { lastIndex = selectedIndex } } */ func tabBarController(tabBarController: UITabBarController, shouldSelectViewController viewController: UIViewController) -> Bool { // This will break if the modal view controller is not the second tab let modalController = viewControllers![1] //as! UIViewController // Check if the view about to load is the second tab and if it is, load the modal form instead. if viewController == modalController { let storyboard = UIStoryboard(name: "Record", bundle: nil) let vc = storyboard.instantiateInitialViewController() presentViewController(vc!, animated: true, completion: nil) return false } else { return true } } func logout() { PFUser.logOut() self.dismissViewControllerAnimated(true, completion: nil) self.navigationController?.popToRootViewControllerAnimated(true) } func onSavedDraft() { showUserProfile(false, tune: nil) } func onPublishedTune(notification: NSNotification) { // Get the Tune passed in fron the NSNotification var tune: Tune? if let userInfo = notification.userInfo as? [String: Tune] { tune = userInfo["Tune"] } showUserProfile(true, tune: tune) } func showUserProfile(publishedTunes: Bool, tune: Tune?) { let userProfileVC = viewControllers![2] as! UserProfileViewController userProfileVC.selectedType = publishedTunes ? 0 : 1 if let tune = tune { let publishedVC = userProfileVC.delegates[userProfileVC.selectedType] as! PublishedTunesUserProfileViewControllerDelegate publishedVC.addTune(tune) } selectedViewController = userProfileVC } /* // 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
890e8c4d5d3416918c067606ffe8197f
32.916667
134
0.660934
5.188385
false
false
false
false
shaowei-su/swiftmi-app
swiftmi/swiftmi/UsersDal.swift
4
2737
// // UsersDal.swift // swiftmi // // Created by yangyin on 15/4/18. // Copyright (c) 2015年 swiftmi. All rights reserved. // import UIKit import CoreData import SwiftyJSON class UsersDal: NSObject { func addUser(obj:JSON,save:Bool)->Users? { var context=CoreDataManager.shared.managedObjectContext; let model = NSEntityDescription.entityForName("Users", inManagedObjectContext: context) var user = Users(entity: model!, insertIntoManagedObjectContext: context) if model != nil { var addUser = self.JSON2Object(obj, user: user) if(save) { CoreDataManager.shared.save() } return addUser } return nil } internal func deleteAll(){ CoreDataManager.shared.deleteTable("Users") } internal func save(){ var context=CoreDataManager.shared.managedObjectContext; context.save(nil) } internal func getCurrentUser()->Users? { var request = NSFetchRequest(entityName: "Users") request.fetchLimit = 1 var result = CoreDataManager.shared.executeFetchRequest(request) if let users = result { if (users.count > 0 ){ return users[0] as? Users } return nil } else { return nil } } internal func JSON2Object(obj:JSON,user:Users) -> Users{ var data = obj var userId = data["userId"].int64! var username = data["username"].string! var email = data["email"].string var following_count = data["following_count"].int32! var follower_count = data["follower_count"].int32! var points = data["points"].int32! var signature = data["signature"].string var profile = data["profile"].string var isAdmin = data["isAdmin"].int32! var avatar = data["avatar"].string var createTime = data["createTime"].int64! var updateTime = data["updateTime"].int64! user.userId = userId user.username = username user.email = email user.follower_count = follower_count user.following_count = following_count user.points = points user.signature = signature user.profile = profile user.isAdmin = isAdmin user.avatar = avatar user.createTime = createTime user.updateTime = updateTime return user; } }
mit
4fdce4a83e6c3671609ba8ca23de4334
24.324074
95
0.540037
5.131332
false
false
false
false
developerkitchen/Swift3Projects
SwiftCustomTableProject/SwiftCustomTableProject/ViewController.swift
1
1632
// // ViewController.swift // SwiftCustomTableProject // // Created by İbrahim Gündüz on 27.07.2017. // Copyright © 2017 Developer Kitchen. All rights reserved. // import UIKit class ViewController: UIViewController, UITableViewDataSource, UITableViewDelegate { var products = ["Iphone 6S", "General Mobile 6", "Samsung S7", "Nokia Windows Phone"] var prices = ["2 700 TL", "1 100 TL", "2 500 TL", "900 TL"] var stocks = ["14 adet", "2 adet", "19 adet", "5 adet"] var images = ["product_default", "product_default", "product_default", "product_default"] override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return products.count } public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "myCell", for: indexPath) as! ProductTableViewCell cell.productImageView.image = UIImage(named: "\(images[indexPath.row])") as UIImage? cell.productName.text = products[indexPath.row] cell.productValue.text = prices[indexPath.row] cell.productStock.text = stocks[indexPath.row] cell.remainTime.text = "2 saat 13 dakika 17 saninye" return cell } }
gpl-3.0
065550a781cce48630a616d0e60ad58b
33.638298
115
0.665848
4.38814
false
false
false
false
cnkaptan/SwiftLessons
AllAboutOptionals.playground/Contents.swift
1
2039
//: Playground - noun: a place where people can play import UIKit var maybeString: String? = "Hi" print(maybeString) //maybeString = nil print(maybeString) // count(maybeString) burada ide seni uyarir ve gelen stringin nil olamasina karsin guvenceni almani saglar //optinal binding denir asagidaki kontrole if maybeString != nil { maybeString!.characters.count } // Yukaridaki kontrolu her zaman yapmak yerine asagidaki yol izlenebilir // asagidaki definetelyString ancak maybeString nill degilse atanir ve sonrasinda optinal olmadan kullanabilirz //asagidaki kullanimada optinal binding denir if let definitelyString = maybeString{ print(definitelyString.characters.count) }else{ print ("It's Nil") } var mostLikelyString: String! = "Hi" // nil olmayacak optional bir String tanimliyoruz eger nil yaparsan error alirsin , daha cok ileriye dogru bu degiskene optinal olmayacan gibi davranmani saglar, kodunda direk optinal olmayan string mis gibi davranabilirsin //mostLikelyString = nil print(mostLikelyString.characters.count) class CupHolder{ var cups:[String]? = nil } class Car { var cupHolder:CupHolder? = nil } let niceCar = Car() niceCar.cupHolder = CupHolder() if let cupHolder = niceCar.cupHolder{ if var cups = cupHolder.cups{ cups.append("Coke") }else{ cupHolder.cups = ["Coke"] } } if let cupHolder = niceCar.cupHolder{ if let cups = cupHolder.cups{ if cups[0] == "Coke"{ print("Yayy") }else{ print("I'm Sad") } } } // asagidaki islem yukardaki cupholder kontrollerinin kisaltilmis halidir ver buna optinal chaining denir //niceCar.cupHolder = nil // ilk once cupholderi kontrol ediyo varsa cups i check ediyo eger cupholder veya cups nilse direk firstcup direk nil ataniyo let firstCup = niceCar.cupHolder?.cups?[0] niceCar.cupHolder?.cups?.append("Water") niceCar.cupHolder?.cups?.insert("Coffee", atIndex: 2) print(niceCar.cupHolder?.cups) print(niceCar.cupHolder?.cups?.count)
mit
b0bec416c1bbad98b9ec392c296d9962
21.910112
261
0.724865
3.052395
false
false
false
false
linkedin/LayoutKit
LayoutKitTests/EmbeddedLayoutTests.swift
1
3229
// Copyright 2016 LinkedIn Corp. // 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. import XCTest @testable import LayoutKit class EmbeddedLayoutTests: XCTestCase { private let rootView = View() private let singleViewArrangement = SizeLayout(minSize: .zero, config: { _ in }).arrangement() override func setUp() { super.setUp() rootView.subviews.forEach { $0.removeFromSuperview() } } func testKeepsSubviewsForEmbeddedLayoutWithReuseId() { var parentView: View? let parentLayout = SizeLayout(minSize: .zero, viewReuseId: "test", config: { view in parentView = view }) // Create Parent Layout parentLayout.arrangement().makeViews(in: rootView) // Create Embedded Layout XCTAssertNotNil(parentView) singleViewArrangement.makeViews(in: parentView) // Re-create Parent Layout parentLayout.arrangement().makeViews(in: rootView) XCTAssertEqual(parentView?.subviews.count, 1) } func testRemovesSubviewsForEmbeddedLayoutWithoutReuseId() { var parentView: View? let parentLayout = SizeLayout(minSize: .zero, config: { view in parentView = view }) // Create Parent Layout parentLayout.arrangement().makeViews(in: rootView) // Create Embedded Layout XCTAssertNotNil(parentView) singleViewArrangement.makeViews(in: parentView) let originalParentView = parentView // Re-create Parent Layout parentLayout.arrangement().makeViews(in: rootView) XCTAssertNotEqual(originalParentView, parentView) XCTAssertEqual(parentView?.subviews.count, 0) } func testEmbeddedLayoutsAreRemoved() { var originalHostView: View? SizeLayout( minSize: .zero, viewReuseId: "foo", sublayout: SizeLayout(minSize: .zero, viewReuseId: "bar", config: { view in originalHostView = view self.singleViewArrangement.makeViews(in: view) }), config: { _ in }).arrangement().makeViews(in: rootView) XCTAssertEqual(rootView.subviews.count, 1) XCTAssertNotNil(originalHostView) XCTAssertEqual(originalHostView?.subviews.count, 1) var updatedHostView: View? SizeLayout( minSize: .zero, viewReuseId: "foo", sublayout: SizeLayout(minSize: .zero, viewReuseId: "baz", config: { view in updatedHostView = view }), config: { _ in }).arrangement().makeViews(in: rootView) XCTAssertEqual(rootView.subviews.count, 1) XCTAssertNotNil(updatedHostView) XCTAssertEqual(updatedHostView?.subviews.count, 0) XCTAssertNotEqual(originalHostView, updatedHostView) } }
apache-2.0
df118d395b6f2d5df6d605135295eaf7
34.097826
131
0.655931
4.790801
false
true
false
false
peterobbin/atomSimulation
atoms/ElectronUncertainty.swift
1
703
// // ElectronUncertainty.swift // atoms // // Created by Luobin Wang on 8/3/15. // Copyright © 2015 Luobin Wang. All rights reserved. // import Foundation import SpriteKit class Uncertainty { let uncertainCloud = SKSpriteNode(imageNamed: "glow.png") let initPoint:CGPoint var notConfigured = true init(_initPoint:CGPoint){ self.initPoint = _initPoint self.uncertainCloud.position = initPoint } func setup(_notConfigured:Bool){ self.notConfigured = _notConfigured //uncertainCloud.position = _pos uncertainCloud.name = "uncertainCloud" uncertainCloud.zPosition = -3 } func update(){ } }
mit
90cfbfff9cb9e06a84c2086fe092d639
20.272727
61
0.641026
3.836066
false
true
false
false
luzefeng/QuickRearrangeTableView
Example/App/ViewController.swift
1
2226
import UIKit class ViewController: UIViewController, QuickRearrangeTableViewDataSource, UITableViewDelegate, UITableViewDataSource { var currentIndexPath: NSIndexPath? var cellTitles = ["0x15", "0x2", "0x3", "0x4", "0x5", "0x6", "0x7", "0x8", "0x9", "0xA", "0xB", "0xC", "0xD", "0xE", "0xF", "0x10", "0x11", "0x12", "0x13", "0x14", "0x1"] override func prefersStatusBarHidden() -> Bool { return true } override func viewDidLoad() { super.viewDidLoad() let tableView = QuickRearrangeTableView(frame: view.frame, options: QuickRearrangeTableViewOptions(hover: true, translucency: false)) tableView.delegate = self tableView.dataSource = self tableView.rearrangeDataSource = self tableView.separatorInset = UIEdgeInsetsZero tableView.layoutMargins = UIEdgeInsetsZero tableView.backgroundColor = .grayColor() tableView.tableFooterView = UIView() tableView.rowHeight = tableView.frame.height/10.0 view.addSubview(tableView) } // MARK: UITableViewDelegate func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) { tableView.deselectRowAtIndexPath(indexPath, animated: true) } // MARK: UITableViewDataSource func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return cellTitles.count } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = UITableViewCell(style: .Default, reuseIdentifier: nil) if let unwrappedCurrentIndexPath = currentIndexPath where indexPath == unwrappedCurrentIndexPath { cell.backgroundColor = nil } else { cell.textLabel?.text = cellTitles[indexPath.row] } cell.separatorInset = UIEdgeInsetsZero cell.layoutMargins = UIEdgeInsetsZero return cell } // MARK: QuickRearrangeTableViewDataSource func moveObjectAtCurrentIndexPathToIndexPath(indexPath: NSIndexPath) { if let unwrappedCurrentIndexPath = currentIndexPath { let object = cellTitles[unwrappedCurrentIndexPath.row] cellTitles.removeAtIndex(unwrappedCurrentIndexPath.row) cellTitles.insert(object, atIndex: indexPath.row) } } }
mit
53ce8655d5c360b60298468f1ee18085
26.158537
119
0.730907
4.716102
false
false
false
false
ovenbits/ModelRocket
Sources/Model.swift
1
6267
// Model.swift // // Copyright (c) 2015 Oven Bits, LLC // // 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 public class Model: NSObject, NSCoding { private var JSONMappings: [PropertyDescription] { let mirror = Mirror(reflecting: self) return inspect(mirror) } private func inspect(mirror: Mirror, _ mappings: [PropertyDescription] = []) -> [PropertyDescription] { var mappings = mappings if let parentMirror = mirror.superclassMirror() where parentMirror.children.count > 0 { mappings += inspect(parentMirror, mappings) } mappings += mirror.children.flatMap { $0.value as? PropertyDescription } return mappings } // MARK: Initialization public required override init() { super.init() } public required init(json: JSON) { super.init() JSONMappings.forEach { $0.fromJSON(json) } JSONMappings.forEach { $0.initPostProcess() } } public required init?(strictJSON: JSON) { super.init() var valid = true var debugString = "Initializing object of type: \(self.dynamicType)" for map in JSONMappings { let validObject = map.fromJSON(strictJSON) if map.required && !validObject { valid = false #if DEBUG debugString += "\n\tProperty failed for key: \(map.key), type: \(map.type)" #else break #endif } } guard valid else { #if DEBUG print(debugString) #endif return nil } JSONMappings.forEach { $0.initPostProcess() } } public class func modelForJSON(json: JSON) -> Model { return Model(json: json) } public class func modelForStrictJSON(json: JSON) -> Model? { return Model(strictJSON: json) } // MARK: JSON private func subKeyPathDictionary(value value: AnyObject, keys: [String], index: Int, previousDictionary: AnyObject?) -> [String : AnyObject] { if index == 0 { let key = keys[index] guard let previousDictionary = previousDictionary as? [String : AnyObject] else { return [key : value] } return mergeDictionaries(previousDictionary, [key : value]) } return subKeyPathDictionary(value: [keys[index] : value], keys: keys, index: index-1, previousDictionary: previousDictionary) } /// Create JSON representation of object public func json() -> (dictionary: [String : AnyObject], json: JSON?, data: NSData?) { var dictionary: [String : AnyObject] = [:] for map in JSONMappings { let components = map.key.componentsSeparatedByString(".") if components.count > 1 { if let value: AnyObject = map.toJSON() { let firstKeyPath = components[0] let subKeyPaths = Array(components[1..<components.count]) let previousDictionary: AnyObject? = dictionary[firstKeyPath] let subDictionary = subKeyPathDictionary(value: value, keys: subKeyPaths, index: subKeyPaths.count-1, previousDictionary: previousDictionary) dictionary[firstKeyPath] = subDictionary } } else if let value: AnyObject = map.toJSON() { dictionary[map.key] = value } } if let jsonData = try? NSJSONSerialization.dataWithJSONObject(dictionary, options: .PrettyPrinted) { let json = JSON(data: jsonData) return (dictionary: dictionary, json: json, data: jsonData) } return (dictionary: dictionary, json: nil, data: nil) } // MARK: NSCoding public required convenience init?(coder aDecoder: NSCoder) { self.init() JSONMappings.forEach { $0.decode(aDecoder) } } public func encodeWithCoder(aCoder: NSCoder) { JSONMappings.forEach { $0.encode(aCoder) } } // MARK: Copying public override func copy() -> AnyObject { if let json = json().json { return self.dynamicType.init(json: json) } return self.dynamicType.init() } // MARK: Private private func mergeDictionaries(left: [String : AnyObject], _ right: [String : AnyObject]) -> [String : AnyObject] { var map: [String : AnyObject] = [:] for (k, v) in left { map[k] = v } for (k, v) in right { if let previousValue = map[k] as? [String : AnyObject] { if let value = v as? [String : AnyObject] { let replacement = mergeDictionaries(previousValue, value) map[k] = replacement continue } } map[k] = v } return map } }
mit
5815262fefe06adb30edc55531043368
33.059783
161
0.576033
4.94633
false
false
false
false
TarangKhanna/Inspirator
WorkoutMotivation/CustomPageViewController.swift
13
1071
// // CustomPageViewController.swift // BWWalkthroughExample // // Created by Yari D'areglia on 18/09/14. // Copyright (c) 2014 Yari D'areglia. All rights reserved. // import UIKit class CustomPageViewController: UIViewController,BWWalkthroughPage { @IBOutlet var imageView:UIImageView? @IBOutlet var titleLabel:UILabel? @IBOutlet var textLabel:UILabel? override func viewDidLoad() { super.viewDidLoad() } // MARK: BWWalkThroughPage protocol func walkthroughDidScroll(position: CGFloat, offset: CGFloat) { var tr = CATransform3DIdentity tr.m34 = -1/500.0 titleLabel?.layer.transform = CATransform3DRotate(tr, CGFloat(M_PI) * (1.0 - offset), 1, 1, 1) textLabel?.layer.transform = CATransform3DRotate(tr, CGFloat(M_PI) * (1.0 - offset), 1, 1, 1) var tmpOffset = offset if(tmpOffset > 1.0){ tmpOffset = 1.0 + (1.0 - tmpOffset) } imageView?.layer.transform = CATransform3DTranslate(tr, 0 , (1.0 - tmpOffset) * 200, 0) } }
apache-2.0
7d1ac5d2f8693d9aaaf065d8d0b695c9
27.945946
102
0.637722
3.797872
false
false
false
false
SwiftKit/Reactant
Source/CollectionView/Implementation/SimpleCollectionView.swift
2
1999
// // SimpleCollectionView.swift // Reactant // // Created by Filip Dolnik on 12.02.17. // Copyright © 2017 Brightify. All rights reserved. // import RxSwift public enum SimpleCollectionViewAction<CELL: Component> { case selected(CELL.StateType) case cellAction(CELL.StateType, CELL.ActionType) case refresh } open class SimpleCollectionView<CELL: UIView>: FlowCollectionViewBase<CELL.StateType, SimpleCollectionViewAction<CELL>> where CELL: Component { public typealias MODEL = CELL.StateType private let cellIdentifier = CollectionViewCellIdentifier<CELL>() open override var actions: [Observable<SimpleCollectionViewAction<CELL>>] { #if os(iOS) return [ collectionView.rx.modelSelected(MODEL.self).map(SimpleCollectionViewAction.selected), refreshControl?.rx.controlEvent(.valueChanged).rewrite(with: SimpleCollectionViewAction.refresh) ].compactMap { $0 } #else return [ collectionView.rx.modelSelected(MODEL.self).map(SimpleCollectionViewAction.selected) ] #endif } private let cellFactory: () -> CELL public init(cellFactory: @escaping () -> CELL = CELL.init, reloadable: Bool = true, automaticallyDeselect: Bool = true) { self.cellFactory = cellFactory super.init(reloadable: reloadable, automaticallyDeselect: automaticallyDeselect) } open override func loadView() { super.loadView() collectionView.register(identifier: cellIdentifier) } open override func bind(items: Observable<[MODEL]>) { items .bind(to: collectionView.items(with: cellIdentifier)) { [unowned self] row, model, cell in self.configure(cell: cell, factory: self.cellFactory, model: model, mapAction: { SimpleCollectionViewAction.cellAction(model, $0) }) } .disposed(by: lifetimeDisposeBag) } }
mit
201904ce1c0e322707e83b4561122af7
32.864407
148
0.662162
4.885086
false
false
false
false
epau/OProgressView
Source/CGPoint+PointOnEllipse.swift
1
912
// // CGPoint+PointOnEllipse.swift // OProgressView // // Created by Edward Paulosky on 2/2/17. // Copyright © 2017 epau. All rights reserved. // import UIKit extension CGPoint { // Angle is in radians static func pointOnEllipse(in rect: CGRect, for angle: CGFloat) -> CGPoint { let center = CGPoint(x: rect.midX, y: rect.midY) let xRadius = rect.width / 2 let yRadius = rect.height / 2 return center.pointOnEllipse(angle: angle, xRadius: xRadius, yRadius: yRadius) } // Angle is in degrees static func pointOnEllipse(in rect: CGRect, for angle: Int) -> CGPoint { return pointOnEllipse(in: rect, for: CGFloat(angle.degreesToRadians)) } // Angle is in radians func pointOnEllipse(angle: CGFloat, xRadius: CGFloat, yRadius: CGFloat) -> CGPoint { let x = self.x + xRadius * cos(angle) let y = self.y - yRadius * sin(angle) return CGPoint(x: x, y: y) } }
mit
0d36f1d2d307ce1321042745b377c0dd
26.606061
86
0.675082
3.517375
false
false
false
false
raymondshadow/SwiftDemo
SwiftApp/Common/Common/Utility/TimeUtility.swift
1
992
// // TimeUtility.swift // Common // // Created by wuyp on 2017/7/3. // Copyright © 2017年 raymond. All rights reserved. // import Foundation public typealias Task = (_ cancel: Bool) -> Void @discardableResult public func delay(_ time: TimeInterval, task: @escaping () -> ()) -> Task? { func dispatch_later(block: @escaping ()->()) { let t = DispatchTime.now() + time DispatchQueue.main.asyncAfter(deadline: t, execute: block) } var closeure: (() -> Void)? = task var result: Task? let delayedCloseure: Task = { cancel in if let internalCloseure = closeure { if cancel == false { DispatchQueue.main.async(execute: internalCloseure) } } closeure = nil result = nil } result = delayedCloseure dispatch_later { if let delayedCloseure = result { delayedCloseure(false) } } return result }
apache-2.0
0dabbd082fbc9aa9b188033ea3d0355c
21.477273
76
0.562184
4.244635
false
false
false
false
boytpcm123/ImageDownloader
ImageDownloader/ImageDownloader/Downloader.swift
1
3900
// // Downloader.swift // ImageDownloader // // Created by ninjaKID on 2/27/17. // Copyright © 2017 ninjaKID. All rights reserved. // import Foundation import SSZipArchive class Downloader { class func downloadImageWithURL(url:String) -> UIImage! { let data = NSData(contentsOf: NSURL(string: url)! as URL) return UIImage(data: data! as Data) } static func downloadFileZip() { if let fileUrl = URL(string: Const.urlFileZip) { // check if it exists before downloading it if FileManager().fileExists(atPath: Const.pathZipFile.path) { print("The file already exists at path") readFile(atPath: Const.pathFolderName.path) } else { // if the file doesn't exist // just download the data from your url URLSession.shared.downloadTask(with: fileUrl, completionHandler: { (location, response, error) in // after downloading your data you need to save it to your destination url guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200, let location = location, error == nil else { return } do { try FileManager.default.moveItem(at: location, to: Const.pathZipFile) print("file saved") // Unzip SSZipArchive.unzipFile(atPath: Const.pathZipFile.path, toDestination: Const.documentsUrl.path) readFile(atPath: Const.pathFolderName.path) } catch let error as NSError { print(error.localizedDescription) } }).resume() } } } static func readFile(atPath: String) { var items: [String] do { items = try FileManager.default.contentsOfDirectory(atPath: atPath) } catch { return } for (_, item) in items.enumerated() { if item.hasSuffix("json") { if let name:String = (item.components(separatedBy: ".").first) { let filePath = Const.pathFolderName.appendingPathComponent(name).appendingPathExtension("json").path //print(filePath) let arrayFile = getDataFile(filePath) let fileDownload: FileDownload = FileDownload(nameFile: name, pathFile: filePath, numberOfContent: arrayFile.count, dataOfContent: arrayFile) Common.ListFileDownload.append(fileDownload) } } } // let jsonItems = items.filter({ return $0.hasSuffix("json") }) // Common.ListFileDownload = jsonItems.map({ return FileDownload(nameFile: $0.components(separatedBy: ".").first!, numberOfContent: 0) }) //Post a notification NotificationCenter.default.post(name: Const.notificationDownloadedZip, object: nil) } static func getDataFile(_ filePath: String) -> [String] { do { if let data = NSData(contentsOfFile: filePath) { let jsons = try JSONSerialization.jsonObject(with: data as Data, options: .mutableContainers) return jsons as! [String] } else { print("error cannot read data") } } catch { print("error cannot find file") } return [] } }
apache-2.0
dcecf4f79ed3db3d753c3fe9fbcc022d
32.324786
161
0.510131
5.476124
false
false
false
false
mojidabckuu/content
Content/Classes/Views/InfiniteControl.swift
1
8715
// // InfiniteControl.swift // Pods // // Created by Vlad Gorbenko on 9/7/16. // // import UIKit public protocol ContentControl { func startAnimating() func stopAnimating() var isAnimating: Bool { get } } public extension CGRect { var center: CGPoint { return CGPoint(x: self.origin.x + self.width / 2, y: self.origin.y + self.height / 2) } } open class UIInfiniteControl: UIControl { var height: CGFloat = 60 var activityIndicatorView: UIActivityIndicatorView! override open var isAnimating: Bool { return self.activityIndicatorView.isAnimating } var isObserving: Bool { return _isObserving } var infiniteState: State { set { if _state != newValue { let prevState = _state _state = newValue self.activityIndicatorView.center = self.bounds.center switch newValue { case .stopped: self.activityIndicatorView.stopAnimating() case .triggered, .loading: self.activityIndicatorView.startAnimating() default: self.activityIndicatorView.startAnimating() } if prevState == .triggered { self.sendActions(for: .valueChanged) } } } get { return _state } } fileprivate var _state: State = .stopped fileprivate var _isObserving = false fileprivate weak var scrollView: UIScrollView? fileprivate var originalInset: UIEdgeInsets = UIEdgeInsets() override open func startAnimating() { self.layoutSubviews() if self.isEnabled { self.infiniteState = .loading } } override open func stopAnimating() { self.infiniteState = .stopped } //MARK: - Lifecycle override public init(frame: CGRect) { super.init(frame: frame) self.setup() } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } deinit { self.stopObserveScrollView() } //MARK: - Setup func setup() { self.activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .gray) self.activityIndicatorView.hidesWhenStopped = true self.addSubview(self.activityIndicatorView) } //MARK: - Layout override open func layoutSubviews() { super.layoutSubviews() if let size = self.scrollView?.bounds.size { self.frame = CGRect(x: 0, y: self.contentSize.height, width: size.width, height: self.height) self.activityIndicatorView.center = self.bounds.center } self.bringSubview(toFront: self.activityIndicatorView) } // override open func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) if let scrollView = newSuperview as? UIScrollView { if self.scrollView == nil { self.scrollView = scrollView self.originalInset = scrollView.contentInset } self.startObserveScrollView() } } override open func didMoveToWindow() { super.didMoveToWindow() if self.window == nil { self.stopObserveScrollView() } else { self.startObserveScrollView() } } // ScrollView func resetInsets() { if var contentInset = self.scrollView?.contentInset { contentInset.bottom = self.originalInset.bottom self.setContentInset(contentInset) } } func adjustInsets() { if let contentInset = self.scrollView?.contentInset { var newInsets = contentInset if self.isEnabled { newInsets.bottom = self.originalInset.bottom + self.height } if contentInset.bottom != newInsets.bottom { self.scrollView?.removeObserver(self, forKeyPath: "contentInset") self.setContentInset(newInsets) self.scrollView?.addObserver(self, forKeyPath: "contentInset", options: .new, context: nil) } } } func setContentInset(_ contentInset: UIEdgeInsets) { let options: UIViewAnimationOptions = [.allowUserInteraction, .beginFromCurrentState] // UIView.animate(withDuration: 0.3, delay: 0, options: options, animations: { [weak self] in // TODO: Needs testing. // Because of animation it gives animation for ScrollView self.scrollView?.contentInset = contentInset // }, completion: nil) } //MARK: - Observing func startObserveScrollView() { if !self.isObserving { self.scrollView?.addObserver(self, forKeyPath: "contentOffset", options: .new, context: nil) self.scrollView?.addObserver(self, forKeyPath: "contentSize", options: .new, context: nil) self.scrollView?.addObserver(self, forKeyPath: "contentInset", options: .new, context: nil) _isObserving = true self.adjustInsets() } } func stopObserveScrollView() { if self.isObserving { self.scrollView?.removeObserver(self, forKeyPath: "contentOffset") self.scrollView?.removeObserver(self, forKeyPath: "contentSize") self.scrollView?.removeObserver(self, forKeyPath: "contentInset") _isObserving = false self.resetInsets() } } override open func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { guard let keyPath = keyPath else { return } if keyPath == "contentOffset" { if let offset = (change?[NSKeyValueChangeKey.newKey] as? NSValue)?.cgPointValue { self.scrollViewDidScroll(offset) } } else if keyPath == "contentSize" { self.layoutSubviews() } else if keyPath == "contentInset" { if let value = change?[NSKeyValueChangeKey.newKey] as? NSValue { let targetBottom = self.isEnabled ? self.originalInset.bottom + self.height : self.originalInset.bottom if targetBottom != value.uiEdgeInsetsValue.bottom { self.originalInset = value.uiEdgeInsetsValue self.adjustInsets() } } } } // TableView returns wrong content size when takes table header and footer views. var contentSize: CGSize { if let tableView = self.scrollView as? UITableView { let rowsCount = tableView.dataSource?.tableView(tableView, numberOfRowsInSection: 0) ?? 0 if let footerView = tableView.tableFooterView , rowsCount == 0 { return CGSize(width: tableView.contentSize.width, height: footerView.frame.origin.y) } if let footerView = tableView.tableFooterView, let headerView = tableView.tableHeaderView, rowsCount == 0 { return CGSize(width: tableView.contentSize.width, height: footerView.bounds.height + headerView.bounds.height) } } return self.scrollView?.contentSize ?? UIScreen.main.bounds.size } func scrollViewDidScroll(_ contentOffset: CGPoint) { if _state != .loading && self.isEnabled && contentOffset.y >= 0 { let contentSize = self.contentSize let threshold = contentSize.height - self.scrollView!.bounds.size.height if self.scrollView?.isDragging == true && _state == .triggered { self.infiniteState = .loading } else if self.scrollView?.isDragging == true && contentOffset.y > threshold && _state == .stopped { self.infiniteState = .triggered } else if contentOffset.y < threshold && _state == .stopped { self.infiniteState = .stopped } } } // UIView override open var isEnabled: Bool { set { super.isEnabled = newValue if isEnabled { self.startObserveScrollView() } else { self.stopObserveScrollView() } } get { return super.isEnabled } } override open var tintColor: UIColor! { set { super.tintColor = newValue self.activityIndicatorView.color = newValue } get { return super.tintColor } } } extension UIInfiniteControl { enum State { case stopped case triggered case loading case all } }
mit
712bfff0630bd2dbd39aeda1dedd7f3f
34.864198
156
0.598967
5.231092
false
false
false
false
mmick66/CalendarView
KDCalendar/CalendarView/CalendarView+Extensions.swift
1
2092
/* * KDCalendarView.swift * Created by Michael Michailidis on 24/10/2017. * http://blog.karmadust.com/ * * 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 import EventKit extension EKEvent { var isOneDay : Bool { let components = Calendar.current.dateComponents([.era, .year, .month, .day], from: self.startDate, to: self.endDate) return (components.era == 0 && components.year == 0 && components.month == 0 && components.day == 0) } } extension String { subscript(_ range: CountableRange<Int>) -> String { let start = self.index(self.startIndex, offsetBy: range.lowerBound) let end = self.index(self.startIndex, offsetBy: range.upperBound) let subString = self[start..<end] return String(subString) } } extension Date { func convertToTimeZone(from fromTimeZone: TimeZone, to toTimeZone: TimeZone) -> Date { let delta = TimeInterval(toTimeZone.secondsFromGMT(for: self) - fromTimeZone.secondsFromGMT(for: self)) return addingTimeInterval(delta) } }
mit
b24931f4826d00d0d868504ff8659a88
38.471698
125
0.720841
4.313402
false
false
false
false
debugsquad/nubecero
nubecero/Model/HomeUpload/MHomeUploadItemStatusLoaded.swift
1
4681
import UIKit import FirebaseDatabase class MHomeUploadItemStatusLoaded:MHomeUploadItemStatus { private let kKilobytePerByte:Int = 1000 private let kAssetSync:String = "assetHomeSyncUploading" private let kFinished:Bool = false private let kSelectable:Bool = true init(item:MHomeUploadItem?) { let reusableIdentifier:String = VHomeUploadCellActive.reusableIdentifier let color:UIColor = UIColor.black super.init( reusableIdentifier:reusableIdentifier, item:item, assetSync:kAssetSync, finished:kFinished, selectable:kSelectable, color:color) } override init( reusableIdentifier:String, item:MHomeUploadItem?, assetSync:String, finished:Bool, selectable:Bool, color:UIColor) { fatalError() } override func process(controller:CHomeUploadSync) { super.process(controller:controller) guard let userId:MSession.UserId = MSession.sharedInstance.user.userId, let localId:String = item?.localId, let imageData:Data = item?.imageData, let pixelWidth:Int = item?.pixelWidth, let pixelHeight:Int = item?.pixelHeight, let taken:TimeInterval = item?.creationDate else { let errorString:String = NSLocalizedString("MHomeUploadItemStatusLoaded_errorUser", comment:"") controller.errorSyncing(error:errorString) return } let albumId:MPhotos.AlbumId? if let userAlbum:MPhotosItemUser = controller.album as? MPhotosItemUser { albumId = userAlbum.albumId } else { albumId = nil } let totalStorage:Int = MSession.sharedInstance.server.totalStorage() let parentUser:String = FDatabase.Parent.user.rawValue let propertyPhotos:String = FDatabaseModelUser.Property.photos.rawValue let propertyDiskUsed:String = FDatabaseModelUser.Property.diskUsed.rawValue let pathPhotos:String = "\(parentUser)/\(userId)/\(propertyPhotos)" let pathDiskUsed:String = "\(parentUser)/\(userId)/\(propertyDiskUsed)" let dataLength:Int = imageData.count / kKilobytePerByte let modelPhoto:FDatabaseModelPhoto = FDatabaseModelPhoto( localId:localId, albumId:albumId, taken:taken, size:dataLength, pixelWidth:pixelWidth, pixelHeight:pixelHeight) let photoJson:Any = modelPhoto.modelJson() FMain.sharedInstance.database.listenOnce( path:pathDiskUsed, modelType:FDatabaseModelUserDiskUsed.self) { [weak self, weak controller] ( diskUsed:FDatabaseModelUserDiskUsed?) in guard let totalDiskUsed:Int = diskUsed?.diskUsed else { let errorString:String = NSLocalizedString("MHomeUploadItemStatusLoaded_errorUser", comment:"") controller?.errorSyncing(error:errorString) return } let remainDisk:Int = totalStorage - totalDiskUsed if remainDisk > dataLength { self?.item?.photoId = FMain.sharedInstance.database.createChild( path:pathPhotos, json:photoJson) FMain.sharedInstance.database.transaction( path:pathDiskUsed) { (mutableData:FIRMutableData) -> (FIRTransactionResult) in if let currentDiskUsed:Int = mutableData.value as? Int { let newDataLength:Int = dataLength + currentDiskUsed mutableData.value = newDataLength } else { mutableData.value = dataLength } let transactionResult:FIRTransactionResult = FIRTransactionResult.success( withValue:mutableData) return transactionResult } self?.item?.statusReferenced() } else { self?.item?.statusDiskFull() } controller?.keepSyncing() } } }
mit
6d45fce31dee5343c52d7858ff362847
32.676259
111
0.548814
5.729498
false
false
false
false
EasySwift/EasySwift
Carthage/Checkouts/Kingfisher/Sources/NSButton+Kingfisher.swift
2
14655
// // NSButton+Kingfisher.swift // Kingfisher // // Created by Jie Zhang on 14/04/2016. // // Copyright (c) 2016 Wei Wang <[email protected]> // // 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 AppKit // MARK: - Set Images /** * Set image to use from web. */ extension Kingfisher where Base: NSButton { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { base.image = placeholder guard let resource = resource else { completionHandler?(nil, nil, .none, nil) return .empty } setWebURL(resource.downloadURL) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.webURL else { return } self.setImageTask(nil) if image != nil { strongBase.image = image } completionHandler?(image, error, cacheType, imageURL) } }) setImageTask(task) return task } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ public func cancelImageDownloadTask() { imageTask?.downloadTask?.cancel() } /** Set an alternateImage with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult public func setAlternateImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { base.alternateImage = placeholder guard let resource = resource else { completionHandler?(nil, nil, .none, nil) return .empty } setAlternateWebURL(resource.downloadURL) let task = KingfisherManager.shared.retrieveImage( with: resource, options: options, progressBlock: { receivedSize, totalSize in if let progressBlock = progressBlock { progressBlock(receivedSize, totalSize) } }, completionHandler: {[weak base] image, error, cacheType, imageURL in DispatchQueue.main.safeAsync { guard let strongBase = base, imageURL == self.alternateWebURL else { return } self.setAlternateImageTask(nil) guard let image = image else { completionHandler?(nil, error, cacheType, imageURL) return } strongBase.alternateImage = image completionHandler?(image, error, cacheType, imageURL) } }) setAlternateImageTask(task) return task } /// Cancel the alternate image download task bounded to the image view if it is running. /// Nothing will happen if the downloading has already finished. public func cancelAlternateImageDownloadTask() { alternateImageTask?.downloadTask?.cancel() } } // MARK: - Associated Object private var lastURLKey: Void? private var imageTaskKey: Void? private var lastAlternateURLKey: Void? private var alternateImageTaskKey: Void? extension Kingfisher where Base: NSButton { /// Get the image URL binded to this image view. public var webURL: URL? { return objc_getAssociatedObject(base, &lastURLKey) as? URL } fileprivate func setWebURL(_ url: URL) { objc_setAssociatedObject(base, &lastURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var imageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &imageTaskKey) as? RetrieveImageTask } fileprivate func setImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &imageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } /// Get the alternate image URL binded to this button. public var alternateWebURL: URL? { return objc_getAssociatedObject(base, &lastAlternateURLKey) as? URL } fileprivate func setAlternateWebURL(_ url: URL) { objc_setAssociatedObject(base, &lastAlternateURLKey, url, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } fileprivate var alternateImageTask: RetrieveImageTask? { return objc_getAssociatedObject(base, &alternateImageTaskKey) as? RetrieveImageTask } fileprivate func setAlternateImageTask(_ task: RetrieveImageTask?) { objc_setAssociatedObject(base, &alternateImageTaskKey, task, .OBJC_ASSOCIATION_RETAIN_NONATOMIC) } } // MARK: - Deprecated. Only for back compatibility. /** * Set image to use from web. Deprecated. Use `kf` namespacing instead. */ extension NSButton { /** Set an image with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.setImage` instead.", renamed: "kf.setImage") public func kf_setImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /** Cancel the image download task bounded to the image view if it is running. Nothing will happen if the downloading has already finished. */ @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.cancelImageDownloadTask` instead.", renamed: "kf.cancelImageDownloadTask") public func kf_cancelImageDownloadTask() { kf.cancelImageDownloadTask() } /** Set an alternateImage with a resource, a placeholder image, options, progress handler and completion handler. - parameter resource: Resource object contains information such as `cacheKey` and `downloadURL`. - parameter placeholder: A placeholder image when retrieving the image at URL. - parameter options: A dictionary could control some behaviors. See `KingfisherOptionsInfo` for more. - parameter progressBlock: Called when the image downloading progress gets updated. - parameter completionHandler: Called when the image retrieved and set. - returns: A task represents the retrieving process. - note: Both the `progressBlock` and `completionHandler` will be invoked in main thread. The `CallbackDispatchQueue` specified in `optionsInfo` will not be used in callbacks of this method. */ @discardableResult @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.setAlternateImage` instead.", renamed: "kf.setAlternateImage") public func kf_setAlternateImage(with resource: Resource?, placeholder: Image? = nil, options: KingfisherOptionsInfo? = nil, progressBlock: DownloadProgressBlock? = nil, completionHandler: CompletionHandler? = nil) -> RetrieveImageTask { return kf.setAlternateImage(with: resource, placeholder: placeholder, options: options, progressBlock: progressBlock, completionHandler: completionHandler) } /// Cancel the alternate image download task bounded to the image view if it is running. /// Nothing will happen if the downloading has already finished. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.cancelAlternateImageDownloadTask` instead.", renamed: "kf.cancelAlternateImageDownloadTask") public func kf_cancelAlternateImageDownloadTask() { kf.cancelAlternateImageDownloadTask() } /// Get the image URL binded to this image view. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.webURL` instead.", renamed: "kf.webURL") public var kf_webURL: URL? { return kf.webURL } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.setWebURL") fileprivate func kf_setWebURL(_ url: URL) { kf.setWebURL(url) } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.imageTask") fileprivate var kf_imageTask: RetrieveImageTask? { return kf.imageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setImageTask") fileprivate func kf_setImageTask(_ task: RetrieveImageTask?) { kf.setImageTask(task)} /// Get the alternate image URL binded to this button. @available(*, deprecated, message: "Extensions directly on NSButton are deprecated. Use `button.kf.alternateWebURL` instead.", renamed: "kf.alternateWebURL") public var kf_alternateWebURL: URL? { return kf.alternateWebURL } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.setAlternateWebURL") fileprivate func kf_setAlternateWebURL(_ url: URL) { kf.setAlternateWebURL(url) } @available(*, deprecated, message: "Extensions directly on NSButton are deprecated.",renamed: "kf.alternateImageTask") fileprivate var kf_alternateImageTask: RetrieveImageTask? { return kf.alternateImageTask } @available(*, deprecated, message: "Extensions directly on UIButton are deprecated.",renamed: "kf.setAlternateImageTask") fileprivate func kf_setAlternateImageTask(_ task: RetrieveImageTask?) { kf.setAlternateImageTask(task) } }
apache-2.0
a7ce351dd583d146d338d4e007deb711
45.376582
125
0.655544
5.503192
false
false
false
false
abelsanchezali/ViewBuilder
Source/Vector/VectorHelper.swift
1
13720
// // VectorHelper.swift // ViewBuilder // // Created by Abel Sanchez on 8/28/16. // Copyright © 2016 Abel Sanchez. All rights reserved. // import UIKit func +(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x + b.x, y: a.y + b.y) } func -(a:CGPoint, b:CGPoint) -> CGPoint { return CGPoint(x: a.x - b.x, y: a.y - b.y) } private class SVGPathCommandParser { static let CommandsSet = Set<Character>(["m","M","z","Z","l","L","h","H","v","V","c","C","s","S","q","Q","t","T","a","A"]) static let DigitSet = Set<Character>(["0","1","2","3","4","5","6","7","8","9"]) static let NullSet = Set<Character>([" ","\t","\r","\n"]) static let SignSet = Set<Character>(["+","-"]) static let ExponentialSet = Set<Character>(["e","E"]) static let Dot: Character = "." static let Comma: Character = "," let inputString: String var currentIndex: String.Index init(data: String) { inputString = data currentIndex = data.startIndex } private var isEmpty: Bool { return currentIndex == inputString.endIndex } private func readCommandName() -> Character? { if isEmpty { return nil } let commandName = inputString[currentIndex] if SVGPathCommandParser.CommandsSet.contains(commandName) { currentIndex = inputString.index(after: currentIndex) return commandName } else { return nil } } private func readNullCharacters() { while !isEmpty { let char = inputString[currentIndex] if !SVGPathCommandParser.NullSet.contains(char) { return } currentIndex = inputString.index(after: currentIndex) } } private func readSeparator() { if isEmpty { return } let char = inputString[currentIndex] if char == SVGPathCommandParser.Comma { currentIndex = inputString.index(after: currentIndex) } } private func readNumber() -> String? { readNullCharacters() var allowSign = true var allowDot = true var allowExponential = false var hasDot = false var hasExponential = false var stop = false let firstIndex = currentIndex while !isEmpty && !stop { let char = inputString[currentIndex] switch char { case _ where SVGPathCommandParser.SignSet.contains(char): if !allowSign { stop = true break } case _ where SVGPathCommandParser.DigitSet.contains(char): allowSign = false allowDot = !hasDot && !hasExponential case SVGPathCommandParser.Dot: if !allowDot { stop = true break } else { allowDot = false hasDot = true allowExponential = true } case _ where SVGPathCommandParser.ExponentialSet.contains(char): if !allowExponential { stop = true break } else { allowExponential = false hasExponential = true allowSign = true } default: stop = true break } if stop { break } currentIndex = inputString.index(after: currentIndex) } return inputString.substring(with: firstIndex..<currentIndex) } func readCommand() -> (Character, [CGFloat])? { if isEmpty { return nil } readNullCharacters() guard let commandName = readCommandName() else { return nil } var parameters = [CGFloat]() while !isEmpty { guard let numberString = readNumber() else { return nil } if numberString.isEmpty { break } guard let number = Double(numberString) else { return nil } parameters.append(CGFloat(number)) readNullCharacters() readSeparator() } return (commandName, parameters) } } public class VectorHelper { public class func getPathFromSVGPathData(data: String?) -> CGPath? { guard let data = data else { return nil } let parser = SVGPathCommandParser(data: data) let path = UIBezierPath() var lastControlPoint: CGPoint? = nil func executeClose(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil path.close() return true } func executeMove(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil if parameters.count % 2 != 0 { return false } if parameters.count == 0 { return true } let point = (isRelative ? path.currentPoint : CGPoint.zero) + CGPoint(x: parameters[0], y: parameters[1]) path.move(to: point) return executeLine(Array(parameters[2..<parameters.count]), isRelative: isRelative) } func executeLine(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil if parameters.count % 2 != 0 { return false } let count = parameters.count / 2 for i in 0..<count { let point = (isRelative ? path.currentPoint : CGPoint.zero) + CGPoint(x: parameters[2 * i + 0], y: parameters[2 * i + 1]) path.addLine(to: point) } return true } func executeVertical(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil let count = parameters.count for i in 0..<count { let originPoint = path.currentPoint let point = CGPoint(x: originPoint.x, y: (isRelative ? originPoint.y : 0) + parameters[i]) path.addLine(to: point) } return true } func executeHorizontal(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil let count = parameters.count for i in 0..<count { let originPoint = path.currentPoint let point = CGPoint(x: (isRelative ? originPoint.x : 0) + parameters[i], y: originPoint.y) path.addLine(to: point) } return true } func executeArc(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil if parameters.count % 7 != 0 { return false } let count = parameters.count / 7 for i in 0..<count { let currentPoint = isRelative ? path.currentPoint : CGPoint.zero let endPoint = CGPoint(x:parameters[7 * i + 5], y: parameters[7 * i + 6]) + currentPoint path.addLine(to: endPoint) //path.addCurveToPoint(endPoint, controlPoint1: currentPoint, controlPoint2: currentPoint) } return true } func executeQuadraticStart(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil if parameters.count % 4 != 0 { return false } let count = parameters.count / 4 for i in 0..<count { let originPoint = isRelative ? path.currentPoint : CGPoint.zero let endPoint = CGPoint(x: parameters[4 * i + 2], y: parameters[4 * i + 3]) + originPoint let controlPoint = CGPoint(x: parameters[4 * i + 0], y: parameters[4 * i + 1]) + originPoint path.addQuadCurve(to: endPoint, controlPoint: controlPoint) lastControlPoint = controlPoint } return true } func executeQuadraticContinue(_ parameters: [CGFloat], isRelative: Bool) -> Bool { if parameters.count % 2 != 0 { return false } let count = parameters.count / 2 for i in 0..<count { let currentPoint = path.currentPoint let originPoint = isRelative ? currentPoint : CGPoint.zero let endPoint = CGPoint(x: parameters[2 * i + 0], y: parameters[2 * i + 1]) + originPoint var controlPoint: CGPoint if let lastControlPoint = lastControlPoint { controlPoint = currentPoint + (currentPoint - lastControlPoint) } else { controlPoint = path.currentPoint } path.addQuadCurve(to: endPoint, controlPoint: controlPoint) lastControlPoint = controlPoint } return true } func executeCubicStart(_ parameters: [CGFloat], isRelative: Bool) -> Bool { lastControlPoint = nil if parameters.count % 6 != 0 { return false } let count = parameters.count / 6 for i in 0..<count { let originPoint = isRelative ? path.currentPoint : CGPoint.zero let endPoint = CGPoint(x: parameters[6 * i + 4], y: parameters[6 * i + 5]) + originPoint let controlPoint1 = CGPoint(x: parameters[6 * i + 0], y: parameters[6 * i + 1]) + originPoint let controlPoint2 = CGPoint(x: parameters[6 * i + 2], y: parameters[6 * i + 3]) + originPoint path.addCurve(to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2) lastControlPoint = controlPoint2 } return true } func executeCubicContinue(_ parameters: [CGFloat], isRelative: Bool) -> Bool { if parameters.count % 4 != 0 { return false } let count = parameters.count / 4 for i in 0..<count { let currentPoint = path.currentPoint let originPoint = isRelative ? currentPoint : CGPoint.zero let endPoint = CGPoint(x: parameters[4 * i + 2], y: parameters[4 * i + 3]) + originPoint let controlPoint2 = CGPoint(x: parameters[4 * i + 0], y: parameters[4 * i + 1]) + originPoint var controlPoint1: CGPoint if let lastControlPoint = lastControlPoint { controlPoint1 = currentPoint + (currentPoint - lastControlPoint) } else { controlPoint1 = path.currentPoint } path.addCurve(to: endPoint, controlPoint1: controlPoint1, controlPoint2: controlPoint2) lastControlPoint = controlPoint2 } return true } while let command = parser.readCommand() { //print("\(command.0) - \(command.1)") var result = false switch command.0 { case "M": result = executeMove(command.1, isRelative: false) case "m": result = executeMove(command.1, isRelative: true) case "L": result = executeLine(command.1, isRelative: false) case "l": result = executeLine(command.1, isRelative: true) case "V": result = executeVertical(command.1, isRelative: false) case "v": result = executeVertical(command.1, isRelative: true) case "H": result = executeHorizontal(command.1, isRelative: false) case "h": result = executeHorizontal(command.1, isRelative: true) case "A": result = executeArc(command.1, isRelative: false) case "a": result = executeArc(command.1, isRelative: true) case "Q": result = executeQuadraticStart(command.1, isRelative: false) case "q": result = executeQuadraticStart(command.1, isRelative: true) case "T": result = executeQuadraticContinue(command.1, isRelative: false) case "t": result = executeQuadraticContinue(command.1, isRelative: true) case "C": result = executeCubicStart(command.1, isRelative: false) case "c": result = executeCubicStart(command.1, isRelative: true) case "S": result = executeCubicContinue(command.1, isRelative: false) case "s": result = executeCubicContinue(command.1, isRelative: true) case "Z": result = executeClose(command.1, isRelative: false) case "z": result = executeClose(command.1, isRelative: true) default: break } if !result { return nil } } path.apply(CGAffineTransform.identity) return path.cgPath } }
mit
455fede5cb5fb95de2e387307967f95b
36.078378
126
0.509512
5.136279
false
false
false
false
zwaldowski/ParksAndRecreation
Swift-2/CustomTruncation.playground/Sources/NSRange.swift
1
1552
// // NSRange.swift // // Created by Zachary Waldowski on 7/16/15. // Copyright (c) 2015 Big Nerd Ranch. Some rights reserved. Licensed under MIT. // import Foundation import Swift extension String.UTF16View { var range: NSRange { return NSRange(indices, within: self) } } public extension NSRange { init(_ utf16Range: Range<String.UTF16View.Index>, within utf16: String.UTF16View) { location = utf16.startIndex.distanceTo(utf16Range.startIndex) length = utf16Range.count } init(_ range: Range<String.Index>, within characters: String) { let utf16 = characters.utf16 let utfStart = range.startIndex.samePositionIn(utf16) let utfEnd = range.endIndex.samePositionIn(utf16) self.init(utfStart ..< utfEnd, within: utf16) } func toOptional() -> NSRange? { guard location != NSNotFound else { return nil } return self } func sameRangeIn(characters: String) -> Range<String.Index>? { guard location != NSNotFound else { return nil } let utfStart = characters.utf16.startIndex.advancedBy(location, limit: characters.utf16.endIndex) guard utfStart != characters.utf16.endIndex else { return nil } let utfEnd = utfStart.advancedBy(length, limit: characters.utf16.endIndex) guard let start = utfStart.samePositionIn(characters), end = utfEnd.samePositionIn(characters) else { return nil } return start ..< end } }
mit
360a56a8fa2b34bde40656f07d74a4a2
28.846154
105
0.642397
4.194595
false
false
false
false
jakub-tucek/fit-checker-2.0
fit-checker/controller/CoursesTableViewController.swift
1
4613
// // CoursesTableViewController.swift // fit-checker // // Created by Josef Dolezal on 18/01/2017. // Copyright © 2017 Josef Dolezal. All rights reserved. // import UIKit import RealmSwift /// Courses list controller. class CoursesTableViewController: UITableViewController { /// Defines mutualy exclusive controller states enum ControllerState { case refreshing case idle } /// Database context manager dependency fileprivate let contextManager: ContextManager /// Network controller dependency fileprivate let networkController: NetworkController /// List of stored courses fileprivate var courses: Results<Course>? /// Realm notification token for course list changes private var token: NotificationToken? /// Current controller state (default: .idle), indicates whether controller /// is refreshing data or is idle private var controllerState = ControllerState.idle init(contextManager: ContextManager, networkController: NetworkController) { self.contextManager = contextManager self.networkController = networkController super.init(nibName: nil, bundle: nil) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(animated) animateRowsDeselect() } override func viewDidLoad() { super.viewDidLoad() loadData() configureView() refreshData() } /// Download new data func refreshData() { // Fixes refresh controller glitch which, // when the controller is loading, data are refreshed silentely guard controllerState != .refreshing else { return } controllerState = .refreshing networkController.loadCourseList { // Stop refresh control when download is comleted DispatchQueue.main.async { [weak self] in self?.controllerState = .idle self?.refreshControl?.endRefreshing() } } } /// Configure view related stuff private func configureView() { let refreshControl = UIRefreshControl() title = tr(.courses) tableView.register(UITableViewCell.self, forCellReuseIdentifier: UITableViewCell.identifier) tableView.addSubview(refreshControl) refreshControl.addTarget(self, action: #selector(refreshData), for: .valueChanged) self.refreshControl = refreshControl } /// Load stored data into view private func loadData() { do { let realm = try contextManager.createContext() courses = realm.objects(Course.self) token = courses?.addNotificationBlock { [weak self] _ in self?.tableView.reloadData() } } catch { Logger.shared.error("\(error)") } } deinit { token?.stop() } } // MARK: - UITableViewDataSource extension CoursesTableViewController { override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return courses?.count ?? 0 } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: UITableViewCell.identifier, for: indexPath) if let course = courses?[indexPath.row] { cell.textLabel?.text = course.name.uppercased() cell.selectionStyle = course.classificationAvailable ? .default : .none cell.accessoryType = course.classificationAvailable ? .disclosureIndicator : .none } return cell } } // MARK: - UITableViewDelegate extension CoursesTableViewController { override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let keychain = Keechain(service: .edux) guard let course = courses?[indexPath.row], let (student, _) = keychain.getAccount(), course.classificationAvailable == true else { return } let controller = CourseClassificationTableViewController( student: student, courseId: course.id, networkController: networkController, contextManager: contextManager ) navigationController?.pushViewController(controller, animated: true) } }
mit
5a7e1c2185aff0e47a6738834e557c6b
28.375796
109
0.639853
5.645043
false
false
false
false
AliceAponasko/LJReader
LJReader/Extensions/NSDateExtension.swift
1
1355
// // NSDateExtension.swift // LJReader // // Created by Alice Aponasko on 2/27/16. // Copyright © 2016 aliceaponasko. All rights reserved. // import Foundation extension NSDate: Comparable {} func < (lhs: NSDate?, rhs: NSDate?) -> Bool { if let date1 = lhs, date2 = rhs { return date1 < date2 } return false } func <= (lhs: NSDate?, rhs: NSDate?) -> Bool { if let date1 = lhs, date2 = rhs { return date1 <= date2 } return false } public func < (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedAscending } public func <= (lhs: NSDate, rhs: NSDate) -> Bool { return lhs < rhs || lhs.compare(rhs) == .OrderedSame } func > (lhs: NSDate?, rhs: NSDate?) -> Bool { if let date1 = lhs, date2 = rhs { return date1 > date2 } return false } func >= (lhs: NSDate?, rhs: NSDate?) -> Bool { if let date1 = lhs, date2 = rhs { return date1 >= date2 } return false } public func > (lhs: NSDate, rhs: NSDate) -> Bool { return lhs.compare(rhs) == .OrderedDescending } public func >= (lhs: NSDate, rhs: NSDate) -> Bool { return lhs > rhs || lhs.compare(rhs) == .OrderedSame } extension NSDate { func between(startDate: NSDate, _ endDate: NSDate) -> Bool { return (startDate < self) && (self < endDate) } }
mit
ae7cd97ead8caa465e2aea350522fe18
20.15625
64
0.587888
3.376559
false
false
false
false
petrone/PetroneAPI_swift
PetroneAPI/PetroneEnums.swift
1
11490
// // PetroneEnums.swift // Petrone // // Created by Byrobot on 2017. 7. 31.. // Copyright © 2017년 Byrobot. All rights reserved. // import Foundation public enum PetroneDataType: UInt8 { case None case Ping = 0x01, ///< Ping connection status ( reserve ) Ack, ///< Data response ack Error, ///< Connection error Request, ///< Request Passcode ///< new pairing password case Control = 0x10, ///< Control Petrone command Command, Command2, Command3 case LedMode = 0x20, ///< LED mode setting LedMode2, ///< LED mode setting ( 2 values ) LedModeCommand, ///< LED mode & command LedModeCommandIr, ///< LED mode, command & IR Send LedModeColor, ///< LED mode color RGB setting LedModeColor2, ///< LED mode color RGB setting ( 2 values ) LedEvent, ///< LED event LedEvent2, ///< LED event ( 2 values ), LedEventCommand, ///< LED event & command LedEventCommandIr, ///< LED mode, command & IR Send LedEventColor, ///< LED event color RGB LedEventColor2, ///< LED event color RGB ( 2 values ) LedModeDefaultColor, ///< LED Default mode color LedModeDefaultColor2 ///< LED Default mode color ( 2 values) case Address = 0x30, State, ///< PETRONE status ( Drone mode, coordinate, battery ) Attitude, ///< PETRONE attitude(Vector) GyroBias, ///< PETRONE Gyro(Vector) TrimAll, ///< PETRONE trim infomation( Flight, Drive ) TrimFlight, ///< PETRONE flight trim information TrimDrive, ///< PETRONE drive trim information CountFlight, ///< PETRONE flight count information CountDrive ///< PETRONE drive count information case IrMessage = 0x40 ///< IR Data send/recv // Sensor data case ImuRawAndAngle = 0x50, ///< IMU Raw + Angle Pressure, ///< Pressure sensor ImageFlow, ///< ImageFlow Button, ///< Button Input Battery, ///< Battery sStatus Motor, ///< Motor staus Temperature, ///< Temperature Range, ///< Range sensor EndOfType } public enum PetroneCommand : UInt8 { case None = 0 case ModePetrone = 0x10 ///< PETRONE mode change case Coordinate = 0x20, ///< PETRONE coordinate change Trim, ///< PETRONE trime change FlightEvent, ///< PETRONE flight event DriveEvent, ///< PETRONE drive event Stop ///< PETRONE stop case ResetHeading = 0x50, ///< PETRONe Heading reset ClearGyroBiasAndTrim, ///< Clear Gyro & trim ClearTrim ///< Clear trim case Request = 0x90, ///< Request data type EndOfType } public enum PetroneFlightEvent : UInt8 { case None = 0, TakeOff, ///< TakeOff FlipFront, ///< Flip FlipRear, ///< Flip FlipLeft, ///< Flip FlipRight, ///< Flip Stop, ///< Stop Landing, ///< Landing TurnOver, ///< TurnOver for reverse Shot, ///< IR Shot event UnderAttack, ///< IR Damage event Square, CircleLeft, CircleRight, Rotate180, EndOfType } public enum PetroneDriveEvent : UInt8 { case None = 0, Stop, ///< Stop Shot, ///< IR Shot event UnderAttack, ///< IR Damage event Square, CircleLeft, CircleRight, Rotate90Left, Rotate90Right, Rotate180, Rotate3600, EndOfType } public enum PetroneMode : UInt8 { case None = 0 case Flight = 0x10, ///< Flight with guard FlightNoGuard, ///< Flight no guard FlightFPV ///< Flight with FPV Kit case Drive = 0x20, ///< Drive DriveFPV ///< Drive with FPV Kit } public enum PetroneModeSystem: UInt8 { case None = 0, Boot, ///< System Booting Wait, ///< Ready for connection Ready, ///< Ready for control Running, ///< Running code Update, ///< Firmware Updating. UpdateComplete, ///< Firmware update complete Error, ///< System error EndOfType } public enum PetroneModeFlight: UInt8 { case None = 0, Ready, ///< Ready for flight TakeOff, ///< Take off Flight, ///< Flight Flip, ///< Flip Stop, ///< Stop flight Landing, ///< Landing Reverse, ///< Reverse Accident, ///< Accident ( Change to ready ) Error, ///< System error EndOfType } public enum PetroneModeDrive: UInt8 { case None = 0, Ready, ///< Ready for drive Start, ///< Start Drive, ///< Drive Stop, ///< Stop driving Accident, ///< Accident ( Change to ready ) Error, ///< System error EndOfType } public enum PetroneCoordinate: UInt8 { case None = 0, Absolute, ///< Absolute axis Relative, ///< Relative axis Fixed, ///< Fixed heading axis EndOfType } public enum PetroneDirection: UInt8 { case None = 0, Left, Front, Right, Rear, EndOfType } public enum PetroneSensorOrientation: UInt8 { case None = 0, Normal, // Normal ReverseStart, // Start reverse Reversed, // Reversed EndOfType } public enum PetroneLigthMode: UInt8 { case None = 0, WaitingForConnect, ///< Waiting for connect Connected case EyeNone = 0x10, EyeHold, ///< Eye light hold EyeMix, ///< Eye light color change EyeFlicker, ///< Eye light flickering EyeFlickerDouble, ///< Eye light flickering 2times EyeDimming ///< Eye light dimming case ArmNone = 0x40, ArmHold, ///< 지정한 색상을 계속 켬 ArmMix, ///< 순차적으로 LED 색 변경 ArmFlicker, ///< 깜빡임 ArmFlickerDouble, ///< 깜빡임(두 번 깜빡이고 깜빡인 시간만큼 꺼짐) ArmDimming, ///< 밝기 제어하여 천천히 깜빡임 ArmFlow, ///< 앞에서 뒤로 흐름 ArmFlowReverse ///< 뒤에서 앞으로 흐름 case EndOfType } public enum PetroneColors: UInt8 { case AliceBlue = 0, AntiqueWhite, Aqua, Aquamarine, Azure, Beige, Bisque, Black, BlanchedAlmond, Blue, BlueViolet, // 10 Brown, BurlyWood, CadetBlue, Chartreuse, Chocolate, Coral, CornflowerBlue, Cornsilk, Crimson, Cyan, // 20 DarkBlue, DarkCyan, DarkGoldenRod, DarkGray, DarkGreen, DarkKhaki, DarkMagenta, DarkOliveGreen, DarkOrange, DarkOrchid, // 30 DarkRed, DarkSalmon, DarkSeaGreen, DarkSlateBlue, DarkSlateGray, DarkTurquoise, DarkViolet, DeepPink, DeepSkyBlue, DimGray, // 40 DodgerBlue, FireBrick, FloralWhite, ForestGreen, Fuchsia, Gainsboro, GhostWhite, Gold, GoldenRod, Gray, // 50 Green, GreenYellow, HoneyDew, HotPink, IndianRed, Indigo, Ivory, Khaki, Lavender, LavenderBlush, // 60 LawnGreen, LemonChiffon, LightBlue, LightCoral, LightCyan, LightGoldenRodYellow, LightGray, LightGreen, LightPink, LightSalmon, // 70 LightSeaGreen, LightSkyBlue, LightSlateGray, LightSteelBlue, LightYellow, Lime, LimeGreen, Linen, Magenta, Maroon, // 80 MediumAquaMarine, MediumBlue, MediumOrchid, MediumPurple, MediumSeaGreen, MediumSlateBlue, MediumSpringGreen, MediumTurquoise, MediumVioletRed, MidnightBlue, // 90 MintCream, MistyRose, Moccasin, NavajoWhite, Navy, OldLace, Olive, OliveDrab, Orange, OrangeRed, // 100 Orchid, PaleGoldenRod, PaleGreen, PaleTurquoise, PaleVioletRed, PapayaWhip, PeachPuff, Peru, Pink, Plum, // 110 PowderBlue, Purple, RebeccaPurple, Red, RosyBrown, RoyalBlue, SaddleBrown, Salmon, SandyBrown, SeaGreen, // 120 SeaShell, Sienna, Silver, SkyBlue, SlateBlue, SlateGray, Snow, SpringGreen, SteelBlue, Tan, // 130 Teal, Thistle, Tomato, Turquoise, Violet, Wheat, White, WhiteSmoke, Yellow, YellowGreen }
mit
468474b656b9f8177309d243d2ee81f2
27.463659
91
0.417012
5.014128
false
false
false
false
AFathi/NotchToolkit
NotchToolkit/Classes/NotchBar.swift
2
4082
// // NotchBar.swift // NotchToolbar // // Created by Ahmed Bekhit on 9/23/17. // Copyright © 2017 Ahmed Fathi Bekhit. All rights reserved. // import UIKit public class NotchBar: UIView { /** This allows you to choose between statusBar & noStatusBar modes. */ public var mode:notchMode = .statusBar /** This allows you to set the height of the NotchBar. */ public var height:CGFloat = 250 /** This allows you to set the background color of the NotchBar. */ public var bgColor:UIColor = .black /** This allows you to set the corner radii of the NotchBar. */ public var curve:CGFloat = 35 /** This allows you to initially set the NotchBar visibility. */ public var isVisible:Bool = false /** This allows you to set the animation show/hide & rotation animation time interval of the NotchBar. */ public var animationInterval:TimeInterval = 0.3 override init(frame: CGRect) { super.init(frame: frame) create() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) create() } var scale:CGFloat! var multiplier:CGFloat! func create() { switch mode { case .statusBar: scale = UIScreen.main.portraitNotch.width multiplier = UIScreen.main.multiplier case .noStatusBar: scale = UIScreen.main.widePortraitNotch.width multiplier = UIScreen.main.multiplierWide } self.bounds = CGRect(x: 0, y: 0, width: scale, height: height) self.center = CGPoint(x: UIScreen.main.portraitNotch.origin.x, y: (self.bounds.height/2)) self.backgroundColor = bgColor self.draw(.corner, position: .bottom, curve: curve) self.layer.masksToBounds = true self.alpha = isVisible ? 1 : 0 } /** This function is used to resize the NotchBar when device orientation is changed. */ public func refresh(orientation:deviceOrientation) { let subtrehend = isVisible ? 0 : self.bounds.height switch mode { case .statusBar: scale = UIScreen.main.portraitNotch.width multiplier = UIScreen.main.multiplier case .noStatusBar: scale = UIScreen.main.widePortraitNotch.width multiplier = UIScreen.main.multiplierWide } switch orientation { case .portrait: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.scale, height: self.height) self.center = CGPoint(x: UIScreen.main.portraitNotch.origin.x, y: (self.bounds.height/2) - subtrehend) self.backgroundColor = self.bgColor self.draw(.corner, position: .bottom, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) case .landscapeLeft: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.height, height: self.scale) self.center = CGPoint(x: (self.bounds.height*(self.multiplier*self.height)) - subtrehend, y: UIScreen.main.landscapeLeftNotch.origin.y) self.backgroundColor = self.bgColor self.draw(.corner, position: .right, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) case .landscapeRight: UIView.animate(withDuration: animationInterval, animations: { self.bounds = CGRect(x: 0, y: 0, width: self.height, height: self.scale) self.center = CGPoint(x: (UIScreen.main.bounds.width-self.bounds.height*(self.multiplier*self.height)) + subtrehend, y: UIScreen.main.landscapeRightNotch.origin.y) self.backgroundColor = self.bgColor self.draw(.corner, position: .left, curve: self.curve) self.alpha = self.isVisible ? 1 : 0 }) } } }
mit
0c9dd103144c5182ab767a805ad0697a
36.787037
179
0.608184
4.336876
false
false
false
false
zixun/ZXKit
Pod/Classes/core/extension/UIScrollView+.swift
1
2015
// // UIScrollView+Capture.swift // CocoaChinaPlus // // Created by zixun on 15/9/19. // Copyright © 2015年 zixun. All rights reserved. // import Foundation import UIKit // MARK: - capture public extension UIScrollView { public func capture()->UIImage{ var image = UIImage(); UIGraphicsBeginImageContextWithOptions(self.contentSize, false, UIScreen.mainScreen().scale) // save initial values let savedContentOffset = self.contentOffset; let savedFrame = self.frame; let savedBackgroundColor = self.backgroundColor // reset offset to top left point self.contentOffset = CGPointZero; // set frame to content size self.frame = CGRectMake(0, 0, self.contentSize.width, self.contentSize.height); // remove background self.backgroundColor = UIColor.clearColor() // make temp view with scroll view content size // a workaround for issue when image on ipad was drawn incorrectly let tempView = UIView(frame: CGRectMake(0, 0, self.contentSize.width, self.contentSize.height)) // save superview let tempSuperView = self.superview // remove scrollView from old superview self.removeFromSuperview() // and add to tempView tempView.addSubview(self) // render view // drawViewHierarchyInRect not working correctly tempView.layer.renderInContext(UIGraphicsGetCurrentContext()!) // and get image image = UIGraphicsGetImageFromCurrentImageContext(); // and return everything back tempView.subviews[0].removeFromSuperview() tempSuperView?.addSubview(self) // restore saved settings self.contentOffset = savedContentOffset; self.frame = savedFrame; self.backgroundColor = savedBackgroundColor UIGraphicsEndImageContext(); return image } }
mit
5ca47f084af6fe16dc6340d8b2014320
30.952381
103
0.639165
5.604457
false
false
false
false
mityung/XERUNG
IOS/Xerung/Xerung/MemberDetailViewController.swift
1
6274
// // MemberDetailViewController.swift // Xerung // // Created by mityung on 21/03/17. // Copyright © 2017 mityung. All rights reserved. // import UIKit class MemberDetailViewController: UIViewController, UITableViewDelegate, UITableViewDataSource { struct person { var name:String = "" var number:String = "" var uid:String = "" } var type:String! var query:String! var data = [person]() @IBOutlet weak var tableView: UITableView! override func viewDidLoad() { super.viewDidLoad() self.title = "Member Details" self.findBloodGroup() self.tableView.estimatedRowHeight = 170; self.tableView.rowHeight = UITableViewAutomaticDimension; //tableView.tableFooterView = UIView(frame: CGRect.zero) // tableView.backgroundView = UIImageView(image: UIImage(named: "backScreen.png")) tableView.separatorStyle = .none let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupCalled cell.dirtectoryType.text = selectedGroupName cell.aboutLabel.text = selectedGroupAbout cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "defaultDirectory") } tableView.tableHeaderView = cell } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return data.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "MemberDetailCell", for: indexPath) as! MemberDetailCell if data[indexPath.row].name == "" { cell.nameLabel.text = "Unknown" }else{ cell.nameLabel.text = data[indexPath.row].name.uppercaseFirst } cell.numberLabel.text = data[indexPath.row].number cell.selectionStyle = .none cell.backgroundColor = UIColor.clear return cell } /* func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? { let cell = tableView.dequeueReusableCell(withIdentifier: "HeaderCell") as! HeaderCell cell.directoryMoto.text = selectedGroupAbout cell.dirtectoryType.text = selectedGroupCalled cell.directoryImage.layer.cornerRadius = cell.directoryImage.frame.width/2 cell.directoryImage.layer.masksToBounds = true cell.directoryImage.layer.borderWidth = 1 cell.directoryImage.layer.borderColor = themeColor.cgColor if selectedGroupPhoto != "" && selectedGroupPhoto != "0" { if let imageData = Data(base64Encoded: selectedGroupPhoto , options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) { let DecodedImage = UIImage(data: imageData) cell.directoryImage.image = DecodedImage } }else{ cell.directoryImage.image = UIImage(named: "user.png") } return cell } func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat { return 88 }*/ func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return UITableViewAutomaticDimension } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let viewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewController") as! ProfileViewController viewController.pid = data[indexPath.row].uid self.navigationController?.pushViewController(viewController, animated: true) } func findBloodGroup(){ let databasePath = UserDefaults.standard.url(forKey: "DataBasePath")! let contactDB = FMDatabase(path: String(describing: databasePath)) if (contactDB?.open())! { var querySQL = "" if type == "blood" { querySQL = "SELECT * FROM GroupData where bloodGroup = '\(query!)' " }else if type == "city" { querySQL = "SELECT * FROM GroupData where city = '\(query!)' " } else if type == "profession" { querySQL = "SELECT * FROM GroupData where profession = '\(query!)' " } print(querySQL) let results:FMResultSet? = contactDB?.executeQuery(querySQL,withArgumentsIn: nil) while((results?.next()) == true){ data.append(person.init( name: results!.string(forColumn: "name")!, number: results!.string(forColumn: "number")!, uid: results!.string(forColumn: "UID")! )) } tableView.reloadData() contactDB?.close() } else { print("Error: \(contactDB?.lastErrorMessage())") } } /* // 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. } */ }
apache-2.0
b3fb632d84fa093a3848f195c41d4af5
35.684211
138
0.620915
5.271429
false
false
false
false
fakerabbit/LucasBot
LucasBot/Avatar.swift
2
1498
// // Avatar.swift // LucasBot // // Created by Mirko Justiniano on 1/30/17. // Copyright © 2017 LB. All rights reserved. // import Foundation import UIKit class Avatar: UIView { var isBot: Bool! { didSet { if isBot == true { imageView.image = UIImage(named: "botAvatar") } else { imageView.image = UIImage(named: "userAvatar") } } } private let imageView = UIImageView(frame: CGRect.zero) private let s:CGFloat = 40.0 override init(frame: CGRect) { super.init(frame: CGRect(x: 0, y: 0, width: s, height: s)) self.backgroundColor = UIColor.clear self.layer.cornerRadius = 19.0; self.layer.masksToBounds = false; self.clipsToBounds = true imageView.backgroundColor = UIColor.clear imageView.contentMode = .scaleAspectFit imageView.isUserInteractionEnabled = false //imageView.layer.cornerRadius = 18.0; //imageView.layer.masksToBounds = false; //imageView.clipsToBounds = true self.addSubview(imageView) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override func layoutSubviews() { super.layoutSubviews() let w = self.frame.size.width let h = self.frame.size.height imageView.frame = CGRect(x: 0, y: 0, width: w, height: h) } }
gpl-3.0
abf73dc4b17520985b55bc06350842d3
26.218182
66
0.58517
4.364431
false
false
false
false
chrislzm/TimeAnalytics
Time Analytics/TAActivityTableViewController.swift
1
3188
// // TAActivityTableViewController.swift // Time Analytics // // Displays all Time Analytics Activity data (TAActivitySegment managed objects) and allows user to tap into a detail view for each one. // // Created by Chris Leung on 5/23/17. // Copyright © 2017 Chris Leung. All rights reserved. // import CoreData import UIKit class TAActivityTableViewController: TATableViewController { @IBOutlet weak var activityTableView: UITableView! let viewTitle = "Activities" // MARK: Lifecycle override func viewDidLoad() { // Set tableview for superclass before calling super method so that it can setup the table's properties (style, etc.) super.tableView = activityTableView super.viewDidLoad() navigationItem.title = viewTitle // Get the context let delegate = UIApplication.shared.delegate as! AppDelegate let context = delegate.stack.context // Create a fetchrequest let fr = NSFetchRequest<NSFetchRequestResult>(entityName: "TAActivitySegment") fr.sortDescriptors = [NSSortDescriptor(key: "startTime", ascending: false)] // Create the FetchedResultsController fetchedResultsController = NSFetchedResultsController(fetchRequest: fr, managedObjectContext: context, sectionNameKeyPath: "daySectionIdentifier", cacheName: nil) } override func viewDidAppear(_ animated: Bool) { super.viewDidAppear(animated) // If no data, let the user know if fetchedResultsController?.sections?.count == 0 { createTableEmptyMessageIn(tableView, "No activities recorded yet.\n\nPlease ensure that your sleep and\nworkout activities are being written\nto Apple Health data and that\nTime Analytics is authorized to\nread your Health data.") } else { removeTableEmptyMessageFrom(tableView) // Deselect row if we selected one that caused a segue if let selectedRowIndexPath = activityTableView.indexPathForSelectedRow { activityTableView.deselectRow(at: selectedRowIndexPath, animated: true) } } } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment let cell = tableView.dequeueReusableCell(withIdentifier: "TAActivityTableViewCell", for: indexPath) as! TAActivityTableViewCell // Get label values let start = activity.startTime! as Date let end = activity.endTime! as Date // Set label values cell.timeLabel.text = generateTimeInOutStringWithDate(start, end) cell.lengthLabel.text = generateLengthString(start, end) cell.nameLabel.text = "\(activity.type!): \(activity.name!)" return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let activity = fetchedResultsController!.object(at: indexPath) as! TAActivitySegment showActivityDetailViewController(activity) } }
mit
126f4f9d2137176374fa707e02c64847
39.858974
242
0.68748
5.457192
false
false
false
false
yangxiaodongcn/iOSAppBase
iOSAppBase/Carthage/Checkouts/XCGLogger/Sources/XCGLogger/Misc/Optional/UserInfoHelpers.swift
2
5892
// // UserInfoHelpers.swift // XCGLogger: https://github.com/DaveWoodCom/XCGLogger // // Created by Dave Wood on 2016-09-19. // Copyright © 2016 Dave Wood, Cerebral Gardens. // Some rights reserved: https://github.com/DaveWoodCom/XCGLogger/blob/master/LICENSE.txt // /// Protocol for creating tagging objects (ie, a tag, a developer, etc) to filter log messages by public protocol UserInfoTaggingProtocol { /// The name of the tagging object var name: String { get set } /// Convert the object to a userInfo compatible dictionary var dictionary: [String: String] { get } /// initialize the object with a name init(_ name: String) } /// Struction for tagging log messages with Tags public struct Tag: UserInfoTaggingProtocol { /// The name of the tag public var name: String /// Dictionary representation compatible with the userInfo paramater of log messages public var dictionary: [String: String] { return [XCGLogger.Constants.userInfoKeyTags: name] } /// Initialize a Tag object with a name public init(_ name: String) { self.name = name } /// Create a Tag object with a name public static func name(_ name: String) -> Tag { return Tag(name) } /// Generate a userInfo compatible dictionary for the array of tag names public static func names(_ names: String...) -> [String: [String]] { var tags: [String] = [] for name in names { tags.append(name) } return [XCGLogger.Constants.userInfoKeyTags: tags] } } /// Struction for tagging log messages with Developers public struct Dev: UserInfoTaggingProtocol { /// The name of the developer public var name: String /// Dictionary representation compatible with the userInfo paramater of log messages public var dictionary: [String: String] { return [XCGLogger.Constants.userInfoKeyDevs: name] } /// Initialize a Dev object with a name public init(_ name: String) { self.name = name } /// Create a Dev object with a name public static func name(_ name: String) -> Dev { return Dev(name) } /// Generate a userInfo compatible dictionary for the array of dev names public static func names(_ names: String...) -> [String: [String]] { var tags: [String] = [] for name in names { tags.append(name) } return [XCGLogger.Constants.userInfoKeyDevs: tags] } } /// Overloaded operator to merge userInfo compatible dictionaries together /// Note: should correctly handle combining single elements of the same key, or an element and an array, but will skip sets public func |<Key: Hashable, Value: Any> (lhs: Dictionary<Key, Value>, rhs: Dictionary<Key, Value>) -> Dictionary<Key, Any> { var mergedDictionary: Dictionary<Key, Any> = lhs rhs.forEach { key, rhsValue in guard let lhsValue = lhs[key] else { mergedDictionary[key] = rhsValue; return } guard !(rhsValue is Set<AnyHashable>) else { return } guard !(lhsValue is Set<AnyHashable>) else { return } if let lhsValue = lhsValue as? [Any], let rhsValue = rhsValue as? [Any] { // array, array -> array var mergedArray: [Any] = lhsValue mergedArray.append(contentsOf: rhsValue) mergedDictionary[key] = mergedArray } else if let lhsValue = lhsValue as? [Any] { // array, item -> array var mergedArray: [Any] = lhsValue mergedArray.append(rhsValue) mergedDictionary[key] = mergedArray } else if let rhsValue = rhsValue as? [Any] { // item, array -> array var mergedArray: [Any] = rhsValue mergedArray.append(lhsValue) mergedDictionary[key] = mergedArray } else { // two items -> array mergedDictionary[key] = [lhsValue, rhsValue] } } return mergedDictionary } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: UserInfoTaggingProtocol, rhs: UserInfoTaggingProtocol) -> Dictionary<String, Any> { return lhs.dictionary | rhs.dictionary } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: UserInfoTaggingProtocol, rhs: Dictionary<String, Any>) -> Dictionary<String, Any> { return lhs.dictionary | rhs } /// Overloaded operator, converts UserInfoTaggingProtocol types to dictionaries and then merges them public func | (lhs: Dictionary<String, Any>, rhs: UserInfoTaggingProtocol) -> Dictionary<String, Any> { return rhs.dictionary | lhs } /// Extend UserInfoFilter to be able to use UserInfoTaggingProtocol objects public extension UserInfoFilter { /// Initializer to create an inclusion list of tags to match against /// /// Note: Only log messages with a specific tag will be logged, all others will be excluded /// /// - Parameters: /// - tags: Array of UserInfoTaggingProtocol objects to match against. /// public convenience init(includeFrom tags: [UserInfoTaggingProtocol]) { var names: [String] = [] for tag in tags { names.append(tag.name) } self.init(includeFrom: names) } /// Initializer to create an exclusion list of tags to match against /// /// Note: Log messages with a specific tag will be excluded from logging /// /// - Parameters: /// - tags: Array of UserInfoTaggingProtocol objects to match against. /// public convenience init(excludeFrom tags: [UserInfoTaggingProtocol]) { var names: [String] = [] for tag in tags { names.append(tag.name) } self.init(excludeFrom: names) } }
mit
02fde78c7fb75245da0485a6459d69cc
32.662857
125
0.649126
4.570209
false
false
false
false
githubError/KaraNotes
KaraNotes/KaraNotes/Attention/Controller/CPFSearchController.swift
1
8814
// // CPFSearchController.swift // KaraNotes // // Created by 崔鹏飞 on 2017/4/24. // Copyright © 2017年 崔鹏飞. All rights reserved. // import UIKit import Alamofire class CPFSearchController: BaseViewController { fileprivate var searchBar:UISearchBar! fileprivate var articleModels: [CPFSearchArticleModel] = [] fileprivate var userModels: [CPFSearchUserModel] = [] fileprivate var tableView:UITableView! fileprivate let SearchUserCellID: String = "searchUserCell" fileprivate let SearchArticleCellID: String = "searchArticleCell" fileprivate let modalTransitioningDelegate = CPFModalTransitioningDelegate() override func viewDidLoad() { super.viewDidLoad() setupSubviews() } } // MARK: - UISearchBarDelegate extension CPFSearchController: UISearchBarDelegate { func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) { if !searchText.hasSuffix("\n") { return } searchBarSearchButtonClicked(searchBar) } func searchBarSearchButtonClicked(_ searchBar: UISearchBar) { searchBar.resignFirstResponder() let params = ["token_id":getUserInfoForKey(key: CPFUserToken), "keywords":searchBar.text!, "pagenum":"0", "pagesize":"3"] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .searchUser), method: .post, parameters: params, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let result = json["result"] as? JSONDictionary else { fatalError("解析 search 用户列表失败")} guard let userlist = result["userlist"] as? [JSONDictionary] else { fatalError("解析 search 用户列表失败")} self.userModels = userlist.map({ (json) -> CPFSearchUserModel in return CPFSearchUserModel.parse(json: json) }) self.tableView.reloadData() case .failure(let error): print(error.localizedDescription) default: print("Unkonw error when search user list") } } let articleParams = ["pagenum": "0", "pagesize": "3", "keywords": searchBar.text!] Alamofire.request(CPFNetworkRoute.getAPIFromRouteType(route: .searchArticle), method: .post, parameters: articleParams, encoding: JSONEncoding.default, headers: [:]).responseJSON { (response) in switch response.result { case .success(let json as JSONDictionary): guard let code = json["code"] as? String else { fatalError("解析 search 文章列表失败")} if code != "1" { return } guard let result = json["result"] as? [JSONDictionary] else { fatalError("解析 search 文章列表失败")} self.articleModels = result.map({ (json) -> CPFSearchArticleModel in return CPFSearchArticleModel.parse(json: json) }) self.tableView.reloadData() case .failure(let error): print(error.localizedDescription) default: print("Unkonw error when search article list") } } } } // MARK: - setup subviews extension CPFSearchController { func setupSubviews() -> Void { setupNavSearchBar() setupTableView() } func setupNavSearchBar() -> Void { let titleView = UIView() titleView.frame = CGRect(x: 0, y: 0, width: CPFScreenW, height: 30) searchBar = UISearchBar() searchBar.delegate = self searchBar.setBackgroundImage(UIImage.init(), for: .any, barMetrics: .default) searchBar.setImage(UIImage.init(named: "search")?.scaleToSize(newSize: CGSize(width: 15, height: 15)), for: .search, state: .normal) searchBar.backgroundColor = UIColor.clear searchBar.placeholder = CPFLocalizableTitle("attention_search_placeholder") searchBar.tintColor = UIColor.white let textFiled:UITextField = searchBar.value(forKeyPath: "_searchField") as! UITextField textFiled.setValue(UIColor.white, forKeyPath: "_placeholderLabel.textColor") textFiled.backgroundColor = CPFRGBA(r: 0, g: 0, b: 0, a: 0.4) textFiled.textColor = UIColor.white titleView.addSubview(searchBar) searchBar.snp.makeConstraints { (make) in make.left.right.top.bottom.equalToSuperview() } navigationItem.titleView = titleView } func setupTableView() -> Void { tableView = UITableView(frame: view.bounds, style: .grouped) tableView.register(CPFSearchUserCell.self, forCellReuseIdentifier: SearchUserCellID) tableView.register(CPFSearchArticleCell.self, forCellReuseIdentifier: SearchArticleCellID) tableView.contentInset = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0) tableView.separatorStyle = .singleLine tableView.delegate = self tableView.dataSource = self view.addSubview(tableView) } } extension CPFSearchController: UITableViewDelegate, UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 2 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return section == 0 ? userModels.count : articleModels.count } func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? { if section == 0 && userModels.count > 0 { return CPFLocalizableTitle("user") } if section == 1 && articleModels.count > 0 { return CPFLocalizableTitle("article") } // if userModels.count == 0 && articleModels.count > 0 { // print("----------------") // tableView.contentInset = UIEdgeInsets(top: -50, left: 0, bottom: 0, right: 0) // } else { // print("+++++") // tableView.contentInset = UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0) // } // tableView.contentInset = (userModels.count == 0 && articleModels.count > 0) ? UIEdgeInsets(top: -50, left: 0, bottom: 0, right: 0) : UIEdgeInsets(top: -20, left: 0, bottom: 0, right: 0) return "" } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = indexPath.section == 0 ? tableView.dequeueReusableCell(withIdentifier: SearchUserCellID) as! CPFSearchUserCell : tableView.dequeueReusableCell(withIdentifier: SearchArticleCellID) as! CPFSearchArticleCell switch indexPath.section { case 0: (cell as! CPFSearchUserCell).userModel = userModels[indexPath.row] default: (cell as! CPFSearchArticleCell).searchArticleModel = articleModels[indexPath.row] } return cell } func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let currentCell = tableView.cellForRow(at: indexPath) // 相对 keyWindow 的位置 let keyWindow = UIApplication.shared.keyWindow let currentCellItemRectInSuperView = currentCell?.superview?.convert((currentCell?.frame)!, to: keyWindow) modalTransitioningDelegate.startRect = CGRect(x: 0.0, y: (currentCellItemRectInSuperView?.origin.y)!, width: CPFScreenW, height: 85.0) switch indexPath.section { case 0: print("用户列表") default: // 文章列表 let articleModel = articleModels[indexPath.row] let browseArticleCtr = CPFBrowseArticleController() browseArticleCtr.isMyArticle = false browseArticleCtr.thumbImage = (currentCell as! CPFSearchArticleCell).thumbImage browseArticleCtr.articleID = articleModel.article_id browseArticleCtr.articleTitle = articleModel.article_title browseArticleCtr.articleCreateTime = articleModel.article_create_formatTime browseArticleCtr.articleAuthorName = articleModel.user_name browseArticleCtr.transitioningDelegate = modalTransitioningDelegate browseArticleCtr.modalPresentationStyle = .custom present(browseArticleCtr, animated: true, completion: nil) } } func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 85.0 } }
apache-2.0
e613242cddea4ff9008ac878f7c6bd5d
41.276699
223
0.629808
4.982265
false
false
false
false
khizkhiz/swift
stdlib/public/core/StringUnicodeScalarView.swift
2
13439
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// @warn_unused_result public func ==( lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index ) -> Bool { return lhs._position == rhs._position } @warn_unused_result public func <( lhs: String.UnicodeScalarView.Index, rhs: String.UnicodeScalarView.Index ) -> Bool { return lhs._position < rhs._position } extension String { /// A collection of [Unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value) that /// encodes a `String` value. public struct UnicodeScalarView : Collection, CustomStringConvertible, CustomDebugStringConvertible { internal init(_ _core: _StringCore) { self._core = _core } internal struct _ScratchIterator : IteratorProtocol { var core: _StringCore var idx: Int init(_ core: _StringCore, _ pos: Int) { self.idx = pos self.core = core } mutating func next() -> UTF16.CodeUnit? { if idx == core.endIndex { return nil } defer { idx += 1 } return self.core[idx] } } /// A position in a `String.UnicodeScalarView`. public struct Index : BidirectionalIndex, Comparable { public init(_ _position: Int, _ _core: _StringCore) { self._position = _position self._core = _core } /// Returns the next consecutive value after `self`. /// /// - Precondition: The next value is representable. @warn_unused_result public func successor() -> Index { var scratch = _ScratchIterator(_core, _position) var decoder = UTF16() let (_, length) = decoder._decodeOne(&scratch) return Index(_position + length, _core) } /// Returns the previous consecutive value before `self`. /// /// - Precondition: The previous value is representable. @warn_unused_result public func predecessor() -> Index { var i = _position-1 let codeUnit = _core[i] if _slowPath((codeUnit >> 10) == 0b1101_11) { if i != 0 && (_core[i - 1] >> 10) == 0b1101_10 { i -= 1 } } return Index(i, _core) } /// The end index that for this view. internal var _viewStartIndex: Index { return Index(_core.startIndex, _core) } /// The end index that for this view. internal var _viewEndIndex: Index { return Index(_core.endIndex, _core) } internal var _position: Int internal var _core: _StringCore } /// The position of the first `UnicodeScalar` if the `String` is /// non-empty; identical to `endIndex` otherwise. public var startIndex: Index { return Index(_core.startIndex, _core) } /// The "past the end" position. /// /// `endIndex` is not a valid argument to `subscript`, and is always /// reachable from `startIndex` by zero or more applications of /// `successor()`. public var endIndex: Index { return Index(_core.endIndex, _core) } /// Access the element at `position`. /// /// - Precondition: `position` is a valid position in `self` and /// `position != endIndex`. public subscript(position: Index) -> UnicodeScalar { var scratch = _ScratchIterator(_core, position._position) var decoder = UTF16() switch decoder.decode(&scratch) { case .scalarValue(let us): return us case .emptyInput: _sanityCheckFailure("cannot subscript using an endIndex") case .error: return UnicodeScalar(0xfffd) } } /// Access the contiguous subrange of elements enclosed by `bounds`. /// /// - Complexity: O(1) unless bridging from Objective-C requires an /// O(N) conversion. public subscript(r: Range<Index>) -> UnicodeScalarView { return UnicodeScalarView( _core[r.startIndex._position..<r.endIndex._position]) } /// A type whose instances can produce the elements of this /// sequence, in order. public struct Iterator : IteratorProtocol { init(_ _base: _StringCore) { if _base.hasContiguousStorage { self._baseSet = true if _base.isASCII { self._ascii = true self._asciiBase = UnsafeBufferPointer<UInt8>( start: UnsafePointer(_base._baseAddress), count: _base.count).makeIterator() } else { self._ascii = false self._base = UnsafeBufferPointer<UInt16>( start: UnsafePointer(_base._baseAddress), count: _base.count).makeIterator() } } else { self._ascii = false self._baseSet = false self._iterator = _base.makeIterator() } } /// Advance to the next element and return it, or `nil` if no next /// element exists. /// /// - Precondition: No preceding call to `self.next()` has returned /// `nil`. public mutating func next() -> UnicodeScalar? { var result: UnicodeDecodingResult if _baseSet { if _ascii { switch self._asciiBase.next() { case let x?: result = .scalarValue(UnicodeScalar(x)) case nil: result = .emptyInput } } else { result = _decoder.decode(&(self._base!)) } } else { result = _decoder.decode(&(self._iterator!)) } switch result { case .scalarValue(let us): return us case .emptyInput: return nil case .error: return UnicodeScalar(0xfffd) } } internal var _decoder: UTF16 = UTF16() internal let _baseSet: Bool internal let _ascii: Bool internal var _asciiBase: UnsafeBufferPointerIterator<UInt8>! internal var _base: UnsafeBufferPointerIterator<UInt16>! internal var _iterator: IndexingIterator<_StringCore>! } /// Returns an iterator over the `UnicodeScalar`s that comprise /// this sequence. /// /// - Complexity: O(1). @warn_unused_result public func makeIterator() -> Iterator { return Iterator(_core) } public var description: String { return String(_core[startIndex._position..<endIndex._position]) } public var debugDescription: String { return "StringUnicodeScalarView(\(self.description.debugDescription))" } internal var _core: _StringCore } /// Construct the `String` corresponding to the given sequence of /// Unicode scalars. public init(_ unicodeScalars: UnicodeScalarView) { self.init(unicodeScalars._core) } /// The index type for subscripting a `String`'s `.unicodeScalars` /// view. public typealias UnicodeScalarIndex = UnicodeScalarView.Index } extension String { /// The value of `self` as a collection of [Unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value). public var unicodeScalars : UnicodeScalarView { get { return UnicodeScalarView(_core) } set { _core = newValue._core } } } extension String.UnicodeScalarView : RangeReplaceableCollection { /// Construct an empty instance. public init() { self = String.UnicodeScalarView(_StringCore()) } /// Reserve enough space to store `n` ASCII characters. /// /// - Complexity: O(`n`). public mutating func reserveCapacity(n: Int) { _core.reserveCapacity(n) } /// Append `x` to `self`. /// /// - Complexity: Amortized O(1). public mutating func append(x: UnicodeScalar) { _core.append(x) } /// Append the elements of `newElements` to `self`. /// /// - Complexity: O(*length of result*). public mutating func append< S : Sequence where S.Iterator.Element == UnicodeScalar >(contentsOf newElements: S) { _core.append(contentsOf: newElements.lazy.flatMap { $0.utf16 }) } /// Replace the elements within `bounds` with `newElements`. /// /// Invalidates all indices with respect to `self`. /// /// - Complexity: O(`bounds.count`) if `bounds.endIndex /// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise. public mutating func replaceSubrange< C: Collection where C.Iterator.Element == UnicodeScalar >( bounds: Range<Index>, with newElements: C ) { let rawSubRange = bounds.startIndex._position ..< bounds.endIndex._position let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 } _core.replaceSubrange(rawSubRange, with: lazyUTF16) } } // Index conversions extension String.UnicodeScalarIndex { /// Construct the position in `unicodeScalars` that corresponds exactly to /// `utf16Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf16Index` is an element of /// `String(unicodeScalars).utf16.indices`. public init?( _ utf16Index: String.UTF16Index, within unicodeScalars: String.UnicodeScalarView ) { let utf16 = String.UTF16View(unicodeScalars._core) if utf16Index != utf16.startIndex && utf16Index != utf16.endIndex { _precondition( utf16Index >= utf16.startIndex && utf16Index <= utf16.endIndex, "Invalid String.UTF16Index for this UnicodeScalar view") // Detect positions that have no corresponding index. Note that // we have to check before and after, because an unpaired // surrogate will be decoded as a single replacement character, // thus making the corresponding position valid. if UTF16.isTrailSurrogate(utf16[utf16Index]) && UTF16.isLeadSurrogate(utf16[utf16Index.predecessor()]) { return nil } } self.init(utf16Index._offset, unicodeScalars._core) } /// Construct the position in `unicodeScalars` that corresponds exactly to /// `utf8Index`. If no such position exists, the result is `nil`. /// /// - Precondition: `utf8Index` is an element of /// `String(unicodeScalars).utf8.indices`. public init?( _ utf8Index: String.UTF8Index, within unicodeScalars: String.UnicodeScalarView ) { let core = unicodeScalars._core _precondition( utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex, "Invalid String.UTF8Index for this UnicodeScalar view") // Detect positions that have no corresponding index. if !utf8Index._isOnUnicodeScalarBoundary { return nil } self.init(utf8Index._coreIndex, core) } /// Construct the position in `unicodeScalars` that corresponds /// exactly to `characterIndex`. /// /// - Precondition: `characterIndex` is an element of /// `String(unicodeScalars).indices`. public init( _ characterIndex: String.Index, within unicodeScalars: String.UnicodeScalarView ) { self.init(characterIndex._base._position, unicodeScalars._core) } /// Returns the position in `utf8` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf8)!.indices`. @warn_unused_result public func samePosition(in utf8: String.UTF8View) -> String.UTF8View.Index { return String.UTF8View.Index(self, within: utf8) } /// Returns the position in `utf16` that corresponds exactly /// to `self`. /// /// - Precondition: `self` is an element of `String(utf16)!.indices`. @warn_unused_result public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index { return String.UTF16View.Index(self, within: utf16) } /// Returns the position in `characters` that corresponds exactly /// to `self`, or if no such position exists, `nil`. /// /// - Precondition: `self` is an element of /// `characters.unicodeScalars.indices`. @warn_unused_result public func samePosition(in characters: String) -> String.Index? { return String.Index(self, within: characters) } internal var _isOnGraphemeClusterBoundary: Bool { let scalars = String.UnicodeScalarView(_core) if self == scalars.startIndex || self == scalars.endIndex { return true } let precedingScalar = scalars[self.predecessor()] let graphemeClusterBreakProperty = _UnicodeGraphemeClusterBreakPropertyTrie() let segmenter = _UnicodeExtendedGraphemeClusterSegmenter() let gcb0 = graphemeClusterBreakProperty.getPropertyRawValue( precedingScalar.value) if segmenter.isBoundaryAfter(gcb0) { return true } let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue( scalars[self].value) return segmenter.isBoundary(gcb0, gcb1) } } // Reflection extension String.UnicodeScalarView : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(self, unlabeledChildren: self) } } extension String.UnicodeScalarView : CustomPlaygroundQuickLookable { public var customPlaygroundQuickLook: PlaygroundQuickLook { return .text(description) } }
apache-2.0
3fe933dd613860294c30f206437cd8e5
30.845972
124
0.63286
4.448527
false
false
false
false
anirudh24seven/wikipedia-ios
Wikipedia/Code/WMFWelcomePanelViewController.swift
1
2903
class WMFWelcomePanelViewController: UIViewController { @IBOutlet private var containerView:UIView! @IBOutlet private var nextButton:UIButton! @IBOutlet private var titleLabel:UILabel! @IBOutlet private var subtitleLabel:UILabel! private var viewControllerForContainerView:UIViewController? = nil var welcomePageType:WMFWelcomePageType = .intro override func viewDidLoad() { super.viewDidLoad() embedContainerControllerView() updateUIStrings() nextButton.setTitleColor(UIColor.wmf_blueTintColor(), forState: .Normal) containerView.layer.borderWidth = 1.0 / UIScreen.mainScreen().scale } private func embedContainerControllerView() { if let containerController = containerController { containerController.willMoveToParentViewController(self) containerController.view.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview((containerController.view)!) containerController.view.mas_makeConstraints { make in make.top.bottom().leading().and().trailing().equalTo()(self.containerView) } self.addChildViewController(containerController) containerController.didMoveToParentViewController(self) } } private lazy var containerController: UIViewController? = { switch self.welcomePageType { case .intro: assert(false, "Intro welcome view is not embedded in a panel.") return nil case .languages: return WMFWelcomeLanguageTableViewController.wmf_viewControllerFromWelcomeStoryboard() case .analytics: return WMFWelcomeAnalyticsViewController.wmf_viewControllerFromWelcomeStoryboard() } }() private func updateUIStrings(){ switch self.welcomePageType { case .intro: assert(false, "Intro welcome view is not embedded in a panel.") case .languages: titleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-languages-title").uppercaseStringWithLocale(NSLocale.currentLocale()) subtitleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-languages-sub-title") nextButton.setTitle(localizedStringForKeyFallingBackOnEnglish("welcome-languages-continue-button").uppercaseStringWithLocale(NSLocale.currentLocale()), forState: .Normal) case .analytics: titleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-send-data-title").uppercaseStringWithLocale(NSLocale.currentLocale()) subtitleLabel.text = localizedStringForKeyFallingBackOnEnglish("welcome-send-data-sub-title") nextButton.setTitle(localizedStringForKeyFallingBackOnEnglish("button-done").uppercaseStringWithLocale(NSLocale.currentLocale()), forState: .Normal) } } }
mit
3c56864f8790cc922621a3c493847c86
48.20339
182
0.717534
6.137421
false
false
false
false
peteratseneca/dps923winter2015
Week_10/Places/Classes/StoreInitializer.swift
1
3155
// // StoreInitializer.swift // Classes // // Created by Peter McIntyre on 2015-02-01. // Copyright (c) 2015 School of ICT, Seneca College. All rights reserved. // import CoreData class StoreInitializer { class func create(cdStack: CDStack) { // Add code to create data // For each object that you want to create... // Initialize an object // Set its properties // Save changes // This app will work with the "Example" entity that you can see in the object model // If you have not yet run the app (in the simulator), // and you want to create your own object model, you can... // Comment out (or delete) the 'create data' code below // Delete the entity in the object model // Edit the Model class, and its fetched results controller // Comment out, delete, or edit the data access statements in the '...List' and '...Detail' controllers // If you have did run the app (in the simulator), // you will have to do the above, AND delete the app from the simulator let pb = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place pb.address = "111 Wellington Street, Ottawa, Ontario, Canada" let cw = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place cw.address = "9580 Jane Street, Vaughan, Ontario, Canada" let mr = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place mr.address = "1260 Remembrance Road, Montreal, Quebec, Canada" let wh = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place wh.address = "1600 Pennsylvania Avenue, Washington, D.C., United States of America" let bms = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place bms.address = "151 Speedway Boulevard, Bristol, Tennessee, United States of America" let apl = NSEntityDescription.insertNewObjectForEntityForName("Place", inManagedObjectContext: cdStack.managedObjectContext!) as! Place apl.address = "1 Infinite Loop, Cupertino, California, United States of America" cdStack.saveContext() } // Create a new date object class func newDate(year: Int, month: Int, day: Int) -> NSDate { // Configure the objects we need to create the date var cal = NSCalendar(identifier: NSCalendarIdentifierGregorian)! cal.timeZone = NSTimeZone(abbreviation: "GMT")! var dc = NSDateComponents() // Set the values of the date components dc.year = year dc.month = month dc.day = day dc.hour = 12 dc.minute = 0 dc.second = 0 return cal.dateFromComponents(dc)! } }
mit
f154fd4874fbd394ac1166d4149440b9
41.635135
143
0.658954
4.945141
false
false
false
false
larcus94/ImagePickerSheetController
ImagePickerSheetController/Example/ViewController.swift
2
4520
// // ViewController.swift // Example // // Created by Laurin Brandner on 26/05/15. // Copyright (c) 2015 Laurin Brandner. All rights reserved. // import UIKit import Photos import ImagePickerSheetController class ViewController: UIViewController { // MARK: - View Lifecycle override func viewDidLoad() { super.viewDidLoad() let button = UIButton(type: .system) button.setTitle("Tap Me!", for: []) button.translatesAutoresizingMaskIntoConstraints = false view.addSubview(button) button.heightAnchor.constraint(equalToConstant: 40).isActive = true button.widthAnchor.constraint(equalToConstant: 150).isActive = true button.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true button.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true button.addTarget(self, action: #selector(presentImagePickerSheet(gestureRecognizer:)), for: .touchUpInside) } // MARK: - Other Methods @objc func presentImagePickerSheet(gestureRecognizer: UITapGestureRecognizer) { let presentImagePickerController: (UIImagePickerController.SourceType) -> () = { source in let controller = UIImagePickerController() controller.delegate = self var sourceType = source if (!UIImagePickerController.isSourceTypeAvailable(sourceType)) { sourceType = .photoLibrary print("Fallback to camera roll as a source since the simulator doesn't support taking pictures") } controller.sourceType = sourceType self.present(controller, animated: true, completion: nil) } let controller = ImagePickerSheetController(mediaType: .imageAndVideo) controller.maximumSelection = 1 controller.delegate = self controller.addAction(ImagePickerAction(title: NSLocalizedString("Take Photo Or Video", comment: "Action Title"), secondaryTitle: NSLocalizedString("Add comment", comment: "Action Title"), handler: { _ in presentImagePickerController(.camera) }, secondaryHandler: { _, numberOfPhotos in print("Comment \(numberOfPhotos) photos") })) controller.addAction(ImagePickerAction(title: NSLocalizedString("Photo Library", comment: "Action Title"), secondaryTitle: { NSString.localizedStringWithFormat(NSLocalizedString("ImagePickerSheet.button1.Send %lu Photo", comment: "Action Title") as NSString, $0) as String}, handler: { _ in presentImagePickerController(.photoLibrary) }, secondaryHandler: { _, numberOfPhotos in print("Send \(controller.selectedAssets)") })) controller.addAction(ImagePickerAction(cancelTitle: NSLocalizedString("Cancel", comment: "Action Title"))) if UIDevice.current.userInterfaceIdiom == .pad { controller.modalPresentationStyle = .popover controller.popoverPresentationController?.sourceView = view controller.popoverPresentationController?.sourceRect = CGRect(origin: view.center, size: CGSize()) } present(controller, animated: true, completion: nil) } } // MARK: - UIImagePickerControllerDelegate extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate { func imagePickerControllerDidCancel(_ picker: UIImagePickerController) { dismiss(animated: true, completion: nil) } } // MARK: - ImagePickerSheetControllerDelegate extension ViewController: ImagePickerSheetControllerDelegate { func controllerWillEnlargePreview(_ controller: ImagePickerSheetController) { print("Will enlarge the preview") } func controllerDidEnlargePreview(_ controller: ImagePickerSheetController) { print("Did enlarge the preview") } func controller(_ controller: ImagePickerSheetController, willSelectAsset asset: PHAsset) { print("Will select an asset") } func controller(_ controller: ImagePickerSheetController, didSelectAsset asset: PHAsset) { print("Did select an asset") } func controller(_ controller: ImagePickerSheetController, willDeselectAsset asset: PHAsset) { print("Will deselect an asset") } func controller(_ controller: ImagePickerSheetController, didDeselectAsset asset: PHAsset) { print("Did deselect an asset") } }
mit
b0550b943fcd67f44dd3451c0882ec1a
40.46789
298
0.688053
5.721519
false
false
false
false
cuappdev/tcat-ios
TCAT/Views/DetailIconView.swift
1
7348
// // DetailIconView.swift // TCAT // // Created by Matthew Barker on 2/12/17. // Copyright © 2017 cuappdev. All rights reserved. // import UIKit import SnapKit class DetailIconView: UIView { private let labelLeadingInset: CGFloat = 16 private let labelInsetFromCenterY: CGFloat = 1 static let width: CGFloat = 114 private var scheduledLabelCentered: Constraint? private var scheduledLabelOffsetFromCenter: Constraint? private var isSet: Bool = false private var delayedTimeLabel = UILabel() private var scheduledTimeLabel = UILabel() private var connectorBottom = UIView() private var connectorTop = UIView() private var statusCircle: Circle! init(for direction: Direction, isFirstStep: Bool, isLastStep: Bool) { super.init(frame: .zero) // Format and place time labels scheduledTimeLabel.font = .getFont(.regular, size: 14) delayedTimeLabel.font = .getFont(.regular, size: 14) delayedTimeLabel.textColor = Colors.lateRed if direction.type == .walk { if isLastStep { statusCircle = Circle(size: .large, style: .bordered, color: Colors.dividerTextField) connectorTop.backgroundColor = Colors.dividerTextField connectorBottom.backgroundColor = .clear } else { statusCircle = Circle(size: .small, style: .solid, color: Colors.dividerTextField) connectorTop.backgroundColor = Colors.dividerTextField connectorBottom.backgroundColor = Colors.dividerTextField if isFirstStep { connectorTop.backgroundColor = .clear } } } else { if isLastStep { statusCircle = Circle(size: .large, style: .bordered, color: Colors.tcatBlue) connectorTop.backgroundColor = Colors.tcatBlue connectorBottom.backgroundColor = .clear } else { statusCircle = Circle(size: .small, style: .solid, color: Colors.tcatBlue) if direction.type == .depart { connectorTop.backgroundColor = Colors.dividerTextField connectorBottom.backgroundColor = Colors.tcatBlue } else if direction.type == .transfer { connectorTop.backgroundColor = Colors.tcatBlue connectorBottom.backgroundColor = Colors.tcatBlue } else { // type == .arrive connectorTop.backgroundColor = Colors.tcatBlue connectorBottom.backgroundColor = Colors.dividerTextField } if isFirstStep { connectorTop.backgroundColor = .clear } } } if isFirstStep && isLastStep { connectorTop.backgroundColor = .clear connectorBottom.backgroundColor = .clear } addSubview(scheduledTimeLabel) addSubview(delayedTimeLabel) addSubview(connectorTop) addSubview(connectorBottom) addSubview(statusCircle) setupConstraints() updateTimes(with: direction, isLast: isLastStep) } private func setupConstraints() { let connectorTrailingInset = 14 let connectorWidth = 4 connectorTop.snp.makeConstraints { make in make.trailing.equalToSuperview().inset(connectorTrailingInset) make.top.equalToSuperview() make.bottom.equalTo(snp.centerY) make.width.equalTo(connectorWidth) } connectorBottom.snp.makeConstraints { make in make.trailing.equalTo(connectorTop) make.bottom.equalToSuperview() make.top.equalTo(snp.centerY) make.width.equalTo(connectorWidth) } statusCircle.snp.makeConstraints { make in make.centerY.equalToSuperview() make.size.equalTo(statusCircle.intrinsicContentSize) make.centerX.equalTo(connectorTop) } scheduledTimeLabel.snp.makeConstraints { make in make.leading.equalToSuperview().inset(labelLeadingInset) make.size.greaterThanOrEqualTo(scheduledTimeLabel.intrinsicContentSize) scheduledLabelOffsetFromCenter = make.bottom.equalTo(snp.centerY).offset(-labelInsetFromCenterY).constraint } scheduledLabelOffsetFromCenter?.deactivate() scheduledTimeLabel.snp.makeConstraints { make in scheduledLabelCentered = make.centerY.equalToSuperview().constraint } delayedTimeLabel.snp.makeConstraints { make in make.top.equalTo(snp.centerY).offset(labelInsetFromCenterY) make.size.greaterThanOrEqualTo(delayedTimeLabel.intrinsicContentSize) make.leading.equalToSuperview().inset(labelLeadingInset) } } private func setTimeLabelTexts(for direction: Direction, isLastStep: Bool) { var scheduledTimeString: String { if direction.type == .walk { return isLastStep ? direction.endTimeWithDelayDescription : direction.startTimeWithDelayDescription } else { return isLastStep ? direction.endTimeDescription : direction.startTimeDescription } } let delayedTimeString = isLastStep ? direction.endTimeWithDelayDescription : direction.startTimeWithDelayDescription scheduledTimeLabel.text = scheduledTimeString delayedTimeLabel.text = delayedTimeString } // MARK: - Utility Functions public func updateTimes(with newDirection: Direction, isLast: Bool = false) { updateTimeLabels(with: newDirection, isLast: isLast) } /// Update scheduled label with direction's delay description. Use self.direction by default. func updateTimeLabels(with direction: Direction, isLast: Bool = false) { setTimeLabelTexts(for: direction, isLastStep: isLast) if direction.type == .walk { scheduledTimeLabel.textColor = Colors.primaryText centerScheduledLabel() hideDelayedLabel() } else { if let delay = direction.delay { if delay < 60 { scheduledTimeLabel.textColor = Colors.liveGreen centerScheduledLabel() hideDelayedLabel() } else { scheduledTimeLabel.textColor = Colors.primaryText showDelayedLabel() offsetScheduledLabel() } } else { scheduledTimeLabel.textColor = Colors.primaryText hideDelayedLabel() centerScheduledLabel() } } } private func offsetScheduledLabel() { scheduledLabelCentered?.deactivate() scheduledLabelOffsetFromCenter?.activate() } private func centerScheduledLabel() { scheduledLabelOffsetFromCenter?.deactivate() scheduledLabelCentered?.activate() } func hideDelayedLabel() { delayedTimeLabel.isHidden = true } func showDelayedLabel() { delayedTimeLabel.isHidden = false } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
mit
9244d28ec42ae28adce246833370ae67
35.735
124
0.628964
5.406181
false
false
false
false
practicalswift/swift
stdlib/public/core/SetAnyHashableExtensions.swift
8
1630
//===----------------------------------------------------------------------===// // // This source file is part of the Swift.org open source project // // Copyright (c) 2014 - 2017 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 // //===----------------------------------------------------------------------===// //===----------------------------------------------------------------------===// // Convenience APIs for Set<AnyHashable> //===----------------------------------------------------------------------===// extension Set where Element == AnyHashable { @inlinable public mutating func insert<ConcreteElement : Hashable>( _ newMember: __owned ConcreteElement ) -> (inserted: Bool, memberAfterInsert: ConcreteElement) { let (inserted, memberAfterInsert) = insert(AnyHashable(newMember)) return ( inserted: inserted, memberAfterInsert: memberAfterInsert.base as! ConcreteElement) } @inlinable @discardableResult public mutating func update<ConcreteElement : Hashable>( with newMember: __owned ConcreteElement ) -> ConcreteElement? { return update(with: AnyHashable(newMember)) .map { $0.base as! ConcreteElement } } @inlinable @discardableResult public mutating func remove<ConcreteElement : Hashable>( _ member: ConcreteElement ) -> ConcreteElement? { return remove(AnyHashable(member)) .map { $0.base as! ConcreteElement } } }
apache-2.0
b9c42c172dce93a7b17e5dd0a30c5d2a
34.434783
80
0.57546
5.451505
false
false
false
false
tevelee/CodeGenerator
output/swift/PersonLenses.swift
1
2441
import Foundation extension Person { struct Lenses { static let firstName: Lens<Person, String> = Lens( get: { $0.firstName }, set: { (person, firstName) in var builder = PersonBuilder(existingPerson: person) return builder.withFirstName(firstName).build() } ) static let lastName: Lens<Person, String> = Lens( get: { $0.lastName }, set: { (person, lastName) in var builder = PersonBuilder(existingPerson: person) return builder.withLastName(lastName).build() } ) static let nickName: Lens<Person, String> = Lens( get: { $0.nickName }, set: { (person, nickName) in var builder = PersonBuilder(existingPerson: person) return builder.withNickName(nickName).build() } ) static let age: Lens<Person, Int> = Lens( get: { $0.age }, set: { (person, age) in var builder = PersonBuilder(existingPerson: person) return builder.withAge(age).build() } ) static let address: Lens<Person, Address> = Lens( get: { $0.address }, set: { (person, address) in var builder = PersonBuilder(existingPerson: person) return builder.withAddress(address).build() } ) } } struct BoundLensToPerson<Whole>: BoundLensType { typealias Part = Person let storage: BoundLensStorage<Whole, Part> var firstName: BoundLens<Whole, String> { return BoundLens<Whole, String>(parent: self, sublens: Person.Lenses.firstName) } var lastName: BoundLens<Whole, String> { return BoundLens<Whole, String>(parent: self, sublens: Person.Lenses.lastName) } var nickName: BoundLens<Whole, String> { return BoundLens<Whole, String>(parent: self, sublens: Person.Lenses.nickName) } var age: BoundLens<Whole, Int> { return BoundLens<Whole, Int>(parent: self, sublens: Person.Lenses.age) } var address: BoundLensToAddress<Whole> { return BoundLensToAddress<Whole>(parent: self, sublens: Person.Lenses.address) } } extension Person { var lens: BoundLensToPerson<Person> { return BoundLensToPerson<Person>(instance: self, lens: createIdentityLens()) } }
mit
6e129feffcea5fa23ac15862389acc98
32.902778
87
0.583367
4.245217
false
false
false
false
fernandomarins/food-drivr-pt
hackathon-for-hunger/Modules/Driver/Maps/Models/DonorInfo.swift
1
1294
// // DonorInfo.swift // hackathon-for-hunger // // Created by David Fierstein on 4/3/16. // Copyright © 2016 Hacksmiths. All rights reserved. // import Foundation struct DonorInfo { var timestamp: NSDate? var name: String? var location: String? var lon: Double? var lat: Double? init() { // property values default to nil } init(data: NSDictionary) { /* Timestamp of donation, will be used later if let timestampString = data.valueForKey("updatedAt") as? String { let dateFormatter = NSDateFormatter() dateFormatter.timeZone = NSTimeZone(name: "UTC") dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'" let timestamp = dateFormatter.dateFromString(timestampString) self.timestamp = timestamp } */ name = (data.valueForKey("name") as! String) if let mapString = data.valueForKey("mapString") as? String { location = mapString } if let lonString = (data.valueForKey("longitude") as? NSNumber) { lon = lonString.doubleValue } if let latString = (data.valueForKey("latitude") as? NSNumber) { lat = latString.doubleValue } } }
mit
e7400dd4281fcda339a870233287a611
26.510638
75
0.589327
4.368243
false
false
false
false
testpress/ios-app
ios-app/UI/BaseQuestionsDataSource.swift
1
3099
// // BaseQuestionsDataSource.swift // ios-app // // Copyright © 2017 Testpress. All rights reserved. // // 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 import RealmSwift class BaseQuestionsDataSource: NSObject, UIPageViewControllerDataSource { var attemptItems = [AttemptItem]() init(_ attemptItems: [AttemptItem] = [AttemptItem]()) { super.init() self.attemptItems = attemptItems } func viewControllerAtIndex(_ index: Int) -> BaseQuestionsViewController? { if (attemptItems.count == 0) || (index >= attemptItems.count) { return nil } let attemptItem = attemptItems[index] try! Realm().write { attemptItem.index = index } let viewController = getQuestionsViewController() viewController.attemptItem = attemptItem return viewController } func getQuestionsViewController() -> BaseQuestionsViewController { return BaseQuestionsViewController() } func indexOfViewController(_ viewController: BaseQuestionsViewController) -> Int { return viewController.attemptItem!.index } // MARK: - Page View Controller Data Source func pageViewController(_ pageViewController: UIPageViewController, viewControllerBefore viewController: UIViewController) -> UIViewController? { var index = indexOfViewController(viewController as! BaseQuestionsViewController) if index == 0 { return nil } index -= 1 return viewControllerAtIndex(index) } func pageViewController(_ pageViewController: UIPageViewController, viewControllerAfter viewController: UIViewController) -> UIViewController? { var index = indexOfViewController(viewController as! BaseQuestionsViewController) index += 1 if index == attemptItems.count { return nil } return viewControllerAtIndex(index) } }
mit
d16fbdcb5cd271997fc5341b341e7c07
35.023256
92
0.683021
5.332186
false
false
false
false
devincoughlin/swift
test/SILOptimizer/di_property_wrappers.swift
1
9692
// RUN: %empty-directory(%t) // RUN: %target-build-swift %s -o %t/a.out // RUN: %target-run %t/a.out | %FileCheck %s // REQUIRES: executable_test @propertyWrapper struct Wrapper<T> { var wrappedValue: T { didSet { print(" .. set \(wrappedValue)") } } init(wrappedValue initialValue: T) { print(" .. init \(initialValue)") self.wrappedValue = initialValue } } protocol IntInitializable { init(_: Int) } final class Payload : CustomStringConvertible, IntInitializable { let payload: Int init(_ p: Int) { self.payload = p print(" + payload alloc \(payload)") } deinit { print(" - payload free \(payload)") } var description: String { return "value = \(payload)" } } struct IntStruct { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } // Check that we don't crash if the function has unrelated generic parameters. // SR-11484 mutating func setit<V>(_ v: V) { wrapped = 5 } } final class IntClass { @Wrapper var wrapped: Int init() { wrapped = 42 wrapped = 27 } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: 32) } else { wrapped = 42 } } init(dynamic b: Bool) { if b { wrapped = 42 } wrapped = 27 } } struct RefStruct { @Wrapper var wrapped: Payload init() { wrapped = Payload(42) wrapped = Payload(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: Payload(32)) } else { wrapped = Payload(42) } } init(dynamic b: Bool) { if b { wrapped = Payload(42) } wrapped = Payload(27) } } final class GenericClass<T : IntInitializable> { @Wrapper var wrapped: T init() { wrapped = T(42) wrapped = T(27) } init(conditional b: Bool) { if b { self._wrapped = Wrapper(wrappedValue: T(32)) } else { wrapped = T(42) } } init(dynamic b: Bool) { if b { wrapped = T(42) } wrapped = T(27) } } func testIntStruct() { // CHECK: ## IntStruct print("\n## IntStruct") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 var t1 = IntStruct() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. set 5 t1.setit(false) // CHECK-NEXT: 5 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntStruct(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntStruct(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntStruct(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntStruct(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) } func testIntClass() { // CHECK: ## IntClass print("\n## IntClass") // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. set 27 let t1 = IntClass() // CHECK-NEXT: 27 print(t1.wrapped) // CHECK-NEXT: .. init 42 let t2 = IntClass(conditional: false) // CHECK-NEXT: 42 print(t2.wrapped) // CHECK-NEXT: .. init 32 let t3 = IntClass(conditional: true) // CHECK-NEXT: 32 print(t3.wrapped) // CHECK-NEXT: .. init 27 let t4 = IntClass(dynamic: false) // CHECK-NEXT: 27 print(t4.wrapped) // CHECK-NEXT: .. init 42 // CHECK-NEXT: .. init 27 let t5 = IntClass(dynamic: true) // CHECK-NEXT: 27 print(t5.wrapped) } func testRefStruct() { // CHECK: ## RefStruct print("\n## RefStruct") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. set value = 27 // CHECK-NEXT: - payload free 42 let t1 = RefStruct() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = RefStruct(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = RefStruct(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = RefStruct(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = RefStruct(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } func testGenericClass() { // CHECK: ## GenericClass print("\n## GenericClass") if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. set value = 27 // CHECK-NEXT: - payload free 42 let t1 = GenericClass<Payload>() // CHECK-NEXT: value = 27 print(t1.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 let t2 = GenericClass<Payload>(conditional: false) // CHECK-NEXT: value = 42 print(t2.wrapped) // CHECK-NEXT: - payload free 42 } if true { // CHECK-NEXT: + payload alloc 32 // CHECK-NEXT: .. init value = 32 let t3 = GenericClass<Payload>(conditional: true) // CHECK-NEXT: value = 32 print(t3.wrapped) // CHECK-NEXT: - payload free 32 } if true { // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: .. init value = 27 let t4 = GenericClass<Payload>(dynamic: false) // CHECK-NEXT: value = 27 print(t4.wrapped) // CHECK-NEXT: - payload free 27 } if true { // CHECK-NEXT: + payload alloc 42 // CHECK-NEXT: .. init value = 42 // CHECK-NEXT: + payload alloc 27 // CHECK-NEXT: - payload free 42 // CHECK-NEXT: .. init value = 27 let t5 = GenericClass<Payload>(dynamic: true) // CHECK-NEXT: value = 27 print(t5.wrapped) // CHECK-NEXT: - payload free 27 } } @propertyWrapper struct WrapperWithDefaultInit<Value> { private var _value: Value? = nil init() { print("default init called on \(Value.self)") } var wrappedValue: Value { get { return _value! } set { print("set value \(newValue)") _value = newValue } } } struct UseWrapperWithDefaultInit { @WrapperWithDefaultInit<Int> var x: Int @WrapperWithDefaultInit<String> var y: String init(y: String) { self.y = y } } func testDefaultInit() { // CHECK: ## DefaultInit print("\n## DefaultInit") let use = UseWrapperWithDefaultInit(y: "hello") // CHECK: default init called on Int // FIXME: DI should eliminate the following call // CHECK: default init called on String // CHECK: set value hello } // rdar://problem/51581937: DI crash with a property wrapper of an optional struct OptIntStruct { @Wrapper var wrapped: Int? init() { wrapped = 42 } } func testOptIntStruct() { // CHECK: ## OptIntStruct print("\n## OptIntStruct") let use = OptIntStruct() // CHECK-NEXT: .. init nil // CHECK-NEXT: .. set Optional(42) } // rdar://problem/53504653 struct DefaultNilOptIntStruct { @Wrapper var wrapped: Int? init() { } } func testDefaultNilOptIntStruct() { // CHECK: ## DefaultNilOptIntStruct print("\n## DefaultNilOptIntStruct") let use = DefaultNilOptIntStruct() // CHECK-NEXT: .. init nil } @propertyWrapper struct Wrapper2<T> { var wrappedValue: T { didSet { print(" .. secondSet \(wrappedValue)") } } init(before: Int = -10, wrappedValue initialValue: T, after: String = "end") { print(" .. secondInit \(before), \(initialValue), \(after)") self.wrappedValue = initialValue } } struct HasComposed { @Wrapper @Wrapper2 var x: Int init() { self.x = 17 } } func testComposed() { // CHECK: ## Composed print("\n## Composed") _ = HasComposed() // CHECK-NEXT: .. secondInit -10, 17, end // CHECK-NEXT: .. init Wrapper2<Int>(wrappedValue: 17) } // SR-11477 @propertyWrapper struct SR_11477_W { let name: String init(name: String = "DefaultParamInit") { self.name = name } var wrappedValue: Int { get { return 0 } } } @propertyWrapper struct SR_11477_W1 { let name: String init() { self.name = "Init" } init(name: String = "DefaultParamInit") { self.name = name } var wrappedValue: Int { get { return 0 } } } struct SR_11477_C { @SR_11477_W var property: Int @SR_11477_W1 var property1: Int init() {} func foo() { print(_property.name) } func foo1() { print(_property1.name) } } func testWrapperInitWithDefaultArg() { // CHECK: ## InitWithDefaultArg print("\n## InitWithDefaultArg") let use = SR_11477_C() use.foo() use.foo1() // CHECK-NEXT: DefaultParamInit // CHECK-NEXT: Init } testIntStruct() testIntClass() testRefStruct() testGenericClass() testDefaultInit() testOptIntStruct() testDefaultNilOptIntStruct() testComposed() testWrapperInitWithDefaultArg()
apache-2.0
b1e39bb5ba06fea35f52d108c87798de
18.983505
80
0.590693
3.436879
false
false
false
false
ualch9/onebusaway-iphone
Carthage/Checkouts/IGListKit/Examples/Examples-iOS/IGListKitExamples/Models/FeedItem.swift
2
1316
/** Copyright (c) Facebook, Inc. and its affiliates. 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 final class FeedItem: ListDiffable { let pk: Int let user: User let comments: [String] init(pk: Int, user: User, comments: [String]) { self.pk = pk self.user = user self.comments = comments } // MARK: ListDiffable func diffIdentifier() -> NSObjectProtocol { return pk as NSObjectProtocol } func isEqual(toDiffableObject object: ListDiffable?) -> Bool { guard self !== object else { return true } guard let object = object as? FeedItem else { return false } return user.isEqual(toDiffableObject: object.user) && comments == object.comments } }
apache-2.0
8e175ce9d7dfc126f19c2229367ce512
31.097561
89
0.705927
4.750903
false
false
false
false
mozilla-mobile/firefox-ios
Shared/SupportUtils.swift
2
2243
// This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at http://mozilla.org/MPL/2.0 import Foundation import UIKit /// Utility functions related to SUMO and Webcompat public struct SupportUtils { public static func URLForTopic(_ topic: String) -> URL? { /// Construct a NSURL pointing to a specific topic on SUMO. The topic should be a non-escaped string. It will /// be properly escaped by this function. /// /// The resulting NSURL will include the app version, operating system and locale code. For example, a topic /// "cheese" will be turned into a link that looks like https://support.mozilla.org/1/mobile/2.0/iOS/en-US/cheese guard let escapedTopic = topic.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed), let languageIdentifier = Locale.preferredLanguages.first else { return nil } return URL(string: "https://support.mozilla.org/1/mobile/\(AppInfo.appVersion)/iOS/\(languageIdentifier)/\(escapedTopic)") } public static func URLForReportSiteIssue(_ siteUrl: String?) -> URL? { /// Construct a NSURL pointing to the webcompat.com server to report an issue. /// /// It specifies the source as mobile-reporter. This helps the webcompat server to classify the issue. /// It also adds browser-firefox-ios to the labels in the URL to make it clear /// that this about Firefox on iOS. It makes it easier for webcompat people doing triage and diagnostics. /// It adds a device-type label to help discriminating in between tablet and mobile devices. let deviceType: String if UIDevice.current.userInterfaceIdiom == .pad { deviceType = "device-tablet" } else { deviceType = "device-mobile" } guard let escapedUrl = siteUrl?.addingPercentEncoding(withAllowedCharacters: .urlPathAllowed) else { return nil } return URL(string: "https://webcompat.com/issues/new?src=mobile-reporter&label=browser-firefox-ios&label=\(deviceType)&url=\(escapedUrl)") } }
mpl-2.0
9bc78a39da0c0556f85c99c81a6ec00d
51.162791
146
0.676326
4.643892
false
false
false
false
SuPair/firefox-ios
Extensions/NotificationService/NotificationService.swift
1
12517
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ import Account import Shared import Storage import Sync import UserNotifications class NotificationService: UNNotificationServiceExtension { var display: SyncDataDisplay? var profile: ExtensionProfile? // This is run when an APNS notification with `mutable-content` is received. // If the app is backgrounded, then the alert notification is displayed. // If the app is foregrounded, then the notification.userInfo is passed straight to // AppDelegate.application(_:didReceiveRemoteNotification:completionHandler:) // Once the notification is tapped, then the same userInfo is passed to the same method in the AppDelegate. override func didReceive(_ request: UNNotificationRequest, withContentHandler contentHandler: @escaping (UNNotificationContent) -> Void) { let userInfo = request.content.userInfo guard let content = (request.content.mutableCopy() as? UNMutableNotificationContent) else { return self.didFinish(PushMessage.accountVerified) } if self.profile == nil { self.profile = ExtensionProfile(localName: "profile") } guard let profile = self.profile else { self.didFinish(with: .noProfile) return } let queue = profile.queue let display = SyncDataDisplay(content: content, contentHandler: contentHandler, tabQueue: queue) self.display = display profile.syncDelegate = display let handler = FxAPushMessageHandler(with: profile) handler.handle(userInfo: userInfo).upon { res in self.didFinish(res.successValue, with: res.failureValue as? PushMessageError) } } func didFinish(_ what: PushMessage? = nil, with error: PushMessageError? = nil) { defer { // We cannot use tabqueue after the profile has shutdown; // however, we can't use weak references, because TabQueue isn't a class. // Rather than changing tabQueue, we manually nil it out here. self.display?.tabQueue = nil profile?.shutdown() } guard let display = self.display else { return } display.messageDelivered = false display.displayNotification(what, profile: profile, with: error) if !display.messageDelivered { display.displayUnknownMessageNotification() } } override func serviceExtensionTimeWillExpire() { // Called just before the extension will be terminated by the system. // Use this as an opportunity to deliver your "best attempt" at modified content, otherwise the original push payload will be used. didFinish(with: .timeout) } } class SyncDataDisplay { var contentHandler: ((UNNotificationContent) -> Void) var notificationContent: UNMutableNotificationContent var sentTabs: [SentTab] var tabQueue: TabQueue? var messageDelivered: Bool = false init(content: UNMutableNotificationContent, contentHandler: @escaping (UNNotificationContent) -> Void, tabQueue: TabQueue) { self.contentHandler = contentHandler self.notificationContent = content self.sentTabs = [] self.tabQueue = tabQueue } func displayNotification(_ message: PushMessage? = nil, profile: ExtensionProfile?, with error: PushMessageError? = nil) { guard let message = message, error == nil else { return displayUnknownMessageNotification() } switch message { case .commandReceived(let tab): displayNewSentTabNotification(tab: tab) case .accountVerified: displayAccountVerifiedNotification() case .deviceConnected(let deviceName): displayDeviceConnectedNotification(deviceName) case .deviceDisconnected(let deviceName): displayDeviceDisconnectedNotification(deviceName) case .thisDeviceDisconnected: displayThisDeviceDisconnectedNotification() case .collectionChanged(let collections): if collections.contains("clients") { displayOldSentTabNotification() } else { displayUnknownMessageNotification() } default: displayUnknownMessageNotification() break } } } extension SyncDataDisplay { func displayDeviceConnectedNotification(_ deviceName: String) { presentNotification(title: Strings.FxAPush_DeviceConnected_title, body: Strings.FxAPush_DeviceConnected_body, bodyArg: deviceName) } func displayDeviceDisconnectedNotification(_ deviceName: String?) { if let deviceName = deviceName { presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_body, bodyArg: deviceName) } else { // We should never see this branch presentNotification(title: Strings.FxAPush_DeviceDisconnected_title, body: Strings.FxAPush_DeviceDisconnected_UnknownDevice_body) } } func displayThisDeviceDisconnectedNotification() { presentNotification(title: Strings.FxAPush_DeviceDisconnected_ThisDevice_title, body: Strings.FxAPush_DeviceDisconnected_ThisDevice_body) } func displayAccountVerifiedNotification() { presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } func displayUnknownMessageNotification() { // if, by any change we haven't dealt with the message, then perhaps we // can recycle it as a sent tab message. if sentTabs.count > 0 { displayOldSentTabNotification() } else { presentNotification(title: Strings.SentTab_NoTabArrivingNotification_title, body: Strings.SentTab_NoTabArrivingNotification_body) } } } extension SyncDataDisplay { func displayNewSentTabNotification(tab: [String : String]) { if let urlString = tab["url"], let url = URL(string: urlString), url.isWebPage(), let title = tab["title"] { let tab = [ "title": title, "url": url.absoluteString, "displayURL": url.absoluteDisplayExternalString, "deviceName": nil ] as NSDictionary notificationContent.userInfo["sentTabs"] = [tab] as NSArray // Add tab to the queue. let item = ShareItem(url: urlString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. presentNotification(title: Strings.SentTab_TabArrivingNotification_NoDevice_title, body: url.absoluteDisplayExternalString) } } } extension SyncDataDisplay { func displayOldSentTabNotification() { // We will need to be more precise about calling these SentTab alerts // once we are a) detecting different types of notifications and b) adding actions. // For now, we need to add them so we can handle zero-tab sent-tab-notifications. notificationContent.categoryIdentifier = "org.mozilla.ios.SentTab.placeholder" var userInfo = notificationContent.userInfo // Add the tabs we've found to userInfo, so that the AppDelegate // doesn't have to do it again. let serializedTabs = sentTabs.compactMap { t -> NSDictionary? in return [ "title": t.title, "url": t.url.absoluteString, "displayURL": t.url.absoluteDisplayExternalString, "deviceName": t.deviceName as Any, ] as NSDictionary } func present(_ tabs: [NSDictionary]) { if !tabs.isEmpty { userInfo["sentTabs"] = tabs as NSArray } notificationContent.userInfo = userInfo presentSentTabsNotification(tabs) } let center = UNUserNotificationCenter.current() center.getDeliveredNotifications { notifications in // Let's deal with sent-tab-notifications let sentTabNotifications = notifications.filter { $0.request.content.categoryIdentifier == self.notificationContent.categoryIdentifier } // We can delete zero tab sent-tab-notifications let emptyTabNotificationsIds = sentTabNotifications.filter { $0.request.content.userInfo["sentTabs"] == nil }.map { $0.request.identifier } center.removeDeliveredNotifications(withIdentifiers: emptyTabNotificationsIds) // The one we've just received (but not delivered) may not have any tabs in it either // e.g. if the previous one consumed two tabs. if serializedTabs.count == 0 { // In that case, we try and recycle an existing notification (one that has a tab in it). if let firstNonEmpty = sentTabNotifications.first(where: { $0.request.content.userInfo["sentTabs"] != nil }), let previouslyDeliveredTabs = firstNonEmpty.request.content.userInfo["sentTabs"] as? [NSDictionary] { center.removeDeliveredNotifications(withIdentifiers: [firstNonEmpty.request.identifier]) return present(previouslyDeliveredTabs) } } // We have tabs in this notification, or we couldn't recycle an existing one that does. present(serializedTabs) } } func presentSentTabsNotification(_ tabs: [NSDictionary]) { let title: String let body: String if tabs.count == 0 { title = Strings.SentTab_NoTabArrivingNotification_title body = Strings.SentTab_NoTabArrivingNotification_body } else { let deviceNames = Set(tabs.compactMap { $0["deviceName"] as? String }) if let deviceName = deviceNames.first, deviceNames.count == 1 { title = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_title, deviceName) } else { title = Strings.SentTab_TabArrivingNotification_NoDevice_title } if tabs.count == 1 { // We give the fallback string as the url, // because we have only just introduced "displayURL" as a key. body = (tabs[0]["displayURL"] as? String) ?? (tabs[0]["url"] as! String) } else if deviceNames.count == 0 { body = Strings.SentTab_TabArrivingNotification_NoDevice_body } else { body = String(format: Strings.SentTab_TabArrivingNotification_WithDevice_body, AppInfo.displayName) } } presentNotification(title: title, body: body) } func presentNotification(title: String, body: String, titleArg: String? = nil, bodyArg: String? = nil) { func stringWithOptionalArg(_ s: String, _ a: String?) -> String { if let a = a { return String(format: s, a) } return s } notificationContent.title = stringWithOptionalArg(title, titleArg) notificationContent.body = stringWithOptionalArg(body, bodyArg) // This is the only place we call the contentHandler. contentHandler(notificationContent) // This is the only place we change messageDelivered. We can check if contentHandler hasn't be called because of // our logic (rather than something funny with our environment, or iOS killing us). messageDelivered = true } } extension SyncDataDisplay: SyncDelegate { func displaySentTab(for url: URL, title: String, from deviceName: String?) { if url.isWebPage() { sentTabs.append(SentTab(url: url, title: title, deviceName: deviceName)) let item = ShareItem(url: url.absoluteString, title: title, favicon: nil) _ = tabQueue?.addToQueue(item).value // Force synchronous. } } } struct SentTab { let url: URL let title: String let deviceName: String? }
mpl-2.0
1bf88f467906c6412dcdaa10c4052e29
40.584718
142
0.640569
5.437446
false
false
false
false
wolf81/WTFoundation
WTFoundation/WTErrorView.swift
1
2328
// // ErrorView.swift // Lolcats // // Created by Wolfgang Schreurs on 18/12/2016. // Copyright © 2016 Wolftrail. All rights reserved. // import UIKit public protocol WTErrorViewDelegate: class { func errorViewReloadAction(view: WTErrorView) } fileprivate extension Selector { static let reloadButtonTouchedUpInside = #selector(WTErrorView.reloadButtonTouchUpInside(_:)) } open class WTErrorView: WTView { private var errorLabel = UILabel() private var reloadButton = UIButton() weak open var delegate: WTErrorViewDelegate? override open func createSubviews() -> [UIView] { return [self.errorLabel, self.reloadButton] } override open func commonInit() { super.commonInit() self.errorLabel.textColor = .black self.errorLabel.textAlignment = .center self.reloadButton.setTitle("Reload", for: .normal) self.reloadButton.setTitleColor(.black, for: .normal) self.reloadButton.titleLabel?.font = UIFont.boldSystemFont(ofSize: 16) self.reloadButton.addTarget(self, action: .reloadButtonTouchedUpInside, for: .touchUpInside) } // MARK: - Layout override open func layoutSubviews() { super.layoutSubviews() let bounds = self.bounds let margin: CGFloat = 20.0 let maxWidth = bounds.width - (margin * 2) let constraint = CGSize(width: maxWidth, height: CGFloat.greatestFiniteMagnitude) let labelSize = self.errorLabel.sizeThatFits(constraint) let labelY = bounds.midY - labelSize.height - (margin / 2) self.errorLabel.frame = CGRect(x: margin, y: labelY, width: maxWidth, height: labelSize.height).integral let buttonY = self.errorLabel.frame.maxY + margin let buttonSize = self.reloadButton.sizeThatFits(constraint) self.reloadButton.frame = CGRect(x: margin, y: buttonY, width: maxWidth, height: buttonSize.height).integral } // MARK: - Public open func configure(error: Error) { self.errorLabel.text = error.localizedDescription setNeedsLayout() } // MARK: - Private @objc fileprivate func reloadButtonTouchUpInside(_: UIButton) { self.delegate?.errorViewReloadAction(view: self) } }
bsd-2-clause
710a4c62e11e103f46d5915d29d1e0ed
30.876712
116
0.662656
4.691532
false
false
false
false
exyte/Macaw
Source/animation/types/AnimationSequence.swift
1
2294
import Foundation internal class AnimationSequence: BasicAnimation { let animations: [BasicAnimation] required init(animations: [BasicAnimation], delay: Double = 0.0) { self.animations = animations super.init() self.type = .sequence self.node = animations.first?.node self.delay = delay } override func getDuration() -> Double { let originalDuration = animations.map { $0.getDuration() } .reduce(0) { $0 + $1 } if autoreverses { return originalDuration * 2.0 } return originalDuration } open override func stop() { super.stop() guard let active = animations.first(where: { $0.isActive() }) else { return } active.stop() } open override func pause() { super.pause() guard let active = animations.first(where: { $0.isActive() }) else { return } active.pause() } open override func play() { guard let active = animations.first(where: { $0.isActive() }) else { super.play() return } manualStop = false paused = false active.play() } open override func state() -> AnimationState { for animation in animations { let state = animation.state() if state != .initial { return state } } return .initial } open override func reverse() -> Animation { var reversedAnimations = [BasicAnimation]() animations.forEach { animation in reversedAnimations.append(animation.reverse() as! BasicAnimation) } let reversedSequence = reversedAnimations.reversed().sequence(delay: self.delay) as! BasicAnimation reversedSequence.completion = completion reversedSequence.progress = progress return reversedSequence } } public extension Sequence where Iterator.Element: Animation { func sequence(delay: Double = 0.0) -> Animation { var sequence = [BasicAnimation]() self.forEach { animation in sequence.append(animation as! BasicAnimation) } return AnimationSequence(animations: sequence, delay: delay) } }
mit
306bbeb8f2e0e2eb52e3942a1f5bae1a
23.666667
107
0.583697
4.891258
false
false
false
false
y0ke/actor-platform
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/WebActions/AAWebActionController.swift
2
1510
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation public class AAWebActionController: AAViewController, UIWebViewDelegate { private var webView = UIWebView() private let regex: AARegex private let desc: ACWebActionDescriptor public init(desc: ACWebActionDescriptor) { self.desc = desc self.regex = AARegex(desc.getRegexp()) super.init() } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public override func viewDidLoad() { super.viewDidLoad() webView.delegate = self view.addSubview(webView) webView.loadRequest(NSURLRequest(URL: NSURL(string: desc.getUri())!)) } public override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() webView.frame = view.bounds } public func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool { if let url = request.URL { let rawUrl = url.absoluteString // Match end url if regex.test(rawUrl) { self.executeSafe(Actor.completeWebActionWithHash(desc.getActionHash(), withUrl: rawUrl)) { (val) -> Void in self.dismiss() } return false } } return true } }
agpl-3.0
cec9464b42becd398934ec4bed692e9b
26.981481
144
0.594702
5.067114
false
false
false
false
crspybits/SMCoreLib
SMCoreLib/Classes/Views/SMImageTextView/SMImageTextView.swift
1
14473
// // SMImageTextView.swift // SMCoreLib // // Created by Christopher Prince on 5/21/16. // Copyright © 2016 Spastic Muffin, LLC. All rights reserved. // // A text view with images. Deals with keyboard appearing and disappearing by changing the .bottom property of the .contentInset. import Foundation import HPTextViewTapGestureRecognizer @objc public protocol SMImageTextViewDelegate : class { @objc optional func smImageTextView(_ imageTextView:SMImageTextView, imageWasDeleted imageId:Foundation.UUID?) // You should provide the UIImage corresponding to the NSUUID. Only in an error should this return nil. func smImageTextView(_ imageTextView: SMImageTextView, imageForUUID: Foundation.UUID) -> UIImage? @objc optional func smImageTextView(_ imageTextView: SMImageTextView, imageWasTapped imageId:Foundation.UUID?) } private class ImageTextAttachment : NSTextAttachment { var imageId:Foundation.UUID? } public func ==(lhs:SMImageTextView.ImageTextViewElement, rhs:SMImageTextView.ImageTextViewElement) -> Bool { return lhs.equals(rhs) } public func ===(lhs:SMImageTextView.ImageTextViewElement, rhs:SMImageTextView.ImageTextViewElement) -> Bool { return lhs.equalsWithRange(rhs) } open class SMImageTextView : UITextView, UITextViewDelegate { open weak var imageDelegate:SMImageTextViewDelegate? open var scalingFactor:CGFloat = 0.5 override open var delegate: UITextViewDelegate? { set { if newValue == nil { super.delegate = nil return } Assert.badMojo(alwaysPrintThisString: "Delegate is setup by SMImageTextView, but you can subclass and declare-- all but shouldChangeTextInRange.") } get { return super.delegate } } override init(frame: CGRect, textContainer: NSTextContainer?) { super.init(frame: frame, textContainer: textContainer) self.setup() } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) self.setup() } fileprivate func setup() { super.delegate = self NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillHide), name: UIResponder.keyboardWillHideNotification, object: nil) let tapGesture = HPTextViewTapGestureRecognizer() tapGesture.delegate = self self.addGestureRecognizer(tapGesture) } deinit { NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillShowNotification, object: nil) NotificationCenter.default.removeObserver(self, name: UIResponder.keyboardWillHideNotification, object: nil) } /* @objc private func imageTapGestureAction() { Log.msg("imageTapGestureAction") }*/ fileprivate var originalEdgeInsets:UIEdgeInsets? // There are a number of ways to get the text view to play well the keyboard *and* autolayout: http://stackoverflow.com/questions/14140536/resizing-an-uitextview-when-the-keyboard-pops-up-with-auto-layout (see https://developer.apple.com/library/ios/documentation/StringsTextFonts/Conceptual/TextAndWebiPhoneOS/KeyboardManagement/KeyboardManagement.html for the idea of changing bottom .contentInset). I didn't use http://stackoverflow.com/questions/12924649/autolayout-constraint-keyboard, but it seems to be another means. @objc fileprivate func keyboardWillShow(_ notification:Notification) { let info = notification.userInfo! let kbFrame = info[UIResponder.keyboardFrameEndUserInfoKey] as! NSValue let keyboardFrame = kbFrame.cgRectValue Log.msg("keyboardFrame: \(keyboardFrame)") self.originalEdgeInsets = self.contentInset var insets = self.contentInset insets.bottom += keyboardFrame.size.height self.contentInset = insets } @objc fileprivate func keyboardWillHide(_ notification:Notification) { self.contentInset = self.originalEdgeInsets! } open func insertImageAtCursorLocation(_ image:UIImage, imageId:Foundation.UUID?) { let attrStringWithImage = self.makeImageAttachment(image, imageId: imageId) self.textStorage.insert(attrStringWithImage, at: self.selectedRange.location) } fileprivate func makeImageAttachment(_ image:UIImage, imageId:Foundation.UUID?) -> NSAttributedString { // Modified from http://stackoverflow.com/questions/24010035/how-to-add-image-and-text-in-uitextview-in-ios let textAttachment = ImageTextAttachment() textAttachment.imageId = imageId let oldWidth = image.size.width //I'm subtracting 10px to make the image display nicely, accounting //for the padding inside the textView let scaleFactor = oldWidth / (self.frameWidth - 10) textAttachment.image = UIImage(cgImage: image.cgImage!, scale: scaleFactor/self.scalingFactor, orientation: image.imageOrientation) let attrStringWithImage = NSAttributedString(attachment: textAttachment) return attrStringWithImage } fileprivate static let ElementType = "ElementType" fileprivate static let ElementTypeText = "Text" fileprivate static let ElementTypeImage = "Image" fileprivate static let RangeLocation = "RangeLocation" fileprivate static let RangeLength = "RangeLength" fileprivate static let Contents = "Contents" public enum ImageTextViewElement : Equatable { case Text(String, NSRange) case image(UIImage?, Foundation.UUID?, NSRange) public var text:String? { switch self { case .Text(let string, _): return string case .image: return nil } } // Doesn't test range. For text, tests string. For image, tests uuid. public func equals(_ other:SMImageTextView.ImageTextViewElement) -> Bool { switch self { case .Text(let string, _): switch other { case .Text(let stringOther, _): return string == stringOther case .image: return false } case .image(_, let uuid, _): switch other { case .image(_, let uuidOther, _): return uuid == uuidOther case .Text: return false } } } public func equalsWithRange(_ other:SMImageTextView.ImageTextViewElement) -> Bool { switch self { case .Text(let string, let range): switch other { case .Text(let stringOther, let rangeOther): return string == stringOther && range.length == rangeOther.length && range.location == rangeOther.location case .image: return false } case .image(_, let uuid, let range): switch other { case .image(_, let uuidOther, let rangeOther): return uuid == uuidOther && range.length == rangeOther.length && range.location == rangeOther.location case .Text: return false } } } public func toDictionary() -> [String:AnyObject] { switch self { case .Text(let string, let range): return [ElementType: ElementTypeText as AnyObject, RangeLocation: range.location as AnyObject, RangeLength: range.length as AnyObject, Contents: string as AnyObject] case .image(_, let uuid, let range): var uuidString = "" if uuid != nil { uuidString = uuid!.uuidString } return [ElementType: ElementTypeImage as AnyObject, RangeLocation: range.location as AnyObject, RangeLength: range.length as AnyObject, Contents: uuidString as AnyObject] } } // UIImages in .Image elements will be nil. public static func fromDictionary(_ dict:[String:AnyObject]) -> ImageTextViewElement? { guard let elementType = dict[ElementType] as? String else { Log.error("Couldn't get element type") return nil } switch elementType { case ElementTypeText: guard let rangeLocation = dict[RangeLocation] as? Int, let rangeLength = dict[RangeLength] as? Int, let contents = dict[Contents] as? String else { return nil } return .Text(contents, NSMakeRange(rangeLocation, rangeLength)) case ElementTypeImage: guard let rangeLocation = dict[RangeLocation] as? Int, let rangeLength = dict[RangeLength] as? Int, let uuidString = dict[Contents] as? String else { return nil } return .image(nil, UUID(uuidString: uuidString), NSMakeRange(rangeLocation, rangeLength)) default: return nil } } } open var contents:[ImageTextViewElement]? { get { var result = [ImageTextViewElement]() // See https://stackoverflow.com/questions/37370556/ranges-of-strings-from-nsattributedstring self.attributedText.enumerateAttributes(in: NSMakeRange(0, self.attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (dict, range, stop) in Log.msg("dict: \(dict); range: \(range)") // 9/10/17; I'm having an odd issue here with NSAttributedStringKey.attachment versus NSAttachmentAttributeName. I can't seem to use #available(iOS 11, *) to select between them. // See https://stackoverflow.com/questions/46145780/nsattributedstringkey-attachment-versus-nsattachmentattributename/46148528#46148528 let dictValue = dict[NSAttributedString.Key.attachment] if dictValue == nil { let string = (self.attributedText.string as NSString).substring(with: range) Log.msg("string in range: \(range): \(string)") result.append(.Text(string, range)) } else { let imageAttachment = dictValue as! ImageTextAttachment Log.msg("image at range: \(range)") result.append(.image(imageAttachment.image!, imageAttachment.imageId, range)) } } Log.msg("overall string: \(self.attributedText.string)") // TODO: Need to sort each of the elements in the result array by range.location. Not sure if the enumerateAttributesInRange does this for us. if result.count > 0 { return result } else { return nil } } // end get // Any .Image elements must have non-nil images. set { let mutableAttrString = NSMutableAttributedString() let currFont = self.font if newValue != nil { for elem in newValue! { switch elem { case .Text(let string, let range): let attrString = NSAttributedString(string: string) mutableAttrString.insert(attrString, at: range.location) case .image(let image, let uuid, let range): let attrImageString = self.makeImageAttachment(image!, imageId: uuid) mutableAttrString.insert(attrImageString, at: range.location) } } } self.attributedText = mutableAttrString // Without this, we reset back to a default font size after the insertAttributedString above. self.font = currFont } } } // MARK: UITextViewDelegate extension SMImageTextView { // Modified from http://stackoverflow.com/questions/29571682/how-to-detect-deletion-of-image-in-uitextview public func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool { // empty text means backspace if text.isEmpty { // 9/10/17; I'm having an odd issue here with NSAttributedStringKey.attachment versus NSAttachmentAttributeName. I can't seem to use #available(iOS 11, *) to select between them. // See // See https://stackoverflow.com/questions/46145780/nsattributedstringkey-attachment-versus-nsattachmentattributename/46148528#46148528 let key = NSAttributedString.Key.attachment textView.attributedText.enumerateAttribute(key, in: NSMakeRange(0, textView.attributedText.length), options: NSAttributedString.EnumerationOptions(rawValue: 0)) { (object, imageRange, stop) in if let textAttachment = object as? ImageTextAttachment { if NSLocationInRange(imageRange.location, range) { Log.msg("Deletion of image: \(String(describing: object)); range: \(range)") self.imageDelegate?.smImageTextView?(self, imageWasDeleted: textAttachment.imageId) } } } } return true } } extension SMImageTextView : HPTextViewTapGestureRecognizerDelegate { public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer!, handleTapOn textAttachment: NSTextAttachment!, in characterRange: NSRange) { let attach = textAttachment as! ImageTextAttachment self.imageDelegate?.smImageTextView?(self, imageWasTapped: attach.imageId) } }
gpl-3.0
ceab71dc982b2a2a0549689a668a0079
42.722054
528
0.611733
5.371938
false
false
false
false
epv44/TwitchAPIWrapper
Sources/TwitchAPIWrapper/Requests/GetModeratorEventsRequest.swift
1
792
// // GetModeratorEventsRequest.swift // TwitchAPIWrapper // // Created by Eric Vennaro on 5/16/21. // import Foundation ///Get Moderators request see https://dev.twitch.tv/docs/api/reference/#get-moderator-events public struct GetModeratorEventsRequest: JSONConstructableRequest { public let url: URL? public init( broadcasterID: String, userIDs: [String]? = nil, after: String? = nil, first: String? = nil ) { var queryItems = userIDs?.constructQueryItems(withKey: "user_id") ?? [URLQueryItem]() queryItems.append(contentsOf: ["broadcaster_id": broadcasterID, "after": after, "first": first].buildQueryItems()) self.url = TwitchEndpoints.getModeratorEvents.construct()?.appending(queryItems: queryItems) } }
mit
257655b167d7a13cd5c2821b68da7a4f
32
122
0.681818
3.979899
false
false
false
false
CD1212/Doughnut
Pods/FeedKit/Sources/FeedKit/Models/Namespaces/Media/MediaCategory.swift
2
3116
// // MediaCategory.swift // // Copyright (c) 2017 Nuno Manuel Dias // // 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 /// Allows a taxonomy to be set that gives an indication of the type of media /// content, and its particular contents. It has two optional attributes. public class MediaCategory { /// The element's attributes. public class Attributes { /// The URI that identifies the categorization scheme. It is an optional /// attribute. If this attribute is not included, the default scheme /// is "http://search.yahoo.com/mrss/category_schema". public var scheme: String? /// The human readable label that can be displayed in end user /// applications. It is an optional attribute. public var label: String? } /// The element's attributes. public var attributes: Attributes? /// The element's value. public var value: String? } // MARK: - Initializers extension MediaCategory { convenience init(attributes attributeDict: [String : String]) { self.init() self.attributes = MediaCategory.Attributes(attributes: attributeDict) } } extension MediaCategory.Attributes { convenience init?(attributes attributeDict: [String : String]) { if attributeDict.isEmpty { return nil } self.init() self.scheme = attributeDict["scheme"] self.label = attributeDict["label"] } } // MARK: - Equatable extension MediaCategory: Equatable { public static func ==(lhs: MediaCategory, rhs: MediaCategory) -> Bool { return lhs.value == rhs.value && lhs.attributes == rhs.attributes } } extension MediaCategory.Attributes: Equatable { public static func ==(lhs: MediaCategory.Attributes, rhs: MediaCategory.Attributes) -> Bool { return lhs.scheme == rhs.scheme && lhs.label == rhs.label } }
gpl-3.0
2cc3cb2626c7b7c6951e4f6160bdd9d0
29.54902
97
0.660462
4.692771
false
false
false
false
thanhtrdang/FluentYogaKit
FluentYogaKit/ViewController2.swift
1
1206
// // ViewController2.swift // FluentYogaKit // // Created by Thanh Dang on 6/2/17. // Copyright © 2017 Thanh Dang. All rights reserved. // import Hero import UIKit class ViewController2: UIViewController { fileprivate var blackView: UIView! fileprivate var whiteView: UIView! override func viewDidLoad() { super.viewDidLoad() blackView = UIView() blackView.backgroundColor = .black blackView.hero.id = "batMan" whiteView = UIView() whiteView.backgroundColor = .white // whiteView.heroID = "white" // whiteView.heroModifiers = [.translate(y:50)] view.backgroundColor = .red view.hero.id = "ironMan" hero.isEnabled = true view.subview( blackView, whiteView ) view.yoga .vTop(hAlign: .center, blackView.yoga .size(width: 200, height: 80) .marginTop(50), 30, whiteView.yoga .width(200) .flexGrow(1) ) .layout() view.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(handleTap))) } @objc fileprivate func handleTap() { dismiss(animated: true, completion: nil) } }
apache-2.0
a4603be48efba503b868dd47ae514241
20.517857
97
0.616598
4.070946
false
false
false
false
warren-gavin/OBehave
OBehave/Classes/.FutureWork/OBAnimateBlurOverlayBehavior.swift
1
1618
// // OBAnimateBlurOverlayBehavior.swift // OBehave // // Created by Warren Gavin on 07/07/2017. // Copyright © 2017 Apokrupto. All rights reserved. // import UIKit @available(iOS 10.0, *) public class OBAnimateBlurOverlayBehavior: OBBehavior { @IBOutlet public var underlyingView: UIView! { didSet { underlyingView.addSubview(blurView) blurView.translatesAutoresizingMaskIntoConstraints = false blurView.topAnchor.constraint(equalTo: underlyingView.topAnchor).isActive = true blurView.bottomAnchor.constraint(equalTo: underlyingView.bottomAnchor).isActive = true blurView.trailingAnchor.constraint(equalTo: underlyingView.trailingAnchor).isActive = true blurView.leadingAnchor.constraint(equalTo: underlyingView.leadingAnchor).isActive = true } } private lazy var blurView = UIVisualEffectView(effect: UIBlurEffect(style: .light)) private lazy var animator: UIViewPropertyAnimator = { let propertyAnimator = UIViewPropertyAnimator(duration: 1, curve: .linear) { [unowned self] in self.blurView.effect = nil } propertyAnimator.fractionComplete = 1.0 return propertyAnimator }() var blurProgress: CGFloat = 0.0 { didSet { animator.fractionComplete = 1.0 - min(max(blurProgress, 0.0), 1.0) } } } // MARK: OBBehaviorSideEffectDelegate @available(iOS 10.0, *) public extension OBAnimateBlurOverlayBehavior { func setSideEffectProgress(_ progress: CGFloat) { blurProgress = progress } }
mit
3e137536464bdda32bd032cdceda225c
32.6875
102
0.682746
4.659942
false
false
false
false
Coderian/SwiftedKML
SwiftedKML/Elements/PhotoOverlay.swift
1
2942
// // PhotoOverlay.swift // SwiftedKML // // Created by 佐々木 均 on 2016/02/02. // Copyright © 2016年 S-Parts. All rights reserved. // import Foundation /// KML PhotoOverlay /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// /// <element name="PhotoOverlay" type="kml:PhotoOverlayType" substitutionGroup="kml:AbstractOverlayGroup"/> public class PhotoOverlay :SPXMLElement, AbstractOverlayGroup, HasXMLElementValue{ public static var elementName: String = "PhotoOverlay" public override var parent:SPXMLElement! { didSet { // 複数回呼ばれたて同じものがある場合は追加しない if self.parent.childs.contains(self) == false { self.parent.childs.insert(self) switch parent { case let v as Delete: v.value.abstractFeatureGroup.append(self) case let v as Kml: v.value.abstractFeatureGroup = self case let v as Folder: v.value.abstractFeatureGroup.append(self) case let v as Document: v.value.abstractFeatureGroup.append(self) default: break } } } } public var value : PhotoOverlayType public required init(attributes:[String:String]){ self.value = PhotoOverlayType(attributes: attributes) super.init(attributes: attributes) } public var abstractObject : AbstractObjectType { return self.value } public var abstractFeature : AbstractFeatureType { return self.value } public var abstractOverlay : AbstractOverlayType { return self.value } } /// KML PhotoOverlayType /// /// [KML 2.2 shcema](http://schemas.opengis.net/kml/2.2.0/ogckml22.xsd) /// // <complexType name="PhotoOverlayType" final="#all"> // <complexContent> // <extension base="kml:AbstractOverlayType"> // <sequence> // <element ref="kml:rotation" minOccurs="0"/> // <element ref="kml:ViewVolume" minOccurs="0"/> // <element ref="kml:ImagePyramid" minOccurs="0"/> // <element ref="kml:Point" minOccurs="0"/> // <element ref="kml:shape" minOccurs="0"/> // <element ref="kml:PhotoOverlaySimpleExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> // <element ref="kml:PhotoOverlayObjectExtensionGroup" minOccurs="0" maxOccurs="unbounded"/> // </sequence> // </extension> // </complexContent> // </complexType> // <element name="PhotoOverlaySimpleExtensionGroup" abstract="true" type="anySimpleType"/> // <element name="PhotoOverlayObjectExtensionGroup" abstract="true" substitutionGroup="kml:AbstractObjectGroup"/> public class PhotoOverlayType: AbstractOverlayType { public var rotation:Rotation! public var viewVolume:ViewVolume! public var imagePyramid:ImagePyramid! public var point:Point! public var shape: Shape! public var photoOverlaySimpleExtensionGroup:[AnyObject] = [] public var photoOverlayObjectExtensionGroup:[AbstractObjectGroup] = [] }
mit
e23d4bf91b998f516fbb4f0c471a5035
39.633803
113
0.689775
3.97931
false
false
false
false
IvanRublev/VRMaskColoredButton
Pod/Classes/VRMaskColoredButton.swift
1
6454
// // VRMaskColoredButton.swift // VRMaskColoredButton // // Created by Ivan Rublev on 1/25/16. // // import UIKit /// Button class with images painted dynamicly. Is configurable via property inspector of Interface Builder. /// /// Images for normal, highlighted and selected states are painted by applying color to mask image. The image property value for the appropriate state is treated as grayscale mask and normalColor, highlightedColor or selectedColor property value is used respectively to paint the image for the state. The background images are created the same way. /// /// Properties named selectedHighlighted... could be used for fast setting of images and colors for selected with highlighted state. /// @IBDesignable public class VRMaskColoredButton: VRMaskColoredButtonBase { var fetchImagesForStates: [UIControlState] = [.Normal, .Highlighted, .Selected] /// Color applied to the button's image for normal control state. If not set then the tintColor property value is used. @IBInspectable dynamic public var normalColor: UIColor? { willSet { setImageColor(newValue, forState: .Normal) } } /// Color applied to the button's background image for normal control state. By default is black color. @IBInspectable dynamic public var normalBackgroundColor: UIColor? { willSet { setBackgroundImageColor(newValue, forState: .Normal) } } /// Color applied to the button's image for highlighted control state. If not set then normalColor is used. @IBInspectable dynamic public var highlightedColor: UIColor? { willSet { setImageColor(newValue, forState: .Highlighted) } } /// Color applied to the button's background image for highlighted control state. By default normalBackgroundColor is used. @IBInspectable dynamic public var highlightedBackgroundColor: UIColor? { willSet { setBackgroundImageColor(newValue, forState: .Highlighted) } } /// Color applied to the button's image for selected control state. If not set then normalColor is used. @IBInspectable dynamic public var selectedColor: UIColor? { willSet { setImageColor(newValue, forState: .Selected) } } /// Color applied to the button's background image for selected control state. By default normalBackgroundColor is used. @IBInspectable dynamic public var selectedBackroundColor: UIColor? { willSet { setBackgroundImageColor(newValue, forState: .Selected) } } /// Color applied to the button's image for selected with highlighted control state. If not set then normalColor is used. @IBInspectable dynamic public var selectedHighlightedColor: UIColor? { willSet { setImageColor(newValue, forState: UIControlState.Selected.union(.Highlighted)) } } /// Color applied to the button's background image for selected with highlighted control state. By default normalBackgroundColor is used. @IBInspectable dynamic public var selectedHighlightedBackroundColor: UIColor? { willSet { setBackgroundImageColor(newValue, forState: UIControlState.Selected.union(.Highlighted)) } } /// Image to be set for selected with highlighted state @IBInspectable dynamic public var selectedHighlightedImage: UIImage? { willSet { setImage(newValue, forState: UIControlState.Selected.union(.Highlighted)) } } /// Background image to be set for selected with highlighted state @IBInspectable dynamic public var selectedHighlightedBackgroundImage: UIImage? { willSet { setBackgroundImage(newValue, forState: UIControlState.Selected.union(.Highlighted)) } } // MARK: - // MARK: Default colors override public func imageColorForState(state: UIControlState) -> UIColor? { if let color = super.imageColorForState(state) { return color } else { // return defaults if state == .Normal { return tintColor } else { return imageColorForState(.Normal) } } } override public func backgroundImageColorForState(state: UIControlState) -> UIColor? { if let backgroundColor = super.backgroundImageColorForState(state) { return backgroundColor } else { // return defaults if state == .Normal { return UIColor.blackColor() } else { return backgroundImageColorForState(.Normal) } } } override public var tintColor: UIColor! { didSet { if hasImageColorForState(.Normal) == false { // then tintColor is used as default value to paint images updateImages() updateBackgroundImages() } } } // MARK: - // MARK: Initialization override public init(frame: CGRect) { super.init(frame: frame) } required public init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) // Collect images that were set via IB var imagesForState = [UIControlState : UIImage]() var backgroundImagesForState = [UIControlState : UIImage]() for state in fetchImagesForStates { if let superImage = super.imageForState(state) { if superImage != imagesForState[.Normal] { imagesForState[state] = superImage } } if let superBackgroundImage = super.backgroundImageForState(state) { if superBackgroundImage != backgroundImagesForState[.Normal] { backgroundImagesForState[state] = superBackgroundImage } } } // Fill mask images maskImageForState = imagesForState backgroundMaskImageForState = backgroundImagesForState } // MARK: - // MARK: Intercept images to make them mask images override public func setImage(image: UIImage?, forState state: UIControlState) { maskImageForState[state] = image } override public func imageForState(state: UIControlState) -> UIImage? { return maskImageForState[state] } override public func setBackgroundImage(image: UIImage?, forState state: UIControlState) { backgroundMaskImageForState[state] = image } override public func backgroundImageForState(state: UIControlState) -> UIImage? { return backgroundMaskImageForState[state] } }
mit
2f14d53e26dd5576104dd593073576fc
43.826389
349
0.681593
5.373855
false
false
false
false
nathawes/swift
test/Constraints/tuple_arguments.swift
7
64980
// RUN: %target-typecheck-verify-swift -swift-version 5 // See test/Compatibility/tuple_arguments_4.swift for some // Swift 4-specific tests. func concrete(_ x: Int) {} func concreteLabeled(x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} do { concrete(3) concrete((3)) concreteLabeled(x: 3) concreteLabeled(x: (3)) concreteLabeled((x: 3)) // expected-error {{missing argument label 'x:' in call}} // expected-error@-1 {{cannot convert value of type '(x: Int)' to expected argument type 'Int'}} concreteTwo(3, 4) concreteTwo((3, 4)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTuple(3, 4) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) concrete(a) concrete((a)) concrete(c) concreteTwo(a, b) concreteTwo((a, b)) // expected-error {{global function 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} concreteTwo(d) // expected-error {{global function 'concreteTwo' expects 2 separate arguments}} concreteTuple(a, b) // expected-error {{global function 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} concreteTuple((a, b)) concreteTuple(d) } func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} do { generic(3) generic(3, 4) // expected-error {{extra argument in call}} generic((3)) generic((3, 4)) genericLabeled(x: 3) genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} genericLabeled(x: (3)) genericLabeled(x: (3, 4)) genericTwo(3, 4) genericTwo((3, 4)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTuple(3, 4) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) generic(a) generic(a, b) // expected-error {{extra argument in call}} generic((a)) generic(c) generic((a, b)) generic(d) genericTwo(a, b) genericTwo((a, b)) // expected-error {{global function 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{14-15=}} {{19-20=}} genericTwo(d) // expected-error {{global function 'genericTwo' expects 2 separate arguments}} genericTuple(a, b) // expected-error {{global function 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{16-16=(}} {{20-20=)}} genericTuple((a, b)) genericTuple(d) } var function: (Int) -> () var functionTwo: (Int, Int) -> () // expected-note 5 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () do { function(3) function((3)) functionTwo(3, 4) functionTwo((3, 4)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTuple(3, 4) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((3, 4)) } do { let a = 3 let b = 4 let c = (3) let d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } do { var a = 3 var b = 4 var c = (3) var d = (a, b) function(a) function((a)) function(c) functionTwo(a, b) functionTwo((a, b)) // expected-error {{var 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} functionTwo(d) // expected-error {{var 'functionTwo' expects 2 separate arguments}} functionTuple(a, b) // expected-error {{var 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} functionTuple((a, b)) functionTuple(d) } struct Concrete {} extension Concrete { func concrete(_ x: Int) {} func concreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'concreteTwo' declared here}} func concreteTuple(_ x: (Int, Int)) {} } do { let s = Concrete() s.concrete(3) s.concrete((3)) s.concreteTwo(3, 4) s.concreteTwo((3, 4)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTuple(3, 4) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.concrete(a) s.concrete((a)) s.concrete(c) s.concreteTwo(a, b) s.concreteTwo((a, b)) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.concreteTwo(d) // expected-error {{instance method 'concreteTwo' expects 2 separate arguments}} s.concreteTuple(a, b) // expected-error {{instance method 'concreteTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.concreteTuple((a, b)) s.concreteTuple(d) } extension Concrete { func generic<T>(_ x: T) {} func genericLabeled<T>(x: T) {} func genericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'genericTwo' declared here}} func genericTuple<T, U>(_ x: (T, U)) {} } do { let s = Concrete() s.generic(3) s.generic(3, 4) // expected-error {{extra argument in call}} s.generic((3)) s.generic((3, 4)) s.genericLabeled(x: 3) s.genericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.genericLabeled(x: (3)) s.genericLabeled(x: (3, 4)) s.genericTwo(3, 4) s.genericTwo((3, 4)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(3, 4) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.generic(a) s.generic(a, b) // expected-error {{extra argument in call}} s.generic((a)) s.generic((a, b)) s.generic(d) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTwo(d) // expected-error {{instance method 'genericTwo' expects 2 separate arguments}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) s.genericTuple(d) } extension Concrete { mutating func mutatingConcrete(_ x: Int) {} mutating func mutatingConcreteTwo(_ x: Int, _ y: Int) {} // expected-note 5 {{'mutatingConcreteTwo' declared here}} mutating func mutatingConcreteTuple(_ x: (Int, Int)) {} } do { var s = Concrete() s.mutatingConcrete(3) s.mutatingConcrete((3)) s.mutatingConcreteTwo(3, 4) s.mutatingConcreteTwo((3, 4)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTuple(3, 4) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingConcrete(a) s.mutatingConcrete((a)) s.mutatingConcrete(c) s.mutatingConcreteTwo(a, b) s.mutatingConcreteTwo((a, b)) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{25-26=}} {{30-31=}} s.mutatingConcreteTwo(d) // expected-error {{instance method 'mutatingConcreteTwo' expects 2 separate arguments}} s.mutatingConcreteTuple(a, b) // expected-error {{instance method 'mutatingConcreteTuple' expects a single parameter of type '(Int, Int)'}} {{27-27=(}} {{31-31=)}} s.mutatingConcreteTuple((a, b)) s.mutatingConcreteTuple(d) } extension Concrete { mutating func mutatingGeneric<T>(_ x: T) {} mutating func mutatingGenericLabeled<T>(x: T) {} mutating func mutatingGenericTwo<T, U>(_ x: T, _ y: U) {} // expected-note 5 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple<T, U>(_ x: (T, U)) {} } do { var s = Concrete() s.mutatingGeneric(3) s.mutatingGeneric(3, 4) // expected-error {{extra argument in call}} s.mutatingGeneric((3)) s.mutatingGeneric((3, 4)) s.mutatingGenericLabeled(x: 3) s.mutatingGenericLabeled(x: 3, 4) // expected-error {{extra argument in call}} s.mutatingGenericLabeled(x: (3)) s.mutatingGenericLabeled(x: (3, 4)) s.mutatingGenericTwo(3, 4) s.mutatingGenericTwo((3, 4)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTuple(3, 4) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((3, 4)) } do { var s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric(a, b) // expected-error {{extra argument in call}} s.mutatingGeneric((a)) s.mutatingGeneric((a, b)) s.mutatingGeneric(d) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTwo(d) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(T, U)' [with T = Int, U = Int]}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) s.mutatingGenericTuple(d) } extension Concrete { var function: (Int) -> () { return concrete } var functionTwo: (Int, Int) -> () { return concreteTwo } // expected-note 5 {{'functionTwo' declared here}} var functionTuple: ((Int, Int)) -> () { return concreteTuple } } do { let s = Concrete() s.function(3) s.function((3)) s.functionTwo(3, 4) s.functionTwo((3, 4)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTuple(3, 4) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((3, 4)) } do { let s = Concrete() let a = 3 let b = 4 let c = (3) let d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}} s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } do { var s = Concrete() var a = 3 var b = 4 var c = (3) var d = (a, b) s.function(a) s.function((a)) s.function(c) s.functionTwo(a, b) s.functionTwo((a, b)) // expected-error {{property 'functionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{17-18=}} {{22-23=}} s.functionTwo(d) // expected-error {{property 'functionTwo' expects 2 separate arguments}} s.functionTuple(a, b) // expected-error {{property 'functionTuple' expects a single parameter of type '(Int, Int)'}} {{19-19=(}} {{23-23=)}} s.functionTuple((a, b)) s.functionTuple(d) } struct InitTwo { init(_ x: Int, _ y: Int) {} // expected-note 5 {{'init(_:_:)' declared here}} } struct InitTuple { init(_ x: (Int, Int)) {} } struct InitLabeledTuple { init(x: (Int, Int)) {} } do { _ = InitTwo(3, 4) _ = InitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((3, 4)) _ = InitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = InitLabeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = InitTwo(a, b) _ = InitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{15-16=}} {{20-21=}} _ = InitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = InitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{17-17=(}} {{21-21=)}} _ = InitTuple((a, b)) _ = InitTuple(c) } struct SubscriptTwo { subscript(_ x: Int, _ y: Int) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct SubscriptTuple { subscript(_ x: (Int, Int)) -> Int { get { return 0 } set { } } } struct SubscriptLabeledTuple { subscript(x x: (Int, Int)) -> Int { get { return 0 } set { } } } do { let s1 = SubscriptTwo() _ = s1[3, 4] _ = s1[(3, 4)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} let s2 = SubscriptTuple() _ = s2[3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(3, 4)] } do { let a = 3 let b = 4 let d = (a, b) let s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s1[d] // expected-error {{subscript expects 2 separate arguments}} let s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] let s3 = SubscriptLabeledTuple() _ = s3[x: 3, 4] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} _ = s3[x: (3, 4)] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = SubscriptTwo() _ = s1[a, b] _ = s1[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s1[d] // expected-error {{subscript expects 2 separate arguments}} var s2 = SubscriptTuple() _ = s2[a, b] // expected-error {{subscript expects a single parameter of type '(Int, Int)'}} {{10-10=(}} {{14-14=)}} _ = s2[(a, b)] _ = s2[d] } enum Enum { case two(Int, Int) // expected-note 6 {{'two' declared here}} case tuple((Int, Int)) case labeledTuple(x: (Int, Int)) } do { _ = Enum.two(3, 4) _ = Enum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(3 > 4 ? 3 : 4) // expected-error {{missing argument for parameter #2 in call}} _ = Enum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((3, 4)) _ = Enum.labeledTuple(x: 3, 4) // expected-error {{enum case 'labeledTuple' expects a single parameter of type '(Int, Int)'}} _ = Enum.labeledTuple(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = Enum.two(a, b) _ = Enum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} _ = Enum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = Enum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{18-18=(}} {{22-22=)}} _ = Enum.tuple((a, b)) _ = Enum.tuple(c) } struct Generic<T> {} extension Generic { func generic(_ x: T) {} func genericLabeled(x: T) {} func genericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'genericTwo' declared here}} func genericTuple(_ x: (T, T)) {} } do { let s = Generic<Double>() s.generic(3.0) s.generic((3.0)) s.genericLabeled(x: 3.0) s.genericLabeled(x: (3.0)) s.genericTwo(3.0, 4.0) s.genericTwo((3.0, 4.0)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{25-26=}} s.genericTuple(3.0, 4.0) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{26-26=)}} s.genericTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.generic(3.0, 4.0) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{24-24=)}} sTwo.generic((3.0, 4.0)) sTwo.genericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'genericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.genericLabeled(x: (3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.generic(a) s.generic((a)) s.generic(c) s.genericTwo(a, b) s.genericTwo((a, b)) // expected-error {{instance method 'genericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{16-17=}} {{21-22=}} s.genericTuple(a, b) // expected-error {{instance method 'genericTuple' expects a single parameter of type '(Double, Double)'}} {{18-18=(}} {{22-22=)}} s.genericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.generic(a, b) // expected-error {{instance method 'generic' expects a single parameter of type '(Double, Double)'}} {{16-16=(}} {{20-20=)}} sTwo.generic((a, b)) sTwo.generic(d) } extension Generic { mutating func mutatingGeneric(_ x: T) {} mutating func mutatingGenericLabeled(x: T) {} mutating func mutatingGenericTwo(_ x: T, _ y: T) {} // expected-note 3 {{'mutatingGenericTwo' declared here}} mutating func mutatingGenericTuple(_ x: (T, T)) {} } do { var s = Generic<Double>() s.mutatingGeneric(3.0) s.mutatingGeneric((3.0)) s.mutatingGenericLabeled(x: 3.0) s.mutatingGenericLabeled(x: (3.0)) s.mutatingGenericTwo(3.0, 4.0) s.mutatingGenericTwo((3.0, 4.0)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{33-34=}} s.mutatingGenericTuple(3.0, 4.0) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.mutatingGenericTuple((3.0, 4.0)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(3.0, 4.0) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.mutatingGeneric((3.0, 4.0)) sTwo.mutatingGenericLabeled(x: 3.0, 4.0) // expected-error {{instance method 'mutatingGenericLabeled' expects a single parameter of type '(Double, Double)'}} sTwo.mutatingGenericLabeled(x: (3.0, 4.0)) } do { var s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {24-25=}} {{29-30=}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.mutatingGeneric(a) s.mutatingGeneric((a)) s.mutatingGeneric(c) s.mutatingGenericTwo(a, b) s.mutatingGenericTwo((a, b)) // expected-error {{instance method 'mutatingGenericTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.mutatingGenericTuple(a, b) // expected-error {{instance method 'mutatingGenericTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.mutatingGenericTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.mutatingGeneric(a, b) // expected-error {{instance method 'mutatingGeneric' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.mutatingGeneric((a, b)) sTwo.mutatingGeneric(d) } extension Generic { var genericFunction: (T) -> () { return generic } var genericFunctionTwo: (T, T) -> () { return genericTwo } // expected-note 3 {{'genericFunctionTwo' declared here}} var genericFunctionTuple: ((T, T)) -> () { return genericTuple } } do { let s = Generic<Double>() s.genericFunction(3.0) s.genericFunction((3.0)) s.genericFunctionTwo(3.0, 4.0) s.genericFunctionTwo((3.0, 4.0)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{33-34=}} s.genericFunctionTuple(3.0, 4.0) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{34-34=)}} s.genericFunctionTuple((3.0, 4.0)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(3.0, 4.0) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{32-32=)}} sTwo.genericFunction((3.0, 4.0)) } do { let s = Generic<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) let sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } do { var s = Generic<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.genericFunction(a) s.genericFunction((a)) s.genericFunction(c) s.genericFunctionTwo(a, b) s.genericFunctionTwo((a, b)) // expected-error {{property 'genericFunctionTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{24-25=}} {{29-30=}} s.genericFunctionTuple(a, b) // expected-error {{property 'genericFunctionTuple' expects a single parameter of type '(Double, Double)'}} {{26-26=(}} {{30-30=)}} s.genericFunctionTuple((a, b)) var sTwo = Generic<(Double, Double)>() sTwo.genericFunction(a, b) // expected-error {{property 'genericFunction' expects a single parameter of type '(Double, Double)'}} {{24-24=(}} {{28-28=)}} sTwo.genericFunction((a, b)) sTwo.genericFunction(d) } struct GenericInit<T> { init(_ x: T) {} } struct GenericInitLabeled<T> { init(x: T) {} } struct GenericInitTwo<T> { init(_ x: T, _ y: T) {} // expected-note 10 {{'init(_:_:)' declared here}} } struct GenericInitTuple<T> { init(_ x: (T, T)) {} } struct GenericInitLabeledTuple<T> { init(x: (T, T)) {} } do { _ = GenericInit(3, 4) // expected-error {{extra argument in call}} _ = GenericInit((3, 4)) _ = GenericInitLabeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericInitLabeled(x: (3, 4)) _ = GenericInitTwo(3, 4) _ = GenericInitTwo((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTuple(3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((3, 4)) _ = GenericInitLabeledTuple(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} _ = GenericInitLabeledTuple(x: (3, 4)) } do { _ = GenericInit<(Int, Int)>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((3, 4)) _ = GenericInitLabeled<(Int, Int)>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInitLabeled<(Int, Int)>(x: (3, 4)) _ = GenericInitTwo<Int>(3, 4) _ = GenericInitTwo<Int>((3, 4)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTuple<Int>(3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((3, 4)) _ = GenericInitLabeledTuple<Int>(x: 3, 4) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInitLabeledTuple<Int>(x: (3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit(a, b) // expected-error {{extra argument in call}} _ = GenericInit((a, b)) _ = GenericInit(c) _ = GenericInitTwo(a, b) _ = GenericInitTwo((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{22-23=}} {{27-28=}} _ = GenericInitTwo(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple(a, b) // expected-error {{initializer expects a single parameter of type '(T, T)' [with T = Int]}} {{24-24=(}} {{28-28=)}} _ = GenericInitTuple((a, b)) _ = GenericInitTuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericInit<(Int, Int)>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} _ = GenericInit<(Int, Int)>((a, b)) _ = GenericInit<(Int, Int)>(c) _ = GenericInitTwo<Int>(a, b) _ = GenericInitTwo<Int>((a, b)) // expected-error {{initializer expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{27-28=}} {{32-33=}} _ = GenericInitTwo<Int>(c) // expected-error {{initializer expects 2 separate arguments}} _ = GenericInitTuple<Int>(a, b) // expected-error {{initializer expects a single parameter of type '(Int, Int)'}} {{29-29=(}} {{33-33=)}} _ = GenericInitTuple<Int>((a, b)) _ = GenericInitTuple<Int>(c) } struct GenericSubscript<T> { subscript(_ x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptLabeled<T> { subscript(x x: T) -> Int { get { return 0 } set { } } } struct GenericSubscriptTwo<T> { subscript(_ x: T, _ y: T) -> Int { get { return 0 } set { } } // expected-note 5 {{'subscript(_:_:)' declared here}} } struct GenericSubscriptLabeledTuple<T> { subscript(x x: (T, T)) -> Int { get { return 0 } set { } } } struct GenericSubscriptTuple<T> { subscript(_ x: (T, T)) -> Int { get { return 0 } set { } } } do { let s1 = GenericSubscript<(Double, Double)>() _ = s1[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}} _ = s1[(3.0, 4.0)] let s1a = GenericSubscriptLabeled<(Double, Double)>() _ = s1a [x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{14-14=(}} {{23-23=)}} _ = s1a [x: (3.0, 4.0)] let s2 = GenericSubscriptTwo<Double>() _ = s2[3.0, 4.0] _ = s2[(3.0, 4.0)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{19-20=}} let s3 = GenericSubscriptTuple<Double>() _ = s3[3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{18-18=)}} _ = s3[(3.0, 4.0)] let s3a = GenericSubscriptLabeledTuple<Double>() _ = s3a[x: 3.0, 4.0] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{13-13=(}} {{22-22=)}} _ = s3a[x: (3.0, 4.0)] } do { let a = 3.0 let b = 4.0 let d = (a, b) let s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s1[(a, b)] _ = s1[d] let s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s2[d] // expected-error {{subscript expects 2 separate arguments}} let s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } do { // TODO: Restore regressed diagnostics rdar://problem/31724211 var a = 3.0 // e/xpected-warning {{variable 'a' was never mutated; consider changing to 'let' constant}} var b = 4.0 // e/xpected-warning {{variable 'b' was never mutated; consider changing to 'let' constant}} var d = (a, b) // e/xpected-warning {{variable 'd' was never mutated; consider changing to 'let' constant}} var s1 = GenericSubscript<(Double, Double)>() _ = s1[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s1[(a, b)] _ = s1[d] var s2 = GenericSubscriptTwo<Double>() _ = s2[a, b] _ = s2[(a, b)] // expected-error {{subscript expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{10-11=}} {{15-16=}} _ = s2[d] // expected-error {{subscript expects 2 separate arguments}} var s3 = GenericSubscriptTuple<Double>() _ = s3[a, b] // expected-error {{subscript expects a single parameter of type '(Double, Double)'}} {{10-10=(}} {{14-14=)}} _ = s3[(a, b)] _ = s3[d] } enum GenericEnum<T> { case one(T) case labeled(x: T) case two(T, T) // expected-note 10 {{'two' declared here}} case tuple((T, T)) } do { _ = GenericEnum.one(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.one((3, 4)) _ = GenericEnum.labeled(x: 3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled(x: (3, 4)) _ = GenericEnum.labeled(3, 4) // expected-error {{extra argument in call}} _ = GenericEnum.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum.two(3, 4) _ = GenericEnum.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((3, 4)) } do { _ = GenericEnum<(Int, Int)>.one(3, 4) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((3, 4)) _ = GenericEnum<(Int, Int)>.labeled(x: 3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled(x: (3, 4)) _ = GenericEnum<(Int, Int)>.labeled(3, 4) // expected-error {{enum case 'labeled' expects a single parameter of type '(Int, Int)'}} _ = GenericEnum<(Int, Int)>.labeled((3, 4)) // expected-error {{missing argument label 'x:' in call}} _ = GenericEnum<Int>.two(3, 4) _ = GenericEnum<Int>.two((3, 4)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.tuple(3, 4) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((3, 4)) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { let a = 3 let b = 4 let c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum.one(a, b) // expected-error {{extra argument in call}} _ = GenericEnum.one((a, b)) _ = GenericEnum.one(c) _ = GenericEnum.two(a, b) _ = GenericEnum.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{23-24=}} {{28-29=}} _ = GenericEnum.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(T, T)' [with T = Int]}} {{25-25=(}} {{29-29=)}} _ = GenericEnum.tuple((a, b)) _ = GenericEnum.tuple(c) } do { var a = 3 var b = 4 var c = (a, b) _ = GenericEnum<(Int, Int)>.one(a, b) // expected-error {{enum case 'one' expects a single parameter of type '(Int, Int)'}} {{35-35=(}} {{39-39=)}} _ = GenericEnum<(Int, Int)>.one((a, b)) _ = GenericEnum<(Int, Int)>.one(c) _ = GenericEnum<Int>.two(a, b) _ = GenericEnum<Int>.two((a, b)) // expected-error {{enum case 'two' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{28-29=}} {{33-34=}} _ = GenericEnum<Int>.two(c) // expected-error {{enum case 'two' expects 2 separate arguments}} _ = GenericEnum<Int>.tuple(a, b) // expected-error {{enum case 'tuple' expects a single parameter of type '(Int, Int)'}} {{30-30=(}} {{34-34=)}} _ = GenericEnum<Int>.tuple((a, b)) _ = GenericEnum<Int>.tuple(c) } protocol Protocol { associatedtype Element } extension Protocol { func requirement(_ x: Element) {} func requirementLabeled(x: Element) {} func requirementTwo(_ x: Element, _ y: Element) {} // expected-note 3 {{'requirementTwo' declared here}} func requirementTuple(_ x: (Element, Element)) {} } struct GenericConforms<T> : Protocol { typealias Element = T } do { let s = GenericConforms<Double>() s.requirement(3.0) s.requirement((3.0)) s.requirementLabeled(x: 3.0) s.requirementLabeled(x: (3.0)) s.requirementTwo(3.0, 4.0) s.requirementTwo((3.0, 4.0)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{29-30=}} s.requirementTuple(3.0, 4.0) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{30-30=)}} s.requirementTuple((3.0, 4.0)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(3.0, 4.0) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{28-28=)}} sTwo.requirement((3.0, 4.0)) sTwo.requirementLabeled(x: 3.0, 4.0) // expected-error {{instance method 'requirementLabeled' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{29-29=(}} {{38-38=)}} sTwo.requirementLabeled(x: (3.0, 4.0)) } do { let s = GenericConforms<Double>() let a = 3.0 let b = 4.0 let c = (3.0) let d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) let sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } do { var s = GenericConforms<Double>() var a = 3.0 var b = 4.0 var c = (3.0) var d = (a, b) s.requirement(a) s.requirement((a)) s.requirement(c) s.requirementTwo(a, b) s.requirementTwo((a, b)) // expected-error {{instance method 'requirementTwo' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{20-21=}} {{25-26=}} s.requirementTuple(a, b) // expected-error {{instance method 'requirementTuple' expects a single parameter of type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element)' (aka '(Double, Double)')}} {{22-22=(}} {{26-26=)}} s.requirementTuple((a, b)) var sTwo = GenericConforms<(Double, Double)>() sTwo.requirement(a, b) // expected-error {{instance method 'requirement' expects a single parameter of type 'GenericConforms<(Double, Double)>.Element' (aka '(Double, Double)')}} {{20-20=(}} {{24-24=)}} sTwo.requirement((a, b)) sTwo.requirement(d) } extension Protocol { func takesClosure(_ fn: (Element) -> ()) {} func takesClosureTwo(_ fn: (Element, Element) -> ()) {} func takesClosureTuple(_ fn: ((Element, Element)) -> ()) {} } do { let s = GenericConforms<Double>() s.takesClosure({ _ = $0 }) s.takesClosure({ x in }) s.takesClosure({ (x: Double) in }) s.takesClosureTwo({ _ = $0 }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ x in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ (x: (Double, Double)) in }) // expected-error {{contextual closure type '(GenericConforms<Double>.Element, GenericConforms<Double>.Element) -> ()' (aka '(Double, Double) -> ()') expects 2 arguments, but 1 was used in closure body}} s.takesClosureTwo({ _ = $0; _ = $1 }) s.takesClosureTwo({ (x, y) in }) s.takesClosureTwo({ (x: Double, y:Double) in }) s.takesClosureTuple({ _ = $0 }) s.takesClosureTuple({ x in }) s.takesClosureTuple({ (x: (Double, Double)) in }) s.takesClosureTuple({ _ = $0; _ = $1 }) s.takesClosureTuple({ (x, y) in }) s.takesClosureTuple({ (x: Double, y:Double) in }) let sTwo = GenericConforms<(Double, Double)>() sTwo.takesClosure({ _ = $0 }) sTwo.takesClosure({ x in }) sTwo.takesClosure({ (x: (Double, Double)) in }) sTwo.takesClosure({ _ = $0; _ = $1 }) sTwo.takesClosure({ (x, y) in }) sTwo.takesClosure({ (x: Double, y: Double) in }) } do { let _: ((Int, Int)) -> () = { _ = $0 } let _: ((Int, Int)) -> () = { _ = ($0.0, $0.1) } let _: ((Int, Int)) -> () = { t in _ = (t.0, t.1) } let _: ((Int, Int)) -> () = { _ = ($0, $1) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} let _: ((Int, Int)) -> () = { t, u in _ = (t, u) } // expected-error {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{41-41=let (t, u) = arg; }} let _: (Int, Int) -> () = { _ = $0 } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0.0, $0.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { t in _ = (t.0, t.1) } // expected-error {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} let _: (Int, Int) -> () = { _ = ($0, $1) } let _: (Int, Int) -> () = { t, u in _ = (t, u) } } // rdar://problem/28952837 - argument labels ignored when calling function // with single 'Any' parameter func takesAny(_: Any) {} enum HasAnyCase { case any(_: Any) } do { let fn: (Any) -> () = { _ in } fn(123) fn(data: 123) // expected-error {{extraneous argument label 'data:' in call}} takesAny(123) takesAny(data: 123) // expected-error {{extraneous argument label 'data:' in call}} _ = HasAnyCase.any(123) _ = HasAnyCase.any(data: 123) // expected-error {{extraneous argument label 'data:' in call}} } // rdar://problem/29739905 - protocol extension methods on Array had // ParenType sugar stripped off the element type func processArrayOfFunctions(f1: [((Bool, Bool)) -> ()], f2: [(Bool, Bool) -> ()], c: Bool) { let p = (c, c) f1.forEach { block in block(p) block((c, c)) block(c, c) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}} {{11-11=(}} {{15-15=)}} } f2.forEach { block in // expected-note@-1 2{{'block' declared here}} block(p) // expected-error {{parameter 'block' expects 2 separate arguments}} block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}} block(c, c) } f2.forEach { (block: ((Bool, Bool)) -> ()) in // expected-error@-1 {{cannot convert value of type '(((Bool, Bool)) -> ()) -> Void' to expected argument type '(@escaping (Bool, Bool) -> ()) throws -> Void'}} block(p) block((c, c)) block(c, c) } f2.forEach { (block: (Bool, Bool) -> ()) in // expected-note@-1 2{{'block' declared here}} block(p) // expected-error {{parameter 'block' expects 2 separate arguments}} block((c, c)) // expected-error {{parameter 'block' expects 2 separate arguments; remove extra parentheses to change tuple into separate arguments}} {{11-12=}} {{16-17=}} block(c, c) } } // expected-error@+1 {{cannot create a single-element tuple with an element label}} func singleElementTupleArgument(completion: ((didAdjust: Bool)) -> Void) { // TODO: Error could be improved. // expected-error@+1 {{cannot convert value of type '(didAdjust: Bool)' to expected argument type 'Bool'}} completion((didAdjust: true)) } // SR-4378 final public class MutableProperty<Value> { public init(_ initialValue: Value) {} } enum DataSourcePage<T> { case notLoaded } let pages1: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: .notLoaded, totalCount: 0 )) let pages2: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage.notLoaded, totalCount: 0 )) let pages3: MutableProperty<(data: DataSourcePage<Int>, totalCount: Int)> = MutableProperty(( data: DataSourcePage<Int>.notLoaded, totalCount: 0 )) // SR-4745 let sr4745 = [1, 2] let _ = sr4745.enumerated().map { (count, element) in "\(count): \(element)" } // SR-4738 let sr4738 = (1, (2, 3)) [sr4738].map { (x, (y, z)) -> Int in x + y + z } // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{20-26=arg1}} {{38-38=let (y, z) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{20-20=_: }} // expected-error@-3 {{cannot find type 'y' in scope}} // expected-error@-4 {{cannot find type 'z' in scope}} // rdar://problem/31892961 let r31892961_1 = [1: 1, 2: 2] r31892961_1.forEach { (k, v) in print(k + v) } let r31892961_2 = [1, 2, 3] let _: [Int] = r31892961_2.enumerated().map { ((index, val)) in // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{48-60=arg0}} {{3-3=\n let (index, val) = arg0\n }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{48-48=_: }} // expected-error@-3 {{cannot find type 'index' in scope}} // expected-error@-4 {{cannot find type 'val' in scope}} val + 1 } let r31892961_3 = (x: 1, y: 42) _ = [r31892961_3].map { (x: Int, y: Int) in x + y } _ = [r31892961_3].map { (x, y: Int) in x + y } let r31892961_4 = (1, 2) _ = [r31892961_4].map { x, y in x + y } let r31892961_5 = (x: 1, (y: 2, (w: 3, z: 4))) [r31892961_5].map { (x: Int, (y: Int, (w: Int, z: Int))) in x + y } // expected-note {{'x' declared here}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-56=arg1}} {{61-61=let (y, (w, z)) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }} // expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}} let r31892961_6 = (x: 1, (y: 2, z: 4)) [r31892961_6].map { (x: Int, (y: Int, z: Int)) in x + y } // expected-note {{'x' declared here}} // expected-error@-1 {{closure tuple parameter does not support destructuring}} {{30-46=arg1}} {{51-51=let (y, z) = arg1; }} // expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{30-30=_: }} // expected-error@-3{{cannot find 'y' in scope; did you mean 'x'?}} // rdar://problem/32214649 -- these regressed in Swift 4 mode // with SE-0110 because of a problem in associated type inference func r32214649_1<X,Y>(_ a: [X], _ f: (X)->Y) -> [Y] { return a.map(f) } func r32214649_2<X>(_ a: [X], _ f: (X) -> Bool) -> [X] { return a.filter(f) } func r32214649_3<X>(_ a: [X]) -> [X] { return a.filter { _ in return true } } // rdar://problem/32301091 - [SE-0110] causes errors when passing a closure with a single underscore to a block accepting multiple parameters func rdar32301091_1(_ :((Int, Int) -> ())!) {} rdar32301091_1 { _ in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }} func rdar32301091_2(_ :(Int, Int) -> ()) {} rdar32301091_2 { _ in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,_ }} rdar32301091_2 { x in } // expected-error@-1 {{contextual closure type '(Int, Int) -> ()' expects 2 arguments, but 1 was used in closure body}} {{19-19=,<#arg#> }} func rdar32875953() { let myDictionary = ["hi":1] myDictionary.forEach { print("\($0) -> \($1)") } myDictionary.forEach { key, value in print("\(key) -> \(value)") } myDictionary.forEach { (key, value) in print("\(key) -> \(value)") } let array1 = [1] let array2 = [2] _ = zip(array1, array2).map(+) } struct SR_5199 {} extension Sequence where Iterator.Element == (key: String, value: String?) { func f() -> [SR_5199] { return self.map { (key, value) in SR_5199() // Ok } } } func rdar33043106(_ records: [(Int)], _ other: [((Int))]) -> [Int] { let x: [Int] = records.map { _ in let i = 1 return i } let y: [Int] = other.map { _ in let i = 1 return i } return x + y } func itsFalse(_: Int) -> Bool? { return false } func rdar33159366(s: AnySequence<Int>) { _ = s.compactMap(itsFalse) let a = Array(s) _ = a.compactMap(itsFalse) } func sr5429<T>(t: T) { _ = AnySequence([t]).first(where: { (t: T) in true }) } extension Concrete { typealias T = (Int, Int) typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } extension Generic { typealias F = (T) -> () func opt1(_ fn: (((Int, Int)) -> ())?) {} func opt2(_ fn: (((Int, Int)) -> ())??) {} func opt3(_ fn: (((Int, Int)) -> ())???) {} func optAliasT(_ fn: ((T) -> ())?) {} func optAliasF(_ fn: F?) {} } func rdar33239714() { Concrete().opt1 { x, y in } Concrete().opt1 { (x, y) in } Concrete().opt2 { x, y in } Concrete().opt2 { (x, y) in } Concrete().opt3 { x, y in } Concrete().opt3 { (x, y) in } Concrete().optAliasT { x, y in } Concrete().optAliasT { (x, y) in } Concrete().optAliasF { x, y in } Concrete().optAliasF { (x, y) in } Generic<(Int, Int)>().opt1 { x, y in } Generic<(Int, Int)>().opt1 { (x, y) in } Generic<(Int, Int)>().opt2 { x, y in } Generic<(Int, Int)>().opt2 { (x, y) in } Generic<(Int, Int)>().opt3 { x, y in } Generic<(Int, Int)>().opt3 { (x, y) in } Generic<(Int, Int)>().optAliasT { x, y in } Generic<(Int, Int)>().optAliasT { (x, y) in } Generic<(Int, Int)>().optAliasF { x, y in } Generic<(Int, Int)>().optAliasF { (x, y) in } } // rdar://problem/35198459 - source-compat-suite failure: Moya (toType->hasUnresolvedType() && "Should have handled this above" do { func foo(_: (() -> Void)?) {} func bar() -> ((()) -> Void)? { return nil } foo(bar()) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} } // https://bugs.swift.org/browse/SR-6509 public extension Optional { func apply<Result>(_ transform: ((Wrapped) -> Result)?) -> Result? { return self.flatMap { value in transform.map { $0(value) } } } func apply<Value, Result>(_ value: Value?) -> Result? where Wrapped == (Value) -> Result { return value.apply(self) } } // https://bugs.swift.org/browse/SR-6837 // FIXME: Can't overlaod local functions so these must be top-level func takePairOverload(_ pair: (Int, Int?)) {} func takePairOverload(_: () -> ()) {} do { func takeFn(fn: (_ i: Int, _ j: Int?) -> ()) {} func takePair(_ pair: (Int, Int?)) {} takeFn(fn: takePair) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}} takeFn(fn: takePairOverload) // expected-error {{cannot convert value of type '((Int, Int?)) -> ()' to expected argument type '(Int, Int?) -> ()'}} takeFn(fn: { (pair: (Int, Int?)) in } ) // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} takeFn { (pair: (Int, Int?)) in } // Disallow for -swift-version 4 and later // expected-error@-1 {{contextual closure type '(Int, Int?) -> ()' expects 2 arguments, but 1 was used in closure body}} } // https://bugs.swift.org/browse/SR-6796 do { func f(a: (() -> Void)? = nil) {} func log<T>() -> ((T) -> Void)? { return nil } f(a: log() as ((()) -> Void)?) // expected-error {{cannot convert value of type '((()) -> Void)?' to expected argument type '(() -> Void)?'}} func logNoOptional<T>() -> (T) -> Void { } f(a: logNoOptional() as ((()) -> Void)) // expected-error {{cannot convert value of type '(()) -> Void' to expected argument type '() -> Void'}} func g() {} g(()) // expected-error {{argument passed to call that takes no arguments}} func h(_: ()) {} // expected-note {{'h' declared here}} h() // expected-error {{missing argument for parameter #1 in call}} } // https://bugs.swift.org/browse/SR-7191 class Mappable<T> { init(_: T) { } func map<U>(_ body: (T) -> U) -> U { fatalError() } } let x = Mappable(()) // expected-note@-1 2{{'x' declared here}} x.map { (_: Void) in return () } x.map { (_: ()) in () } // https://bugs.swift.org/browse/SR-9470 do { func f(_: Int...) {} let _ = [(1, 2, 3)].map(f) // expected-error {{no exact matches in call to instance method 'map'}} // expected-note@-1 {{found candidate with type '(((Int, Int, Int)) throws -> _) throws -> Array<_>'}} } // rdar://problem/48443263 - cannot convert value of type '() -> Void' to expected argument type '(_) -> Void' protocol P_48443263 { associatedtype V } func rdar48443263() { func foo<T : P_48443263>(_: T, _: (T.V) -> Void) {} struct S1 : P_48443263 { typealias V = Void } struct S2: P_48443263 { typealias V = Int } func bar(_ s1: S1, _ s2: S2, _ fn: () -> Void) { foo(s1, fn) // Ok because s.V is Void foo(s2, fn) // expected-error {{cannot convert value of type '() -> Void' to expected argument type '(S2.V) -> Void' (aka '(Int) -> ()')}} } } func autoclosureSplat() { func takeFn<T>(_: (T) -> ()) {} takeFn { (fn: @autoclosure () -> Int) in } // This type checks because we find a solution T:= @escaping () -> Int and // wrap the closure in a function conversion. takeFn { (fn: @autoclosure () -> Int, x: Int) in } // expected-error@-1 {{contextual closure type '(() -> Int) -> ()' expects 1 argument, but 2 were used in closure body}} // expected-error@-2 {{converting non-escaping value to 'T' may allow it to escape}} takeFn { (fn: @autoclosure @escaping () -> Int) in } // FIXME: It looks like matchFunctionTypes() does not check @autoclosure at all. // Perhaps this is intentional, but we should document it eventually. In the // interim, this test serves as "documentation"; if it fails, please investigate why // instead of changing the test. takeFn { (fn: @autoclosure @escaping () -> Int, x: Int) in } // expected-error@-1 {{contextual closure type '(@escaping () -> Int) -> ()' expects 1 argument, but 2 were used in closure body}} } func noescapeSplat() { func takesFn<T>(_ fn: (T) -> ()) -> T {} func takesEscaping(_: @escaping () -> Int) {} do { let t = takesFn { (fn: () -> Int) in } takesEscaping(t) // This type checks because we find a solution T:= (@escaping () -> Int). } do { let t = takesFn { (fn: () -> Int, x: Int) in } // expected-error@-1 {{converting non-escaping value to 'T' may allow it to escape}} takesEscaping(t.0) } }
apache-2.0
73ccad8a333fe2c0bb96cc0464a402b4
35.732617
253
0.63458
3.416943
false
false
false
false
mxcl/swift-package-manager
Sources/Xcodeproj/xcscheme().swift
1
3047
/* This source file is part of the Swift.org open source project Copyright 2015 - 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 Swift project authors */ import PackageGraph import PackageModel func xcscheme(container: String, graph: PackageGraph, enableCodeCoverage: Bool, printer print: (String) -> Void) { print("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") print("<Scheme LastUpgradeVersion = \"9999\" version = \"1.3\">") print(" <BuildAction parallelizeBuildables = \"YES\" buildImplicitDependencies = \"YES\">") print(" <BuildActionEntries>") // Create buildable references for non-test modules. for module in graph.modules where !module.isTest { // Ignore system modules. // // FIXME: We shouldn't need to manually do this here, instead this // should be phrased in terms of the set of targets we computed. if module.type == .systemModule { continue } print(" <BuildActionEntry buildForTesting = \"YES\" buildForRunning = \"YES\" buildForProfiling = \"YES\" buildForArchiving = \"YES\" buildForAnalyzing = \"YES\">") print(" <BuildableReference") print(" BuildableIdentifier = \"primary\"") print(" BlueprintIdentifier = \"\(module.blueprintIdentifier)\"") print(" BuildableName = \"\(module.buildableName)\"") print(" BlueprintName = \"\(module.blueprintName)\"") print(" ReferencedContainer = \"container:\(container)\">") print(" </BuildableReference>") print(" </BuildActionEntry>") } print(" </BuildActionEntries>") print(" </BuildAction>") print(" <TestAction") print(" buildConfiguration = \"Debug\"") print(" selectedDebuggerIdentifier = \"Xcode.DebuggerFoundation.Debugger.LLDB\"") print(" selectedLauncherIdentifier = \"Xcode.DebuggerFoundation.Launcher.LLDB\"") print(" shouldUseLaunchSchemeArgsEnv = \"YES\"") print(" codeCoverageEnabled = \"\(enableCodeCoverage ? "YES" : "NO")\">") print(" <Testables>") // Create testable references. for module in graph.modules where module.isTest { print(" <TestableReference") print(" skipped = \"NO\">") print(" <BuildableReference") print(" BuildableIdentifier = \"primary\"") print(" BlueprintIdentifier = \"\(module.blueprintIdentifier)\"") print(" BuildableName = \"\(module.buildableName)\"") print(" BlueprintName = \"\(module.blueprintName)\"") print(" ReferencedContainer = \"container:\(container)\">") print(" </BuildableReference>") print(" </TestableReference>") } print(" </Testables>") print(" </TestAction>") print("</Scheme>") }
apache-2.0
00e5f953a0b66401b61a34a05ef26552
43.808824
177
0.612734
4.673313
false
true
false
false
shajrawi/swift
test/IRGen/class_resilience_objc.swift
1
6122
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend -emit-module -enable-library-evolution -emit-module-path=%t/resilient_struct.swiftmodule -module-name=resilient_struct %S/../Inputs/resilient_struct.swift // RUN: %target-swift-frontend(mock-sdk: %clang-importer-sdk) -I %t -enable-library-evolution -enable-objc-interop -emit-ir -o - -primary-file %s | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize -DINT=i%target-ptrsize // XFAIL: CPU=armv7k // XFAIL: CPU=powerpc64le import Foundation import resilient_struct // Note that these are all mutable to allow for the runtime to slide them. // CHECK: @"$s21class_resilience_objc27ClassWithEmptyThenResilientC9resilient0I7_struct0H3IntVvpWvd" = hidden global [[INT]] 0, // CHECK: @"$s21class_resilience_objc27ClassWithResilientThenEmptyC9resilient0I7_struct0F3IntVvpWvd" = hidden global [[INT]] 0, // CHECK: @"$s21class_resilience_objc27ClassWithEmptyThenResilientC5emptyAA0F0VvpWvd" = hidden global [[INT]] 0, // CHECK: @"$s21class_resilience_objc27ClassWithResilientThenEmptyC5emptyAA0H0VvpWvd" = hidden global [[INT]] 0, public class FixedLayoutObjCSubclass : NSObject { // This field could use constant direct access because NSObject has // fixed layout, but we don't allow that right now. public final var field: Int32 = 0 }; // CHECK-LABEL: define hidden swiftcc void @"$s21class_resilience_objc29testConstantDirectFieldAccessyyAA23FixedLayoutObjCSubclassCF"(%T21class_resilience_objc23FixedLayoutObjCSubclassC*) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s21class_resilience_objc23FixedLayoutObjCSubclassC5fields5Int32VvpWvd" // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T21class_resilience_objc23FixedLayoutObjCSubclassC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: store i32 10, i32* [[PAYLOAD_ADDR]] func testConstantDirectFieldAccess(_ o: FixedLayoutObjCSubclass) { o.field = 10 } public class NonFixedLayoutObjCSubclass : NSCoder { // This field uses non-constant direct access because NSCoder has resilient // layout. public final var field: Int32 = 0 } // CHECK-LABEL: define hidden swiftcc void @"$s21class_resilience_objc32testNonConstantDirectFieldAccessyyAA0E23FixedLayoutObjCSubclassCF"(%T21class_resilience_objc26NonFixedLayoutObjCSubclassC*) // CHECK: [[OFFSET:%.*]] = load [[INT]], [[INT]]* @"$s21class_resilience_objc26NonFixedLayoutObjCSubclassC5fields5Int32VvpWvd" // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T21class_resilience_objc26NonFixedLayoutObjCSubclassC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: store i32 10, i32* [[PAYLOAD_ADDR]] func testNonConstantDirectFieldAccess(_ o: NonFixedLayoutObjCSubclass) { o.field = 10 } public class GenericObjCSubclass<T> : NSCoder { public final var content: T public final var field: Int32 = 0 public init(content: T) { self.content = content } } // CHECK-LABEL: define hidden swiftcc void @"$s21class_resilience_objc31testConstantIndirectFieldAccessyyAA19GenericObjCSubclassCyxGlF"(%T21class_resilience_objc19GenericObjCSubclassC*) // FIXME: we could eliminate the unnecessary isa load by lazily emitting // metadata sources in EmitPolymorphicParameters // CHECK: bitcast %T21class_resilience_objc19GenericObjCSubclassC* %0 // CHECK-32: [[ADDR:%.*]] = bitcast %T21class_resilience_objc19GenericObjCSubclassC* %0 to %swift.type** // CHECK-32-NEXT: [[ISA:%.*]] = load %swift.type*, %swift.type** [[ADDR]] // CHECK-64: [[ADDR:%.*]] = bitcast %T21class_resilience_objc19GenericObjCSubclassC* %0 to [[INT]]* // CHECK-64-NEXT: [[ISA:%.*]] = load [[INT]], [[INT]]* [[ADDR]] // CHECK-64-NEXT: [[ISA_MASK:%.*]] = load [[INT]], [[INT]]* @swift_isaMask // CHECK-64-NEXT: [[ISA_VALUE:%.*]] = and [[INT]] [[ISA]], [[ISA_MASK]] // CHECK-64-NEXT: [[ISA:%.*]] = inttoptr [[INT]] [[ISA_VALUE]] to %swift.type* // CHECK-NEXT: [[ISA_ADDR:%.*]] = bitcast %swift.type* [[ISA]] to [[INT]]* // CHECK-32-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[ISA_ADDR]], [[INT]] 15 // CHECK-64-NEXT: [[FIELD_OFFSET_ADDR:%.*]] = getelementptr inbounds [[INT]], [[INT]]* [[ISA_ADDR]], [[INT]] 12 // CHECK-NEXT: [[FIELD_OFFSET:%.*]] = load [[INT]], [[INT]]* [[FIELD_OFFSET_ADDR:%.*]] // CHECK-NEXT: [[OBJECT:%.*]] = bitcast %T21class_resilience_objc19GenericObjCSubclassC* %0 to i8* // CHECK-NEXT: [[ADDR:%.*]] = getelementptr inbounds i8, i8* [[OBJECT]], [[INT]] [[FIELD_OFFSET]] // CHECK-NEXT: [[FIELD_ADDR:%.*]] = bitcast i8* [[ADDR]] to %Ts5Int32V* // CHECK: call void @swift_beginAccess // CHECK-NEXT: [[PAYLOAD_ADDR:%.*]] = getelementptr inbounds %Ts5Int32V, %Ts5Int32V* [[FIELD_ADDR]], i32 0, i32 0 // CHECK-NEXT: store i32 10, i32* [[PAYLOAD_ADDR]] func testConstantIndirectFieldAccess<T>(_ o: GenericObjCSubclass<T>) { // This field uses constant indirect access because NSCoder has resilient // layout. Non-constant indirect is never needed for Objective-C classes // because the field offset vector only contains Swift field offsets. o.field = 10 } @_fixed_layout public struct Empty {} public class ClassWithEmptyThenResilient : DummyClass { public let empty: Empty public let resilient: ResilientInt public init(empty: Empty, resilient: ResilientInt) { self.empty = empty self.resilient = resilient } } public class ClassWithResilientThenEmpty : DummyClass { public let resilient: ResilientInt public let empty: Empty public init(empty: Empty, resilient: ResilientInt) { self.empty = empty self.resilient = resilient } }
apache-2.0
31436103bc540481482b4c30ade2940e
49.180328
242
0.708265
3.665868
false
false
false
false
JohnSansoucie/MyProject2
BlueCap/Beacon/BeaconRegionsViewController.swift
1
10154
// // BeaconRegionsViewController.swift // BlueCap // // Created by Troy Stribling on 9/16/14. // Copyright (c) 2014 gnos.us. All rights reserved. // import UIKit import BlueCapKit class BeaconRegionsViewController: UITableViewController { var stopScanBarButtonItem : UIBarButtonItem! var startScanBarButtonItem : UIBarButtonItem! var beaconRegions = [String:BeaconRegion]() struct MainStoryBoard { static let beaconRegionCell = "BeaconRegionCell" static let beaconsSegue = "Beacons" static let beaconRegionAddSegue = "BeaconRegionAdd" static let beaconRegionEditSegue = "BeaconRegionEdit" } required init(coder aDecoder:NSCoder) { super.init(coder:aDecoder) self.stopScanBarButtonItem = UIBarButtonItem(barButtonSystemItem:.Stop, target:self, action:"toggleMonitoring:") self.startScanBarButtonItem = UIBarButtonItem(title:"Scan", style:UIBarButtonItemStyle.Bordered, target:self, action:"toggleMonitoring:") self.styleUIBarButton(self.startScanBarButtonItem) } override func viewDidLoad() { super.viewDidLoad() self.styleNavigationBar() } override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) self.tableView.reloadData() self.navigationItem.title = "Beacon Regions" self.setScanButton() NSNotificationCenter.defaultCenter().addObserver(self, selector:"didBecomeActive", name:BlueCapNotification.didBecomeActive, object:nil) NSNotificationCenter.defaultCenter().addObserver(self, selector:"didResignActive", name:BlueCapNotification.didResignActive, object:nil) } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) NSNotificationCenter.defaultCenter().removeObserver(self) self.navigationItem.title = "" } override func prepareForSegue(segue:UIStoryboardSegue, sender:AnyObject!) { if segue.identifier == MainStoryBoard.beaconsSegue { let selectedIndexPath = sender as NSIndexPath let beaconsViewController = segue.destinationViewController as BeaconsViewController let beaconName = BeaconStore.getBeaconNames()[selectedIndexPath.row] if let beaconRegion = self.beaconRegions[beaconName] { beaconsViewController.beaconRegion = beaconRegion } } else if segue.identifier == MainStoryBoard.beaconRegionAddSegue { } else if segue.identifier == MainStoryBoard.beaconRegionEditSegue { let selectedIndexPath = sender as NSIndexPath let viewController = segue.destinationViewController as BeaconRegionViewController viewController.regionName = BeaconStore.getBeaconNames()[selectedIndexPath.row] } } func toggleMonitoring(sender:AnyObject) { if CentralManager.sharedInstance.isScanning == false { let beaconManager = BeaconManager.sharedInstance if beaconManager.isRanging { beaconManager.stopRangingAllBeacons() beaconManager.stopMonitoringAllRegions() self.beaconRegions.removeAll(keepCapacity:false) self.setScanButton() } else { self.startMonitoring() } self.tableView.reloadData() } else { self.presentViewController(UIAlertController.alertWithMessage("Central scan is active. Cannot scan and monitor simutaneously. Stop scan to start monitoring"), animated:true, completion:nil) } } func setScanButton() { if BeaconManager.sharedInstance.isRanging { self.navigationItem.setLeftBarButtonItem(self.stopScanBarButtonItem, animated:false) } else { self.navigationItem.setLeftBarButtonItem(self.startScanBarButtonItem, animated:false) } } func startMonitoring() { for (name, uuid) in BeaconStore.getBeacons() { let beacon = BeaconRegion(proximityUUID:uuid, identifier:name) let regionFuture = BeaconManager.sharedInstance.startMonitoringForRegion(beacon) let beaconFuture = regionFuture.flatmap {status -> FutureStream<[Beacon]> in switch status { case .Inside: let beaconManager = BeaconManager.sharedInstance if !beaconManager.isRangingRegion(beacon.identifier) { self.updateDisplay() Notify.withMessage("Entering region '\(name)'. Started ranging beacons.") return beaconManager.startRangingBeaconsInRegion(beacon) } else { let errorPromise = StreamPromise<[Beacon]>() errorPromise.failure(BCAppError.rangingBeacons) return errorPromise.future } case .Outside: BeaconManager.sharedInstance.stopRangingBeaconsInRegion(beacon) self.updateWhenActive() Notify.withMessage("Exited region '\(name)'. Stoped ranging beacons.") let errorPromise = StreamPromise<[Beacon]>() errorPromise.failure(BCAppError.outOfRegion) return errorPromise.future case .Start: self.setScanButton() Logger.debug("BeaconRegionsViewController#startMonitoring: started monitoring region \(name)") return BeaconManager.sharedInstance.startRangingBeaconsInRegion(beacon) } } beaconFuture.onSuccess {beacons in for beacon in beacons { Logger.debug("major:\(beacon.major), minor: \(beacon.minor), rssi: \(beacon.rssi)") } self.updateWhenActive() if UIApplication.sharedApplication().applicationState == .Active && beacons.count > 0 { NSNotificationCenter.defaultCenter().postNotificationName(BlueCapNotification.didUpdateBeacon, object:beacon) } } regionFuture.onFailure {error in BeaconManager.sharedInstance.stopRangingBeaconsInRegion(beacon) self.updateWhenActive() self.presentViewController(UIAlertController.alertOnError(error), animated:true, completion:nil) } self.beaconRegions[name] = beacon } } func updateDisplay() { if UIApplication.sharedApplication().applicationState == .Active { self.tableView.reloadData() } } func didResignActive() { Logger.debug("BeaconRegionsViewController#didResignActive") } func didBecomeActive() { Logger.debug("BeaconRegionsViewController#didBecomeActive") self.tableView.reloadData() } // UITableViewDataSource override func numberOfSectionsInTableView(tableView:UITableView) -> Int { return 1 } override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return BeaconStore.getBeacons().count } override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryBoard.beaconRegionCell, forIndexPath: indexPath) as BeaconRegionCell let name = BeaconStore.getBeaconNames()[indexPath.row] let beaconRegions = BeaconStore.getBeacons() if let beaconRegionUUID = beaconRegions[name] { cell.nameLabel.text = name cell.uuidLabel.text = beaconRegionUUID.UUIDString } cell.nameLabel.textColor = UIColor.blackColor() cell.beaconsLabel.text = "0" cell.nameLabel.textColor = UIColor.lightGrayColor() cell.statusLabel.textColor = UIColor.lightGrayColor() if BeaconManager.sharedInstance.isRangingRegion(name) { if let region = BeaconManager.sharedInstance.beaconRegion(name) { if region.beacons.count == 0 { cell.statusLabel.text = "Monitoring" } else { cell.nameLabel.textColor = UIColor.blackColor() cell.beaconsLabel.text = "\(region.beacons.count)" cell.statusLabel.text = "Ranging" cell.statusLabel.textColor = UIColor(red:0.1, green:0.7, blue:0.1, alpha:0.5) } } } else if CentralManager.sharedInstance.isScanning { cell.statusLabel.text = "Monitoring" } else { cell.statusLabel.text = "Idle" } return cell } override func tableView(tableView:UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool { let name = BeaconStore.getBeaconNames()[indexPath.row] return !BeaconManager.sharedInstance.isRangingRegion(name) } override func tableView(tableView:UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath:NSIndexPath) { if editingStyle == .Delete { let name = BeaconStore.getBeaconNames()[indexPath.row] BeaconStore.removeBeacon(name) tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation:.Fade) } } // UITableViewDelegate override func tableView(tableView:UITableView, didSelectRowAtIndexPath indexPath:NSIndexPath) { let name = BeaconStore.getBeaconNames()[indexPath.row] if BeaconManager.sharedInstance.isRangingRegion(name) { if let beaconRegion = self.beaconRegions[name] { if beaconRegion.beacons.count > 0 { self.performSegueWithIdentifier(MainStoryBoard.beaconsSegue, sender:indexPath) } } } else { self.performSegueWithIdentifier(MainStoryBoard.beaconRegionEditSegue, sender:indexPath) } } }
mit
097dc17d44f6afe05faec1b1ca3b5b6a
44.330357
201
0.644672
5.955425
false
false
false
false
MTTHWBSH/Short-Daily-Devotions
Short Daily Devotions/Views/Cells/Post/PostDetailsCell.swift
1
1768
// // PostDetailsCell.swift // Short Daily Devotions // // Created by Matthew Bush on 11/25/16. // Copyright © 2016 Matt Bush. All rights reserved. // import UIKit import PureLayout class PostDetailsCell: UITableViewCell { static let kReuseIdentifier = "PostDeatailsCell" var title: String var date: String? let titleLabel = UILabel() let dateLabel = UILabel() init(title: String, date: String?) { self.title = title self.date = date super.init(style: .default, reuseIdentifier: PostDetailsCell.kReuseIdentifier) self.styleView() self.setupTitle() self.setupDate() } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func styleView() { backgroundColor = Style.grayLight selectionStyle = .none } private func setupTitle() { titleLabel.text = title.uppercased() titleLabel.textColor = Style.blue titleLabel.font = Style.boldFont(withSize: 20) titleLabel.numberOfLines = 0 addSubview(titleLabel) titleLabel.autoPinEdgesToSuperviewEdges(with: UIEdgeInsetsMake(20, 8, 0, 8), excludingEdge: .bottom) } private func setupDate() { dateLabel.text = date dateLabel.font = Style.lightFont(withSize: 16) dateLabel.numberOfLines = 0 addSubview(dateLabel) dateLabel.autoPinEdge(.top, to: .bottom, of: titleLabel, withOffset: 5) dateLabel.autoPinEdge(.leading, to: .leading, of: titleLabel, withOffset: 0) dateLabel.autoPinEdge(.trailing, to: .trailing, of: titleLabel, withOffset: 0) dateLabel.autoPinEdge(toSuperviewEdge: .bottom) } }
mit
9b83e37a72dfb03ec96066a50ccdaf98
28.45
108
0.646859
4.542416
false
false
false
false
SwiftAndroid/swift
stdlib/private/SwiftPrivatePthreadExtras/PthreadBarriers.swift
4
3654
//===--- PthreadBarriers.swift --------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// #if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #elseif os(Linux) || os(FreeBSD) || os(Android) import Glibc #endif // // Implement pthread barriers. // // (OS X does not implement them.) // public struct _stdlib_pthread_barrierattr_t { public init() {} } public func _stdlib_pthread_barrierattr_init( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public func _stdlib_pthread_barrierattr_destroy( _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t> ) -> CInt { return 0 } public var _stdlib_PTHREAD_BARRIER_SERIAL_THREAD: CInt { return 1 } public struct _stdlib_pthread_barrier_t { var mutex: UnsafeMutablePointer<pthread_mutex_t>? = nil var cond: UnsafeMutablePointer<pthread_cond_t>? = nil /// The number of threads to synchronize. var count: CUnsignedInt = 0 /// The number of threads already waiting on the barrier. /// /// This shared variable is protected by `mutex`. var numThreadsWaiting: CUnsignedInt = 0 public init() {} } public func _stdlib_pthread_barrier_init( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t>, _ attr: UnsafeMutablePointer<_stdlib_pthread_barrierattr_t>?, _ count: CUnsignedInt ) -> CInt { barrier.pointee = _stdlib_pthread_barrier_t() if count == 0 { errno = EINVAL return -1 } barrier.pointee.mutex = UnsafeMutablePointer(allocatingCapacity: 1) if pthread_mutex_init(barrier.pointee.mutex!, nil) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond = UnsafeMutablePointer(allocatingCapacity: 1) if pthread_cond_init(barrier.pointee.cond!, nil) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } barrier.pointee.count = count return 0 } public func _stdlib_pthread_barrier_destroy( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_cond_destroy(barrier.pointee.cond!) != 0 { // FIXME: leaking memory, leaking a mutex. return -1 } if pthread_mutex_destroy(barrier.pointee.mutex!) != 0 { // FIXME: leaking memory. return -1 } barrier.pointee.cond!.deinitialize() barrier.pointee.cond!.deallocateCapacity(1) barrier.pointee.mutex!.deinitialize() barrier.pointee.mutex!.deallocateCapacity(1) return 0 } public func _stdlib_pthread_barrier_wait( _ barrier: UnsafeMutablePointer<_stdlib_pthread_barrier_t> ) -> CInt { if pthread_mutex_lock(barrier.pointee.mutex!) != 0 { return -1 } barrier.pointee.numThreadsWaiting += 1 if barrier.pointee.numThreadsWaiting < barrier.pointee.count { // Put the thread to sleep. if pthread_cond_wait(barrier.pointee.cond!, barrier.pointee.mutex!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return 0 } else { // Reset thread count. barrier.pointee.numThreadsWaiting = 0 // Wake up all threads. if pthread_cond_broadcast(barrier.pointee.cond!) != 0 { return -1 } if pthread_mutex_unlock(barrier.pointee.mutex!) != 0 { return -1 } return _stdlib_PTHREAD_BARRIER_SERIAL_THREAD } }
apache-2.0
c47f150037e1e6b02b2bac4a46fd5f9b
26.89313
80
0.66694
3.887234
false
false
false
false
tiagobsbraga/HotmartTest
HotmartTest/MessageViewController.swift
1
2707
// // MessageViewController.swift // HotmartTest // // Created by Tiago Braga on 06/02/17. // Copyright © 2017 Tiago Braga. All rights reserved. // import UIKit class MessageViewController: BaseViewController { let itemsMessage: [Message] = [ Message(photo: UIImage(named: "persona")!, name: "Tiago Braga"), Message(photo: nil, name: "Valeria Cirqueira"), Message(photo: nil, name: "Maria Carol"), Message(photo: nil, name: "Flávia de Alcântrara Cirqueira"), Message(photo: nil, name: "Ana Paula Pereira"), Message(photo: UIImage(named: "persona")!, name: "Tiago Braga"), Message(photo: nil, name: "Valeria Cirqueira"), Message(photo: nil, name: "Maria Carol"), Message(photo: nil, name: "Flávia de Alcântrara Cirqueira"), Message(photo: nil, name: "Ana Paula Pereira") ] static let ReuseCell: String = "MessageCell" @IBOutlet weak var collectionView: UICollectionView! override func viewDidLoad() { super.viewDidLoad() self.title = Localizable.string(forKey: "title_messages") self.customColorNavigationBar(Style.Color.yellow, extendNavigationBar: true) self.configCollectionView() self.customRightButtonItem() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() print("didReceiveMemoryWarning"); } // MARK: Public Methods // MARK: Private Methods private func configCollectionView() { self.collectionView.register(UIView.loadNib(MessageViewController.ReuseCell), forCellWithReuseIdentifier: MessageViewController.ReuseCell) } private func customRightButtonItem() { let tagView: TagView = UIView.loadView("TagView", index: 0) as! TagView let barButtonItem: UIBarButtonItem = UIBarButtonItem(customView: tagView) self.navigationItem.rightBarButtonItem = barButtonItem } // MARK: Notifications // MARK: Actions } extension MessageViewController: UICollectionViewDataSource { func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return self.itemsMessage.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell: MessageCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: MessageViewController.ReuseCell, for: indexPath) as! MessageCollectionViewCell let message = self.itemsMessage[indexPath.row] cell.populateMessage(message) return cell } }
mit
8ca70028c3f04d382da199ea81d711f3
33.202532
180
0.680237
4.842294
false
false
false
false
huankong/Weibo
Weibo/Weibo/Main/Base/NewFeature/WelcomeViewController.swift
1
2712
// // WelcomeViewController.swift // Weibo // // Created by ldy on 16/7/7. // Copyright © 2016年 ldy. All rights reserved. // import UIKit import SDWebImage class WelcomeViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() /// 初始化视图 setupView() } // deinit { // print("WelcomeViewController销毁") // } /// 初始化视图 func setupView() { view.addSubview(bgImgeV) view.addSubview(iconImageV) view.addSubview(textLabel) bgImgeV.snp_makeConstraints { (make) in make.edges.equalTo(view) } iconImageV.snp_makeConstraints { (make) in make.size.equalTo(CGSize(width: 100, height: 100)) make.centerX.equalTo(view) make.centerY.equalTo(view).offset(-50) } textLabel.snp_makeConstraints { (make) in make.top.equalTo(iconImageV.snp_bottom).offset(20) make.centerX.equalTo(view) } } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) // self.iconImageV.transform = CGAffineTransformMakeScale(0,0) self.iconImageV.transform = CGAffineTransformMakeTranslation(0, 200) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 2, options: UIViewAnimationOptions.init(rawValue: 0), animations: { self.iconImageV.transform = CGAffineTransformMakeTranslation(0, 0) }) { (_) in UIView.animateWithDuration(0.5, animations: { self.textLabel.alpha = 1 }, completion: { (_) in NSNotificationCenter.defaultCenter().postNotificationName(KSwiftRootViewControllerKey, object: true) }) } } // MARK: - 懒加载 /// 大背景图 private lazy var bgImgeV = UIImageView(image: UIImage(named: "ad_background")) ///头像 private lazy var iconImageV: UIImageView = { let imgV = UIImageView() imgV.layer.cornerRadius = 50 imgV.layer.masksToBounds = true if let largeName = UserAcount.readAccount()?.avatar_large { imgV.sd_setImageWithURL(NSURL(string: largeName)) }else { let imageName = "avatar_default_big" imgV.image = UIImage(named: imageName) } return imgV }() private lazy var textLabel: UILabel = { let label = UILabel() label.textColor = UIColor.grayColor() label.text = "欢迎回来" label.sizeToFit() label.alpha = 0 return label }() }
apache-2.0
af4d4e4fde2ae4c58e59fba07b048744
30.654762
169
0.592704
4.576592
false
false
false
false
benlangmuir/swift
test/Interop/SwiftToCxx/structs/resilient-struct-in-cxx.swift
2
10500
// RUN: %empty-directory(%t) // RUN: %target-swift-frontend %s -enable-library-evolution -typecheck -module-name Structs -clang-header-expose-public-decls -emit-clang-header-path %t/structs.h // RUN: %FileCheck %s < %t/structs.h // RUN: %check-interop-cxx-header-in-clang(%t/structs.h) public struct FirstSmallStruct { public var x: UInt32 #if CHANGE_LAYOUT public var y: UInt32 = 0 #endif public func dump() { print("find - small dump") #if CHANGE_LAYOUT print("x&y = \(x)&\(y)") #else print("x = \(x)") #endif } public mutating func mutate() { x = x * 2 #if CHANGE_LAYOUT y = ~y #endif } } // CHECK: class FirstSmallStruct final { // CHECK-NEXT: public: // CHECK: inline FirstSmallStruct(const FirstSmallStruct &other) { // CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment()); // CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0); // CHECK-NEXT: } // CHECK: private: // CHECK-NEXT: inline FirstSmallStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {} // CHECK-NEXT: static inline FirstSmallStruct _make() { // CHECK-NEXT: auto metadata = _impl::$s7Structs16FirstSmallStructVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: return FirstSmallStruct(vwTable); // CHECK-NEXT: } // CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); } // CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); } // CHECK-EMPTY: // CHECK-NEXT: swift::_impl::OpaqueStorage _storage; // CHECK-NEXT: friend class _impl::_impl_FirstSmallStruct; // CHECK-NEXT:}; // CHECK: class _impl_FirstSmallStruct { // CHECK: }; // CHECK-EMPTY: // CHECK-NEXT: } // CHECK-EMPTY: // CHECK-NEXT: } // end namespace // CHECK-EMPTY: // CHECK-NEXT: namespace swift { // CHECK-NEXT: #pragma clang diagnostic push // CHECK-NEXT: #pragma clang diagnostic ignored "-Wc++17-extensions" // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isUsableInGenericContext<Structs::FirstSmallStruct> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct TypeMetadataTrait<Structs::FirstSmallStruct> { // CHECK-NEXT: inline void * _Nonnull getTypeMetadata() { // CHECK-NEXT: return Structs::_impl::$s7Structs16FirstSmallStructVMa(0)._0; // CHECK-NEXT: } // CHECK-NEXT: }; // CHECK-NEXT: namespace _impl{ // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isValueType<Structs::FirstSmallStruct> = true; // CHECK-NEXT: template<> // CHECK-NEXT: static inline const constexpr bool isOpaqueLayout<Structs::FirstSmallStruct> = true; // CHECK-NEXT: template<> // CHECK-NEXT: struct implClassFor<Structs::FirstSmallStruct> { using type = Structs::_impl::_impl_FirstSmallStruct; }; // CHECK-NEXT: } // namespace // CHECK-NEXT: #pragma clang diagnostic pop // CHECK-NEXT: } // namespace swift // CHECK-EMPTY: // CHECK-NEXT: namespace Structs { @frozen public struct FrozenStruct { private let storedInt: Int32 } // CHECK: class FrozenStruct final { // CHECK: alignas(4) char _storage[4]; // CHECK-NEXT: friend class _impl::_impl_FrozenStruct; // CHECK-NEXT: }; public struct LargeStruct { public let x1: Int let x2, x3, x4, x5, x6: Int public var firstSmallStruct: FirstSmallStruct { return FirstSmallStruct(x: 65) } public func dump() { print("x.1 = \(x1), .2 = \(x2), .3 = \(x3), .4 = \(x4), .5 = \(x5)") } } // CHECK: class LargeStruct final { // CHECK-NEXT: public: // CHECK: inline LargeStruct(const LargeStruct &other) { // CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: _storage = swift::_impl::OpaqueStorage(vwTable->size, vwTable->getAlignment()); // CHECK-NEXT: vwTable->initializeWithCopy(_getOpaquePointer(), const_cast<char *>(other._getOpaquePointer()), metadata._0); // CHECK-NEXT: } // CHECK: private: // CHECK-NEXT: inline LargeStruct(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {} // CHECK-NEXT: static inline LargeStruct _make() { // CHECK-NEXT: auto metadata = _impl::$s7Structs11LargeStructVMa(0); // CHECK-NEXT: auto *vwTableAddr = reinterpret_cast<swift::_impl::ValueWitnessTable **>(metadata._0) - 1; // CHECK-NEXT: #ifdef __arm64e__ // CHECK-NEXT: auto *vwTable = reinterpret_cast<swift::_impl::ValueWitnessTable *>(ptrauth_auth_data(reinterpret_cast<void *>(*vwTableAddr), ptrauth_key_process_independent_data, ptrauth_blend_discriminator(vwTableAddr, 11839))); // CHECK-NEXT: #else // CHECK-NEXT: auto *vwTable = *vwTableAddr; // CHECK-NEXT: #endif // CHECK-NEXT: return LargeStruct(vwTable); // CHECK-NEXT: } // CHECK-NEXT: inline const char * _Nonnull _getOpaquePointer() const { return _storage.getOpaquePointer(); } // CHECK-NEXT: inline char * _Nonnull _getOpaquePointer() { return _storage.getOpaquePointer(); } // CHECK-EMPTY: // CHECK-NEXT: swift::_impl::OpaqueStorage _storage; // CHECK-NEXT: friend class _impl::_impl_LargeStruct; // CHECK-NEXT: }; private class RefCountedClass { let x: Int init(x: Int) { self.x = x print("create RefCountedClass \(x)") } deinit { print("destroy RefCountedClass \(x)") } } public struct StructWithRefCountStoredProp { private let storedRef: RefCountedClass init(x: Int) { storedRef = RefCountedClass(x: x) } public func dump() { print("storedRef = \(storedRef.x)") } } // CHECK: inline StructWithRefCountStoredProp(swift::_impl::ValueWitnessTable * _Nonnull vwTable) : _storage(vwTable->size, vwTable->getAlignment()) {} public func createLargeStruct(_ x: Int) -> LargeStruct { return LargeStruct(x1: x, x2: -x, x3: x * 2, x4: x - 4, x5: 0, x6: 21) } public func printSmallAndLarge(_ x: FirstSmallStruct, _ y: LargeStruct) { x.dump() y.dump() } public func createStructWithRefCountStoredProp() -> StructWithRefCountStoredProp { return StructWithRefCountStoredProp(x: 0) } public func mutateSmall(_ x: inout FirstSmallStruct) { #if CHANGE_LAYOUT let y = x.y x.y = x.x x.x = y #else x.x += 1 #endif } // CHECK: inline LargeStruct createLargeStruct(swift::Int x) noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_LargeStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s7Structs17createLargeStructyAA0cD0VSiF(result, x); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline StructWithRefCountStoredProp createStructWithRefCountStoredProp() noexcept SWIFT_WARN_UNUSED_RESULT { // CHECK-NEXT: return _impl::_impl_StructWithRefCountStoredProp::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s7Structs34createStructWithRefCountStoredPropAA0cdefgH0VyF(result); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK: inline void mutateSmall(FirstSmallStruct& x) noexcept { // CHECK-NEXT: return _impl::$s7Structs11mutateSmallyyAA05FirstC6StructVzF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x)); // CHECK-NEXT: } // CHECK: inline void printSmallAndLarge(const FirstSmallStruct& x, const LargeStruct& y) noexcept { // CHECK-NEXT: return _impl::$s7Structs18printSmallAndLargeyyAA05FirstC6StructV_AA0eG0VtF(_impl::_impl_FirstSmallStruct::getOpaquePointer(x), _impl::_impl_LargeStruct::getOpaquePointer(y)); // CHECK-NEXT: } // CHECK: inline uint32_t FirstSmallStruct::getX() const { // CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvg(_getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline void FirstSmallStruct::setX(uint32_t value) { // CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV1xs6UInt32Vvs(value, _getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline void FirstSmallStruct::dump() const { // CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV4dumpyyF(_getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline void FirstSmallStruct::mutate() { // CHECK-NEXT: return _impl::$s7Structs16FirstSmallStructV6mutateyyF(_getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline swift::Int LargeStruct::getX1() const { // CHECK-NEXT: return _impl::$s7Structs11LargeStructV2x1Sivg(_getOpaquePointer()); // CHECK-NEXT: } // CHECK-NEXT: inline FirstSmallStruct LargeStruct::getFirstSmallStruct() const { // CHECK-NEXT: return _impl::_impl_FirstSmallStruct::returnNewValue([&](char * _Nonnull result) { // CHECK-NEXT: _impl::$s7Structs11LargeStructV010firstSmallC0AA05FirsteC0Vvg(result, _getOpaquePointer()); // CHECK-NEXT: }); // CHECK-NEXT: } // CHECK-NEXT: inline void LargeStruct::dump() const { // CHECK-NEXT: return _impl::$s7Structs11LargeStructV4dumpyyF(_getOpaquePointer()); // CHECK-NEXT: } // CHECK: inline void StructWithRefCountStoredProp::dump() const { // CHECK-NEXT: return _impl::$s7Structs28StructWithRefCountStoredPropV4dumpyyF(_getOpaquePointer()); // CHECK-NEXT: }
apache-2.0
fe63d7485c2d267c6d9123f0320afb63
42.209877
231
0.699905
3.681627
false
false
false
false
prolificinteractive/Marker
Example/Marker-Example-iOS/ViewController.swift
1
3437
// // ViewController.swift // Marker // // Created by Htin Linn on 05/04/2016. // Copyright © 2016 Prolific Interactive. All rights reserved. // import Marker import UIKit internal final class ViewController: UIViewController { // MARK: - Override properties override var prefersStatusBarHidden: Bool { return true } // MARK: - Instance properties var theme: AppTheme! // MARK: - Private properties @IBOutlet private weak var label: UILabel! @IBOutlet private weak var textField: UITextField! @IBOutlet private weak var textView: UITextView! { didSet { textView.isEditable = false } } private let labelText = "__the life of pablo__\n" + "__the life of pablo__\n" + "**the life of pablo**\n" + "**the life of pablo**\n\n" + "_the life of pablo_\n" + "which / one\n" + "which / one\n" + "~~which / one~~" private let textFieldText = "track list" private let textViewText = "waves\n" + "wolves\n" + "facts\n" + "fade\n" + ".\n" + "#.#\n" + "^.^\n" // MARK: - Init/Deinit deinit { NotificationCenter.default.removeObserver(self) } // MARK: - Override functions override func viewDidLoad() { super.viewDidLoad() updateViews() registerForNotifications() } override func prepare(for segue: UIStoryboardSegue, sender: Any?) { if let navigationController = segue.destination as? UINavigationController, let themeSettingsViewController = navigationController.viewControllers.first as? ThemeSettingsViewController, segue.identifier == "ThemeSettingsSegue" { themeSettingsViewController.theme = theme } } // MARK: - Private functions private func registerForNotifications() { NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateViews), name: UIContentSizeCategory.didChangeNotification, object: nil) NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateViews), name: Notification.Name(rawValue: AppTheme.Constants.fontThemeDidChangeNotification), object: nil) } @objc private func updateViews() { let fontTheme = theme.fontTheme label.setMarkdownText(labelText, using: fontTheme.headlineTextStyle) textField.setText(textFieldText, using: fontTheme.titleTextStyle) var fadedTextStyleOne = fontTheme.bodyTextStyle fadedTextStyleOne.textColor = UIColor.black.withAlphaComponent(0.5) var fadedTextStyleTwo = fontTheme.bodyTextStyle fadedTextStyleTwo.textColor = UIColor.black.withAlphaComponent(0.2) textView.setText(textViewText, using: fontTheme.bodyTextStyle, customMarkup: [ "#": fadedTextStyleOne, "^": fadedTextStyleTwo ] ) } }
mit
c8f68af39e1007de372aa4e325236a8f
31.11215
132
0.557916
5.198185
false
false
false
false