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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
HongliYu/firefox-ios
|
Client/Frontend/Settings/SettingsTableViewController.swift
|
1
|
28639
|
/* 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 UIKit
struct SettingsUX {
static let TableViewHeaderFooterHeight = CGFloat(44)
}
extension UILabel {
// iOS bug: NSAttributed string color is ignored without setting font/color to nil
func assign(attributed: NSAttributedString?) {
guard let attributed = attributed else { return }
let attribs = attributed.attributes(at: 0, effectiveRange: nil)
if attribs[NSAttributedStringKey.foregroundColor] == nil {
// If the text color attribute isn't set, use the table view row text color.
textColor = UIColor.theme.tableView.rowText
} else {
textColor = nil
}
attributedText = attributed
}
}
// A base setting class that shows a title. You probably want to subclass this, not use it directly.
class Setting: NSObject {
fileprivate var _title: NSAttributedString?
fileprivate var _footerTitle: NSAttributedString?
fileprivate var _cellHeight: CGFloat?
fileprivate var _image: UIImage?
weak var delegate: SettingsDelegate?
// The url the SettingsContentViewController will show, e.g. Licenses and Privacy Policy.
var url: URL? { return nil }
// The title shown on the pref.
var title: NSAttributedString? { return _title }
var footerTitle: NSAttributedString? { return _footerTitle }
var cellHeight: CGFloat? { return _cellHeight}
fileprivate(set) var accessibilityIdentifier: String?
// An optional second line of text shown on the pref.
var status: NSAttributedString? { return nil }
// Whether or not to show this pref.
var hidden: Bool { return false }
var style: UITableViewCellStyle { return .subtitle }
var accessoryType: UITableViewCellAccessoryType { return .none }
var textAlignment: NSTextAlignment { return .natural }
var image: UIImage? { return _image }
fileprivate(set) var enabled: Bool = true
// Called when the cell is setup. Call if you need the default behaviour.
func onConfigureCell(_ cell: UITableViewCell) {
cell.detailTextLabel?.assign(attributed: status)
cell.detailTextLabel?.attributedText = status
cell.detailTextLabel?.numberOfLines = 0
cell.textLabel?.assign(attributed: title)
cell.textLabel?.textAlignment = textAlignment
cell.textLabel?.numberOfLines = 1
cell.textLabel?.lineBreakMode = .byTruncatingTail
cell.accessoryType = accessoryType
cell.accessoryView = nil
cell.selectionStyle = enabled ? .default : .none
cell.accessibilityIdentifier = accessibilityIdentifier
cell.imageView?.image = _image
if let title = title?.string {
if let detailText = cell.detailTextLabel?.text {
cell.accessibilityLabel = "\(title), \(detailText)"
} else if let status = status?.string {
cell.accessibilityLabel = "\(title), \(status)"
} else {
cell.accessibilityLabel = title
}
}
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.indentationWidth = 0
cell.layoutMargins = .zero
// So that the separator line goes all the way to the left edge.
cell.separatorInset = .zero
if let cell = cell as? ThemedTableViewCell {
cell.applyTheme()
}
}
// Called when the pref is tapped.
func onClick(_ navigationController: UINavigationController?) { return }
// Helper method to set up and push a SettingsContentViewController
func setUpAndPushSettingsContentViewController(_ navigationController: UINavigationController?) {
if let url = self.url {
let viewController = SettingsContentViewController()
viewController.settingsTitle = self.title
viewController.url = url
navigationController?.pushViewController(viewController, animated: true)
}
}
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, delegate: SettingsDelegate? = nil, enabled: Bool? = nil) {
self._title = title
self._footerTitle = footerTitle
self._cellHeight = cellHeight
self.delegate = delegate
self.enabled = enabled ?? true
}
}
// A setting in the sections panel. Contains a sublist of Settings
class SettingSection: Setting {
fileprivate let children: [Setting]
init(title: NSAttributedString? = nil, footerTitle: NSAttributedString? = nil, cellHeight: CGFloat? = nil, children: [Setting]) {
self.children = children
super.init(title: title, footerTitle: footerTitle, cellHeight: cellHeight)
}
var count: Int {
var count = 0
for setting in children where !setting.hidden {
count += 1
}
return count
}
subscript(val: Int) -> Setting? {
var i = 0
for setting in children where !setting.hidden {
if i == val {
return setting
}
i += 1
}
return nil
}
}
private class PaddedSwitch: UIView {
fileprivate static let Padding: CGFloat = 8
init(switchView: UISwitch) {
super.init(frame: .zero)
addSubview(switchView)
frame.size = CGSize(width: switchView.frame.width + PaddedSwitch.Padding, height: switchView.frame.height)
switchView.frame.origin = CGPoint(x: PaddedSwitch.Padding, y: 0)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
// A helper class for settings with a UISwitch.
// Takes and optional settingsDidChange callback and status text.
class BoolSetting: Setting {
let prefKey: String? // Sometimes a subclass will manage its own pref setting. In that case the prefkey will be nil
fileprivate let prefs: Prefs
fileprivate let defaultValue: Bool
fileprivate let settingDidChange: ((Bool) -> Void)?
fileprivate let statusText: NSAttributedString?
init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, attributedTitleText: NSAttributedString, attributedStatusText: NSAttributedString? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
self.prefs = prefs
self.prefKey = prefKey
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.statusText = attributedStatusText
super.init(title: attributedTitleText)
}
convenience init(prefs: Prefs, prefKey: String? = nil, defaultValue: Bool, titleText: String, statusText: String? = nil, settingDidChange: ((Bool) -> Void)? = nil) {
var statusTextAttributedString: NSAttributedString?
if let statusTextString = statusText {
statusTextAttributedString = NSAttributedString(string: statusTextString, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.headerTextLight])
}
self.init(prefs: prefs, prefKey: prefKey, defaultValue: defaultValue, attributedTitleText: NSAttributedString(string: titleText, attributes: [NSAttributedStringKey.foregroundColor: UIColor.theme.tableView.rowText]), attributedStatusText: statusTextAttributedString, settingDidChange: settingDidChange)
}
override var status: NSAttributedString? {
return statusText
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
let control = UISwitchThemed()
control.onTintColor = UIConstants.SystemBlueColor
control.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
control.accessibilityIdentifier = prefKey
displayBool(control)
if let title = title {
if let status = status {
control.accessibilityLabel = "\(title.string), \(status.string)"
} else {
control.accessibilityLabel = title.string
}
cell.accessibilityLabel = nil
}
cell.accessoryView = PaddedSwitch(switchView: control)
cell.selectionStyle = .none
}
@objc func switchValueChanged(_ control: UISwitch) {
writeBool(control)
settingDidChange?(control.isOn)
UnifiedTelemetry.recordEvent(category: .action, method: .change, object: .setting, value: self.prefKey, extras: ["to": control.isOn])
}
// These methods allow a subclass to control how the pref is saved
func displayBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
control.isOn = prefs.boolForKey(key) ?? defaultValue
}
func writeBool(_ control: UISwitch) {
guard let key = prefKey else {
return
}
prefs.setBool(control.isOn, forKey: key)
}
}
class PrefPersister: SettingValuePersister {
fileprivate let prefs: Prefs
let prefKey: String
init(prefs: Prefs, prefKey: String) {
self.prefs = prefs
self.prefKey = prefKey
}
func readPersistedValue() -> String? {
return prefs.stringForKey(prefKey)
}
func writePersistedValue(value: String?) {
if let value = value {
prefs.setString(value, forKey: prefKey)
} else {
prefs.removeObjectForKey(prefKey)
}
}
}
class StringPrefSetting: StringSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
super.init(defaultValue: defaultValue, placeholder: placeholder, accessibilityIdentifier: accessibilityIdentifier, persister: PrefPersister(prefs: prefs, prefKey: prefKey), settingIsValid: isValueValid, settingDidChange: settingDidChange)
}
}
class WebPageSetting: StringPrefSetting {
init(prefs: Prefs, prefKey: String, defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, settingDidChange: ((String?) -> Void)? = nil) {
super.init(prefs: prefs,
prefKey: prefKey,
defaultValue: defaultValue,
placeholder: placeholder,
accessibilityIdentifier: accessibilityIdentifier,
settingIsValid: WebPageSetting.isURLOrEmpty,
settingDidChange: settingDidChange)
textField.keyboardType = .URL
textField.autocapitalizationType = .none
textField.autocorrectionType = .no
}
override func prepareValidValue(userInput value: String?) -> String? {
guard let value = value else {
return nil
}
return URIFixup.getURL(value)?.absoluteString
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = .checkmark
textField.textAlignment = .left
}
static func isURLOrEmpty(_ string: String?) -> Bool {
guard let string = string, !string.isEmpty else {
return true
}
return URL(string: string)?.isWebPage() ?? false
}
}
protocol SettingValuePersister {
func readPersistedValue() -> String?
func writePersistedValue(value: String?)
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional settingIsValid and settingDidChange callback
/// If settingIsValid returns false, the Setting will not change and the text remains red.
class StringSetting: Setting, UITextFieldDelegate {
var Padding: CGFloat = 15
fileprivate let defaultValue: String?
fileprivate let placeholder: String
fileprivate let settingDidChange: ((String?) -> Void)?
fileprivate let settingIsValid: ((String?) -> Bool)?
fileprivate let persister: SettingValuePersister
let textField = UITextField()
init(defaultValue: String? = nil, placeholder: String, accessibilityIdentifier: String, persister: SettingValuePersister, settingIsValid isValueValid: ((String?) -> Bool)? = nil, settingDidChange: ((String?) -> Void)? = nil) {
self.defaultValue = defaultValue
self.settingDidChange = settingDidChange
self.settingIsValid = isValueValid
self.placeholder = placeholder
self.persister = persister
super.init()
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if let id = accessibilityIdentifier {
textField.accessibilityIdentifier = id + "TextField"
}
if let placeholderColor = UIColor.theme.general.settingsTextPlaceholder {
textField.attributedPlaceholder = NSAttributedString(string: placeholder, attributes: [NSAttributedStringKey.foregroundColor: placeholderColor])
} else {
textField.placeholder = placeholder
}
cell.tintColor = self.persister.readPersistedValue() != nil ? UIColor.theme.tableView.rowActionAccessory : UIColor.clear
textField.textAlignment = .center
textField.delegate = self
textField.tintColor = UIColor.theme.tableView.rowActionAccessory
textField.addTarget(self, action: #selector(textFieldDidChange), for: .editingChanged)
cell.isUserInteractionEnabled = true
cell.accessibilityTraits = UIAccessibilityTraitNone
cell.contentView.addSubview(textField)
textField.snp.makeConstraints { make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
}
textField.text = self.persister.readPersistedValue() ?? defaultValue
textFieldDidChange(textField)
}
override func onClick(_ navigationController: UINavigationController?) {
textField.becomeFirstResponder()
}
fileprivate func isValid(_ value: String?) -> Bool {
guard let test = settingIsValid else {
return true
}
return test(prepareValidValue(userInput: value))
}
/// This gives subclasses an opportunity to treat the user input string
/// before it is saved or tested.
/// Default implementation does nothing.
func prepareValidValue(userInput value: String?) -> String? {
return value
}
@objc func textFieldDidChange(_ textField: UITextField) {
let color = isValid(textField.text) ? UIColor.theme.tableView.rowText : UIColor.theme.general.destructiveRed
textField.textColor = color
}
@objc func textFieldShouldReturn(_ textField: UITextField) -> Bool {
textField.resignFirstResponder()
return isValid(textField.text)
}
@objc func textFieldDidEndEditing(_ textField: UITextField) {
let text = textField.text
if !isValid(text) {
return
}
self.persister.writePersistedValue(value: prepareValidValue(userInput: text))
// Call settingDidChange with text or nil.
settingDidChange?(text)
}
}
class CheckmarkSetting: Setting {
let onChanged: () -> Void
let isEnabled: () -> Bool
private let subtitle: NSAttributedString?
override var status: NSAttributedString? {
return subtitle
}
init(title: NSAttributedString, subtitle: NSAttributedString?, accessibilityIdentifier: String? = nil, isEnabled: @escaping () -> Bool, onChanged: @escaping () -> Void) {
self.subtitle = subtitle
self.onChanged = onChanged
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
cell.accessoryType = .checkmark
cell.tintColor = isEnabled() ? UIColor.theme.tableView.rowActionAccessory : UIColor.clear
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if !isEnabled() {
onChanged()
}
}
}
/// A helper class for a setting backed by a UITextField.
/// This takes an optional isEnabled and mandatory onClick callback
/// isEnabled is called on each tableview.reloadData. If it returns
/// false then the 'button' appears disabled.
class ButtonSetting: Setting {
var Padding: CGFloat = 8
let onButtonClick: (UINavigationController?) -> Void
let destructive: Bool
let isEnabled: (() -> Bool)?
init(title: NSAttributedString?, destructive: Bool = false, accessibilityIdentifier: String, isEnabled: (() -> Bool)? = nil, onClick: @escaping (UINavigationController?) -> Void) {
self.onButtonClick = onClick
self.destructive = destructive
self.isEnabled = isEnabled
super.init(title: title)
self.accessibilityIdentifier = accessibilityIdentifier
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if isEnabled?() ?? true {
cell.textLabel?.textColor = destructive ? UIColor.theme.general.destructiveRed : UIColor.theme.general.highlightBlue
} else {
cell.textLabel?.textColor = UIColor.theme.tableView.disabledRowText
}
cell.textLabel?.snp.makeConstraints({ make in
make.height.equalTo(44)
make.trailing.equalTo(cell.contentView).offset(-Padding)
make.leading.equalTo(cell.contentView).offset(Padding)
})
cell.textLabel?.textAlignment = .center
cell.accessibilityTraits = UIAccessibilityTraitButton
cell.selectionStyle = .none
}
override func onClick(_ navigationController: UINavigationController?) {
// Force editing to end for any focused text fields so they can finish up validation first.
navigationController?.view.endEditing(true)
if isEnabled?() ?? true {
onButtonClick(navigationController)
}
}
}
// A helper class for prefs that deal with sync. Handles reloading the tableView data if changes to
// the fxAccount happen.
class AccountSetting: Setting, FxAContentViewControllerDelegate {
unowned var settings: SettingsTableViewController
var profile: Profile {
return settings.profile
}
override var title: NSAttributedString? { return nil }
init(settings: SettingsTableViewController) {
self.settings = settings
super.init(title: nil)
}
override func onConfigureCell(_ cell: UITableViewCell) {
super.onConfigureCell(cell)
if settings.profile.getAccount() != nil {
cell.selectionStyle = .none
}
}
override var accessoryType: UITableViewCellAccessoryType { return .none }
func contentViewControllerDidSignIn(_ viewController: FxAContentViewController, withFlags flags: FxALoginFlags) {
// This method will get called twice: once when the user signs in, and once
// when the account is verified by email – on this device or another.
// If the user hasn't dismissed the fxa content view controller,
// then we should only do that (thus finishing the sign in/verification process)
// once the account is verified.
// By the time we get to here, we should be syncing or just about to sync in the
// background, most likely from FxALoginHelper.
if flags.verified {
_ = settings.navigationController?.popToRootViewController(animated: true)
// Reload the data to reflect the new Account immediately.
settings.tableView.reloadData()
// And start advancing the Account state in the background as well.
settings.refresh()
}
}
func contentViewControllerDidCancel(_ viewController: FxAContentViewController) {
NSLog("didCancel")
_ = settings.navigationController?.popToRootViewController(animated: true)
}
}
class WithAccountSetting: AccountSetting {
override var hidden: Bool { return !profile.hasAccount() }
}
class WithoutAccountSetting: AccountSetting {
override var hidden: Bool { return profile.hasAccount() }
}
@objc
protocol SettingsDelegate: AnyObject {
func settingsOpenURLInNewTab(_ url: URL)
}
// The base settings view controller.
class SettingsTableViewController: ThemedTableViewController {
typealias SettingsGenerator = (SettingsTableViewController, SettingsDelegate?) -> [SettingSection]
fileprivate let Identifier = "CellIdentifier"
fileprivate let SectionHeaderIdentifier = "SectionHeaderIdentifier"
var settings = [SettingSection]()
weak var settingsDelegate: SettingsDelegate?
var profile: Profile!
var tabManager: TabManager!
var hasSectionSeparatorLine = true
/// Used to calculate cell heights.
fileprivate lazy var dummyToggleCell: UITableViewCell = {
let cell = UITableViewCell(style: .subtitle, reuseIdentifier: "dummyCell")
cell.accessoryView = UISwitchThemed()
return cell
}()
override func viewDidLoad() {
super.viewDidLoad()
tableView.register(UITableViewCell.self, forCellReuseIdentifier: Identifier)
tableView.register(ThemedTableSectionHeaderFooterView.self, forHeaderFooterViewReuseIdentifier: SectionHeaderIdentifier)
tableView.tableFooterView = UIView(frame: CGRect(width: view.frame.width, height: 30))
tableView.estimatedRowHeight = 44
tableView.estimatedSectionHeaderHeight = 44
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
settings = generateSettings()
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidStartSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(syncDidChangeState), name: .ProfileDidFinishSyncing, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(firefoxAccountDidChange), name: .FirefoxAccountChanged, object: nil)
applyTheme()
}
override func applyTheme() {
settings = generateSettings()
super.applyTheme()
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
refresh()
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
[Notification.Name.ProfileDidStartSyncing, Notification.Name.ProfileDidFinishSyncing, Notification.Name.FirefoxAccountChanged].forEach { name in
NotificationCenter.default.removeObserver(self, name: name, object: nil)
}
}
// Override to provide settings in subclasses
func generateSettings() -> [SettingSection] {
return []
}
@objc fileprivate func syncDidChangeState() {
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
@objc fileprivate func refresh() {
// Through-out, be aware that modifying the control while a refresh is in progress is /not/ supported and will likely crash the app.
if let account = self.profile.getAccount() {
account.advance().upon { state in
DispatchQueue.main.async { () -> Void in
self.tableView.reloadData()
}
}
} else {
self.tableView.reloadData()
}
}
@objc func firefoxAccountDidChange() {
self.tableView.reloadData()
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let section = settings[indexPath.section]
if let setting = section[indexPath.row] {
let cell = ThemedTableViewCell(style: setting.style, reuseIdentifier: nil)
setting.onConfigureCell(cell)
cell.backgroundColor = UIColor.theme.tableView.rowBackground
return cell
}
return super.tableView(tableView, cellForRowAt: indexPath)
}
override func numberOfSections(in tableView: UITableView) -> Int {
return settings.count
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let section = settings[section]
return section.count
}
override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let headerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as? ThemedTableSectionHeaderFooterView else {
return nil
}
let sectionSetting = settings[section]
if let sectionTitle = sectionSetting.title?.string {
headerView.titleLabel.text = sectionTitle.uppercased()
}
// Hide the top border for the top section to avoid having a double line at the top
if section == 0 || !hasSectionSeparatorLine {
headerView.showTopBorder = false
} else {
headerView.showTopBorder = true
}
headerView.applyTheme()
return headerView
}
override func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
let sectionSetting = settings[section]
guard let sectionFooter = sectionSetting.footerTitle?.string,
let footerView = tableView.dequeueReusableHeaderFooterView(withIdentifier: SectionHeaderIdentifier) as? ThemedTableSectionHeaderFooterView else {
return nil
}
footerView.titleLabel.text = sectionFooter
footerView.titleAlignment = .top
footerView.showBottomBorder = false
footerView.applyTheme()
return footerView
}
// To hide a footer dynamically requires returning nil from viewForFooterInSection
// and setting the height to zero.
// However, we also want the height dynamically calculated, there is a magic constant
// for that: `UITableViewAutomaticDimension`.
override func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let sectionSetting = settings[section]
if let _ = sectionSetting.footerTitle?.string {
return UITableViewAutomaticDimension
}
return 0
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let section = settings[indexPath.section]
// Workaround for calculating the height of default UITableViewCell cells with a subtitle under
// the title text label.
if let setting = section[indexPath.row], setting is BoolSetting && setting.status != nil {
return calculateStatusCellHeightForSetting(setting)
}
if let setting = section[indexPath.row], let height = setting.cellHeight {
return height
}
return UITableViewAutomaticDimension
}
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let section = settings[indexPath.section]
if let setting = section[indexPath.row], setting.enabled {
setting.onClick(navigationController)
}
}
fileprivate func calculateStatusCellHeightForSetting(_ setting: Setting) -> CGFloat {
dummyToggleCell.layoutSubviews()
let topBottomMargin: CGFloat = 10
let width = dummyToggleCell.contentView.frame.width - 2 * dummyToggleCell.separatorInset.left
return
heightForLabel(dummyToggleCell.textLabel!, width: width, text: setting.title?.string) +
heightForLabel(dummyToggleCell.detailTextLabel!, width: width, text: setting.status?.string) +
2 * topBottomMargin
}
fileprivate func heightForLabel(_ label: UILabel, width: CGFloat, text: String?) -> CGFloat {
guard let text = text else { return 0 }
let size = CGSize(width: width, height: CGFloat.greatestFiniteMagnitude)
let attrs = [NSAttributedStringKey.font: label.font as Any]
let boundingRect = NSString(string: text).boundingRect(with: size,
options: .usesLineFragmentOrigin, attributes: attrs, context: nil)
return boundingRect.height
}
}
|
mpl-2.0
|
be02eba66359f2a5915ae266c7320733
| 37.90625 | 309 | 0.677283 | 5.339362 | false | false | false | false |
hooman/swift
|
test/stdlib/UnsafePointerDiagnostics.swift
|
1
|
32438
|
// RUN: %target-typecheck-verify-swift -enable-invalid-ephemeralness-as-error -disable-objc-interop
// Test availability attributes on UnsafePointer initializers.
// Assume the original source contains no UnsafeRawPointer types.
func unsafePointerConversionAvailability(
mrp: UnsafeMutableRawPointer,
rp: UnsafeRawPointer,
umpv: UnsafeMutablePointer<Void>, // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
upv: UnsafePointer<Void>, // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
umpi: UnsafeMutablePointer<Int>,
upi: UnsafePointer<Int>,
umps: UnsafeMutablePointer<String>,
ups: UnsafePointer<String>) {
let omrp: UnsafeMutableRawPointer? = mrp
let orp: UnsafeRawPointer? = rp
let oumpv: UnsafeMutablePointer<Void> = umpv // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
let oupv: UnsafePointer<Void>? = upv // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
let oumpi: UnsafeMutablePointer<Int>? = umpi
let oupi: UnsafePointer<Int>? = upi
let oumps: UnsafeMutablePointer<String>? = umps
let oups: UnsafePointer<String>? = ups
_ = UnsafeMutableRawPointer(mrp)
_ = UnsafeMutableRawPointer(rp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umpv)
_ = UnsafeMutableRawPointer(upv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umpi)
_ = UnsafeMutableRawPointer(upi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(umps)
_ = UnsafeMutableRawPointer(ups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(omrp)
_ = UnsafeMutableRawPointer(orp) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumpv)
_ = UnsafeMutableRawPointer(oupv) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumpi)
_ = UnsafeMutableRawPointer(oupi) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
_ = UnsafeMutableRawPointer(oumps)
_ = UnsafeMutableRawPointer(oups) // expected-error {{'init(_:)' has been renamed to 'init(mutating:)'}}
// These all correctly pass with no error.
_ = UnsafeRawPointer(mrp)
_ = UnsafeRawPointer(rp)
_ = UnsafeRawPointer(umpv)
_ = UnsafeRawPointer(upv)
_ = UnsafeRawPointer(umpi)
_ = UnsafeRawPointer(upi)
_ = UnsafeRawPointer(umps)
_ = UnsafeRawPointer(ups)
_ = UnsafeRawPointer(omrp)
_ = UnsafeRawPointer(orp)
_ = UnsafeRawPointer(oumpv)
_ = UnsafeRawPointer(oupv)
_ = UnsafeRawPointer(oumpi)
_ = UnsafeRawPointer(oupi)
_ = UnsafeRawPointer(oumps)
_ = UnsafeRawPointer(oups)
_ = UnsafePointer<Int>(upi)
_ = UnsafePointer<Int>(oumpi)
_ = UnsafePointer<Int>(oupi)
_ = UnsafeMutablePointer<Int>(umpi)
_ = UnsafeMutablePointer<Int>(oumpi)
_ = UnsafeMutablePointer<Void>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutablePointer<Void>'}} expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'UnsafeMutablePointer<Void>'}} expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umpv) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umpi) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafeMutablePointer<Void>(umps) // expected-warning {{UnsafeMutablePointer<Void> has been replaced by UnsafeMutableRawPointer}}
_ = UnsafePointer<Void>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafePointer<Void>'}} expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'UnsafePointer<Void>'}} expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umpv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(upv) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umpi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(upi) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(umps) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafePointer<Void>(ups) // expected-warning {{UnsafePointer<Void> has been replaced by UnsafeRawPointer}}
_ = UnsafeMutablePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutablePointer<Int>'}}
_ = UnsafeMutablePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'UnsafeMutablePointer<Int>'}}
_ = UnsafeMutablePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafeMutablePointer<Int>'}}
_ = UnsafeMutablePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'UnsafeMutablePointer<Int>'}}
_ = UnsafePointer<Int>(rp) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafePointer<Int>'}}
_ = UnsafePointer<Int>(mrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer' to expected argument type 'UnsafePointer<Int>'}}
_ = UnsafePointer<Int>(orp) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafePointer<Int>'}}
_ = UnsafePointer<Int>(omrp) // expected-error {{cannot convert value of type 'UnsafeMutableRawPointer?' to expected argument type 'UnsafePointer<Int>'}}
_ = UnsafePointer<Int>(ups) // expected-error {{cannot convert value of type 'UnsafePointer<String>' to expected argument type 'UnsafePointer<Int>'}}
// expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}}
_ = UnsafeMutablePointer<Int>(umps) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<String>' to expected argument type 'UnsafeMutablePointer<Int>'}}
// expected-note@-1 {{arguments to generic parameter 'Pointee' ('String' and 'Int') are expected to be equal}}
_ = UnsafePointer<String>(upi) // expected-error {{cannot convert value of type 'UnsafePointer<Int>' to expected argument type 'UnsafePointer<String>'}}
// expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}}
_ = UnsafeMutablePointer<String>(umpi) // expected-error {{cannot convert value of type 'UnsafeMutablePointer<Int>' to expected argument type 'UnsafeMutablePointer<String>'}}
// expected-note@-1 {{arguments to generic parameter 'Pointee' ('Int' and 'String') are expected to be equal}}
}
func unsafeRawBufferPointerConversions(
mrp: UnsafeMutableRawPointer,
rp: UnsafeRawPointer,
mrbp: UnsafeMutableRawBufferPointer,
rbp: UnsafeRawBufferPointer,
mbpi: UnsafeMutableBufferPointer<Int>,
bpi: UnsafeBufferPointer<Int>) {
let omrp: UnsafeMutableRawPointer? = mrp
let orp: UnsafeRawPointer? = rp
_ = UnsafeMutableRawBufferPointer(start: mrp, count: 1)
_ = UnsafeRawBufferPointer(start: mrp, count: 1)
_ = UnsafeMutableRawBufferPointer(start: rp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer' to expected argument type 'UnsafeMutableRawPointer?'}}
_ = UnsafeRawBufferPointer(start: rp, count: 1)
_ = UnsafeMutableRawBufferPointer(mrbp)
_ = UnsafeRawBufferPointer(mrbp)
_ = UnsafeMutableRawBufferPointer(rbp) // expected-error {{missing argument label 'mutating:' in call}}
_ = UnsafeRawBufferPointer(rbp)
_ = UnsafeMutableRawBufferPointer(mbpi)
_ = UnsafeRawBufferPointer(mbpi)
_ = UnsafeMutableRawBufferPointer(bpi) // expected-error {{cannot convert value of type 'UnsafeBufferPointer<Int>' to expected argument type 'UnsafeMutableRawBufferPointer'}}
_ = UnsafeRawBufferPointer(bpi)
_ = UnsafeMutableRawBufferPointer(start: omrp, count: 1)
_ = UnsafeRawBufferPointer(start: omrp, count: 1)
_ = UnsafeMutableRawBufferPointer(start: orp, count: 1) // expected-error {{cannot convert value of type 'UnsafeRawPointer?' to expected argument type 'UnsafeMutableRawPointer?'}}
_ = UnsafeRawBufferPointer(start: orp, count: 1)
}
struct SR9800 {
func foo(_: UnsafePointer<CChar>) {}
func foo(_: UnsafePointer<UInt8>) {}
func ambiguityTest(buf: UnsafeMutablePointer<CChar>) {
foo(UnsafePointer(buf)) // this call should be unambiguoius
}
}
// Test that we get a custom diagnostic for an ephemeral conversion to non-ephemeral param for an Unsafe[Mutable][Raw][Buffer]Pointer init.
func unsafePointerInitEphemeralConversions() {
class C {}
var foo = 0
var str = ""
var arr = [0]
var optionalArr: [Int]? = [0]
var c: C?
_ = UnsafePointer(&foo) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer(&foo + 1) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to '+'}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to '+'}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer.init(&foo) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer<Int8>("") // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer<Int8>.init("") // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer<Int8>(str) // expected-error {{initialization of 'UnsafePointer<Int8>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafePointer([0]) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafePointer(arr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafePointer(&arr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafePointer(optionalArr) // expected-error {{initialization of 'UnsafePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(_:)'}}
_ = UnsafeMutablePointer(&foo) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutablePointer(&arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutablePointer(&arr + 2) // expected-error {{cannot use inout expression here; argument #1 must be a pointer that outlives the call to '+'}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>' produces a pointer valid only for the duration of the call to '+'}}
// expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutablePointer(mutating: &foo) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutablePointer<Int8>(mutating: "") // expected-error {{initialization of 'UnsafeMutablePointer<Int8>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutablePointer<Int8>(mutating: str) // expected-error {{initialization of 'UnsafeMutablePointer<Int8>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutablePointer(mutating: [0]) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutablePointer(mutating: arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutablePointer(mutating: &arr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutablePointer(mutating: optionalArr) // expected-error {{initialization of 'UnsafeMutablePointer<Int>' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
_ = UnsafeRawPointer(&foo) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawPointer(str) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeRawPointer(arr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawPointer(&arr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawPointer(optionalArr) // expected-error {{initialization of 'UnsafeRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(_:)'}}
_ = UnsafeMutableRawPointer(&foo) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(&arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(mutating: &foo) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(mutating: str) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(mutating: arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(mutating: &arr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawPointer(mutating: optionalArr) // expected-error {{initialization of 'UnsafeMutableRawPointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(mutating:)}}
_ = UnsafeBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeBufferPointer.init(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use 'withUnsafePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeBufferPointer<Int8>(start: str, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int8>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeBufferPointer<Int8>.init(start: str, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int8>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafePointer<Int8>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeBufferPointer(start: arr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeBufferPointer(start: optionalArr, count: 0) // expected-error {{initialization of 'UnsafeBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
_ = UnsafeMutableBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeMutableBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutablePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use 'withUnsafeMutablePointer' in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeMutableBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeMutableBufferPointer<Int>' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutablePointer<Int>?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeMutableBufferPointer' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use 'withUnsafeBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawBufferPointer(start: str, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
_ = UnsafeRawBufferPointer(start: arr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeRawBufferPointer(start: optionalArr, count: 0) // expected-error {{initialization of 'UnsafeRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]?' to 'UnsafeRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
_ = UnsafeMutableRawBufferPointer(start: &foo, count: 0) // expected-error {{initialization of 'UnsafeMutableRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from 'Int' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use 'withUnsafeMutableBytes' in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = UnsafeMutableRawBufferPointer(start: &arr, count: 0) // expected-error {{initialization of 'UnsafeMutableRawBufferPointer' results in a dangling buffer pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeMutableRawPointer?' produces a pointer valid only for the duration of the call to 'init(start:count:)'}}
// expected-note@-2 {{use the 'withUnsafeMutableBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
// FIXME: This is currently ambiguous.
_ = OpaquePointer(&foo) // expected-error {{no exact matches in call to initializer}}
// FIXME: This is currently ambiguous.
_ = OpaquePointer(&arr) // expected-error {{no exact matches in call to initializer}}
_ = OpaquePointer(arr) // expected-error {{initialization of 'OpaquePointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from '[Int]' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withUnsafeBytes' method on Array in order to explicitly convert argument to buffer pointer valid for a defined scope}}
_ = OpaquePointer(str) // expected-error {{initialization of 'OpaquePointer' results in a dangling pointer}}
// expected-note@-1 {{implicit argument conversion from 'String' to 'UnsafeRawPointer' produces a pointer valid only for the duration of the call to 'init(_:)'}}
// expected-note@-2 {{use the 'withCString' method on String in order to explicitly convert argument to pointer valid for a defined scope}}
}
var global = 0
// Test that we allow non-ephemeral conversions, such as inout-to-pointer for globals.
func unsafePointerInitNonEphemeralConversions() {
_ = UnsafePointer(&global)
_ = UnsafeMutablePointer(&global)
_ = UnsafeRawPointer(&global)
_ = UnsafeMutableRawPointer(&global)
_ = UnsafeBufferPointer(start: &global, count: 0)
_ = UnsafeMutableBufferPointer(start: &global, count: 0)
_ = UnsafeRawBufferPointer(start: &global, count: 0)
_ = UnsafeMutableRawBufferPointer(start: &global, count: 0)
// FIXME: This is currently ambiguous.
_ = OpaquePointer(&global) // expected-error {{ambiguous use of 'init(_:)'}}
}
|
apache-2.0
|
2783a87441ee74b5ca46f63cd0c96b48
| 86.67027 | 262 | 0.749214 | 4.665324 | false | false | false | false |
jer-k/JKVideoUploader-Swift
|
JKVideoUploader-Swift/AppDelegate.swift
|
1
|
6211
|
//
// AppDelegate.swift
// JKVideoUploader-Swift
//
// Created by Jeremy Kreutzbender on 8/20/14.
// Copyright (c) 2014 Jeremy Kreutzbender. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(application: UIApplication!, didFinishLaunchingWithOptions launchOptions: NSDictionary!) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication!) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication!) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication!) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication!) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication!) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "JK.JKVideoUploader_Swift" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1] as NSURL
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("JKVideoUploader_Swift", withExtension: "momd")
return NSManagedObjectModel(contentsOfURL: modelURL)
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("JKVideoUploader_Swift.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError.errorWithDomain("YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext? = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
if coordinator == nil {
return nil
}
var managedObjectContext = NSManagedObjectContext()
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
}
|
mit
|
821886a472d8f76ed7d57da91e0101eb
| 54.954955 | 290 | 0.715344 | 5.788444 | false | false | false | false |
Sundog-Interactive/DF15-Wearables-On-Salesforce
|
iOS/Lead_Nurture/Lead_Nurture/Lead_Nurture/Classes/LeadHandler.swift
|
1
|
1569
|
//
// LeadHandler.swift
// Lead_Nurture
//
// Created by Craig Isakson on 8/24/15.
// Copyright (c) 2015 Sundog Interactive. All rights reserved.
//
import Foundation
class LeadHandler: NSObject, SFRestDelegate {
var watchInfo : WatchInfo?
func assignCampaign() {
var sharedInstance = SFRestAPI.sharedInstance();
var userDictionary = watchInfo?.userInfo as! Dictionary<String, String>;
var leadId:String! = userDictionary["leadId"];
var campaignId:String! = userDictionary["campaignId"];
var fields:Dictionary<String, String> = ["LeadId": leadId, "CampaignId": campaignId];
var request = sharedInstance.requestForCreateWithObjectType("CampaignMember", fields: fields);
sharedInstance.send(request as SFRestRequest, delegate: self);
}
func request(request: SFRestRequest?, didLoadResponse jsonResponse: AnyObject) {
var success = jsonResponse.objectForKey("success") as! Bool
//send the block back to the watch
if let watchInfo = watchInfo {
let stuff = ["success" : success]
watchInfo.replyBlock(stuff)
}
}
func request(request: SFRestRequest?, didFailLoadWithError error:NSError) {
println("In Error: \(error)")
}
func requestDidCancelLoad(request: SFRestRequest) {
println("In requestDidCancelLoad \(request)")
}
func requestDidTimeout(request: SFRestRequest) {
println("In requestDidTimeout \(request)")
}
}
|
apache-2.0
|
0756c4ca588bcab5fe74b25f2496579c
| 29.764706 | 102 | 0.644997 | 4.601173 | false | false | false | false |
jacobwhite/firefox-ios
|
Client/Frontend/Browser/Authenticator.swift
|
1
|
8190
|
/* 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 Shared
import Storage
import Deferred
private let CancelButtonTitle = NSLocalizedString("Cancel", comment: "Label for Cancel button")
private let LogInButtonTitle = NSLocalizedString("Log in", comment: "Authentication prompt log in button")
private let log = Logger.browserLogger
class Authenticator {
fileprivate static let MaxAuthenticationAttempts = 3
static func handleAuthRequest(_ viewController: UIViewController, challenge: URLAuthenticationChallenge, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
// If there have already been too many login attempts, we'll just fail.
if challenge.previousFailureCount >= Authenticator.MaxAuthenticationAttempts {
return deferMaybe(LoginDataError(description: "Too many attempts to open site"))
}
var credential = challenge.proposedCredential
// If we were passed an initial set of credentials from iOS, try and use them.
if let proposed = credential {
if !(proposed.user?.isEmpty ?? true) {
if challenge.previousFailureCount == 0 {
return deferMaybe(Login.createWithCredential(credential!, protectionSpace: challenge.protectionSpace))
}
} else {
credential = nil
}
}
// If we have some credentials, we'll show a prompt with them.
if let credential = credential {
return promptForUsernamePassword(viewController, credentials: credential, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
// Otherwise, try to look them up and show the prompt.
if let loginsHelper = loginsHelper {
return findMatchingCredentialsForChallenge(challenge, fromLoginsProvider: loginsHelper.logins).bindQueue(.main) { result in
guard let credentials = result.successValue else {
return deferMaybe(result.failureValue ?? LoginDataError(description: "Unknown error when finding credentials"))
}
return self.promptForUsernamePassword(viewController, credentials: credentials, protectionSpace: challenge.protectionSpace, loginsHelper: loginsHelper)
}
}
// No credentials, so show an empty prompt.
return self.promptForUsernamePassword(viewController, credentials: nil, protectionSpace: challenge.protectionSpace, loginsHelper: nil)
}
static func findMatchingCredentialsForChallenge(_ challenge: URLAuthenticationChallenge, fromLoginsProvider loginsProvider: BrowserLogins) -> Deferred<Maybe<URLCredential?>> {
return loginsProvider.getLoginsForProtectionSpace(challenge.protectionSpace) >>== { cursor in
guard cursor.count >= 1 else {
return deferMaybe(nil)
}
let logins = cursor.asArray()
var credentials: URLCredential? = nil
// It is possible that we might have duplicate entries since we match against host and scheme://host.
// This is a side effect of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
if logins.count > 1 {
credentials = (logins.find { login in
(login.protectionSpace.`protocol` == challenge.protectionSpace.`protocol`) && !login.hasMalformedHostname
})?.credentials
let malformedGUIDs: [GUID] = logins.compactMap { login in
if login.hasMalformedHostname {
return login.guid
}
return nil
}
loginsProvider.removeLoginsWithGUIDs(malformedGUIDs).upon { log.debug("Removed malformed logins. Success :\($0.isSuccess)") }
}
// Found a single entry but the schemes don't match. This is a result of a schemeless entry that we
// saved in a previous iteration of the app so we need to migrate it. We only care about the
// the username/password so we can rewrite the scheme to be correct.
else if logins.count == 1 && logins[0].protectionSpace.`protocol` != challenge.protectionSpace.`protocol` {
let login = logins[0]
credentials = login.credentials
let new = Login(credential: login.credentials, protectionSpace: challenge.protectionSpace)
return loginsProvider.updateLoginByGUID(login.guid, new: new, significant: true)
>>> { deferMaybe(credentials) }
}
// Found a single entry that matches the scheme and host - good to go.
else {
credentials = logins[0].credentials
}
return deferMaybe(credentials)
}
}
fileprivate static func promptForUsernamePassword(_ viewController: UIViewController, credentials: URLCredential?, protectionSpace: URLProtectionSpace, loginsHelper: LoginsHelper?) -> Deferred<Maybe<LoginData>> {
if protectionSpace.host.isEmpty {
print("Unable to show a password prompt without a hostname")
return deferMaybe(LoginDataError(description: "Unable to show a password prompt without a hostname"))
}
let deferred = Deferred<Maybe<LoginData>>()
let alert: UIAlertController
let title = NSLocalizedString("Authentication required", comment: "Authentication prompt title")
if !(protectionSpace.realm?.isEmpty ?? true) {
let msg = NSLocalizedString("A username and password are being requested by %@. The site says: %@", comment: "Authentication prompt message with a realm. First parameter is the hostname. Second is the realm string")
let formatted = NSString(format: msg as NSString, protectionSpace.host, protectionSpace.realm ?? "") as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: .alert)
} else {
let msg = NSLocalizedString("A username and password are being requested by %@.", comment: "Authentication prompt message with no realm. Parameter is the hostname of the site")
let formatted = NSString(format: msg as NSString, protectionSpace.host) as String
alert = UIAlertController(title: title, message: formatted, preferredStyle: .alert)
}
// Add a button to log in.
let action = UIAlertAction(title: LogInButtonTitle,
style: .default) { (action) -> Void in
guard let user = alert.textFields?[0].text, let pass = alert.textFields?[1].text else { deferred.fill(Maybe(failure: LoginDataError(description: "Username and Password required"))); return }
let login = Login.createWithCredential(URLCredential(user: user, password: pass, persistence: .forSession), protectionSpace: protectionSpace)
deferred.fill(Maybe(success: login))
loginsHelper?.setCredentials(login)
}
alert.addAction(action)
// Add a cancel button.
let cancel = UIAlertAction(title: CancelButtonTitle, style: .cancel) { (action) -> Void in
deferred.fill(Maybe(failure: LoginDataError(description: "Save password cancelled")))
}
alert.addAction(cancel)
// Add a username textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Username", comment: "Username textbox in Authentication prompt")
textfield.text = credentials?.user
}
// Add a password textfield.
alert.addTextField { (textfield) -> Void in
textfield.placeholder = NSLocalizedString("Password", comment: "Password textbox in Authentication prompt")
textfield.isSecureTextEntry = true
textfield.text = credentials?.password
}
viewController.present(alert, animated: true) { () -> Void in }
return deferred
}
}
|
mpl-2.0
|
722af015201c938021531bf8f9c1fb8b
| 52.529412 | 227 | 0.658242 | 5.500336 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
Chula Expo 2017/Chula Expo 2017/First_home/HeaderTableViewCell.swift
|
1
|
1361
|
//
// HeaderTableViewCell.swift
// Chula Expo 2017
//
// Created by NOT on 1/24/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import UIKit
class HeaderTableViewCell: UITableViewCell {
@IBOutlet weak var engLabel: UILabel!
@IBOutlet weak var thaLabel: UILabel!
@IBOutlet weak var icon: UIImageView!
@IBOutlet weak var background: UIView!
var title1: String?{
didSet{
engLabel.text = title1
}
}
var title2: String?{
didSet{
thaLabel.text = title2
}
}
var iconImage: String?{
didSet{
icon.image = UIImage(named: iconImage ?? "heartIcon")
}
}
private func updateUI(){
}
}
extension UIView{
func cardStyle(background: UIView){
background.layer.cornerRadius = 2
background.clipsToBounds = true
// background.clipsToBounds = false
// self.layer.masksToBounds = false
let shadowPath = UIBezierPath(rect: background.bounds)
background.layer.shadowColor = UIColor.darkGray.cgColor
background.layer.shadowOffset = CGSize(width: 0, height: 0)
background.layer.shadowRadius = 1
background.layer.shadowOpacity = 0.2
background.layer.shadowPath = shadowPath.cgPath
}
}
|
mit
|
3c38537069cc9532986abd9e367c2bc6
| 22.859649 | 78 | 0.620588 | 4.429967 | false | false | false | false |
CoderPug/cocoalima.com
|
Sources/App/Controller/podcastController.swift
|
1
|
10668
|
//
// PodcastController.swift
// cocoalima
//
// Created by Jose Torres on 15/1/17.
//
//
import Vapor
import HTTP
import VaporPostgreSQL
// -
final class PodcastController {
var drop = Droplet()
// MARK: -
/// Get current database version. Response will only return if there exists a valid database connection.
func getDBVersion(_ request: Request) throws -> ResponseRepresentable {
if let db = drop.database?.driver as? PostgreSQLDriver {
let version = try db.raw("SELECT version()")
return try JSON(node: version)
} else {
return "No db connection"
}
}
/// Get homepage
func getHome(_ request: Request) throws -> ResponseRepresentable {
var arrayEpisodes: [Episode]?
do {
if let db = drop.database?.driver as? PostgreSQLDriver {
let resultArray = try db.raw("select * from episodes order by id desc limit 5")
arrayEpisodes = resultArray.nodeArray?.flatMap { try? Episode(node: $0) }
} else {
arrayEpisodes = []
}
} catch {
print(error)
arrayEpisodes = []
}
var arrayHosts: [AnyObject]?
arrayHosts = try? Host.all()
let featuredEpisode: Episode?
if arrayEpisodes != nil && arrayEpisodes!.count > 0 {
featuredEpisode = arrayEpisodes?.first
arrayEpisodes?.removeFirst()
} else {
featuredEpisode = nil
}
let arguments: [String: NodeRepresentable]
if featuredEpisode != nil {
arguments = [
"featuredEpisode": try featuredEpisode?.makeNode() ?? EmptyNode,
"episodes": try arrayEpisodes?.makeNode() ?? EmptyNode,
"hosts": try (arrayHosts as? [Host])?.makeNode() ?? EmptyNode
]
} else {
arguments = [
"episodes": try arrayEpisodes?.makeNode() ?? EmptyNode,
"hosts": try (arrayHosts as? [Host])?.makeNode() ?? EmptyNode
]
}
return try drop.view.make("mainswift/mainswift", arguments)
}
/// Get list of available episodes
func getEpisodes(_ request: Request) throws -> ResponseRepresentable {
var arrayEpisodes: [AnyObject]? = []
arrayEpisodes = try? Episode.all()
arrayEpisodes?.sort(by: {
guard let a = $0 as? Episode,
let b = $1 as? Episode else {
return false
}
return (a.id?.int ?? 0) > (b.id?.int ?? 0)
})
var arrayHosts: [AnyObject]? = []
arrayHosts = try? Host.all()
let arguments = [
"episodes": try (arrayEpisodes as? [Episode])?.makeNode() ?? EmptyNode,
"hosts": try (arrayHosts as? [Host])?.makeNode() ?? EmptyNode
]
return try drop.view.make("mainswift/episodes", arguments)
}
/// Get a specific episode with id
func getEpisode(_ episodeId: Int, _ request: Request) throws -> ResponseRepresentable {
var episode: Episode?
episode = try Episode.find(episodeId)
var arrayHosts: [AnyObject]? = []
arrayHosts = try? Host.all()
let arguments: [String: NodeRepresentable]
if episode != nil {
arguments = [
"episode": try episode?.makeNode() ?? EmptyNode,
"hosts": try (arrayHosts as? [Host])?.makeNode() ?? EmptyNode
]
} else {
arguments = [
"hosts": try (arrayHosts as? [Host])?.makeNode() ?? EmptyNode
]
}
return try drop.view.make("mainswift/episode", arguments)
}
// MARK: - RSS
func getRSS(_ request: Request) throws -> ResponseRepresentable {
var arrayEpisodes: [Episode]?
arrayEpisodes = try? Episode.all()
arrayEpisodes?.sort(by: {
return ($0.0.id?.int ?? 0) > ($0.1.id?.int ?? 0)
})
var stringEpisodes = ""
if let arrayEpisodes = arrayEpisodes {
for episode in arrayEpisodes {
stringEpisodes.append( RSSItem(episode).representation() )
}
}
let xml = XML("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n" +
"<rss version=\"2.0\" xmlns:atom=\"http://www.w3.org/2005/Atom/\" xmlns:content=\"http://purl.org/rss/1.0/modules/content/\" xmlns:itunes=\"http://www.itunes.com/dtds/podcast-1.0.dtd\">\n" +
" <channel>\n" +
" <atom:link rel=\"self\" type=\"application/atom+xml\" href=\"http://cocoalima.com/mainswift/rss\" title=\"MP3 Audio\"/>\n" +
" <title>main.swift</title>\n" +
" <generator>http://cocoalima.com/mainswift</generator>\n" +
" <description>Podcast en español con episodios de conversaciones sobre las últimas novedades en el mundo tecnológico de una manera casual y simple. Además de episodios más técnicos sobre las últimas novedades en el desarrollo para las plataformas de Apple.</description>\n" +
" <copyright>© 2016 cocoalima</copyright>\n" +
" <language>es</language>\n" +
" <pubDate>Mon, 05 Dec 2016 05:00:00 -0800</pubDate>\n" +
" <lastBuildDate>Mon, 05 Dec 2016 05:00:00 -0800</lastBuildDate>\n" +
" <link>http://cocoalima.com/mainswift</link>\n" +
" <image>\n" +
" <url>https://s3-us-west-2.amazonaws.com/mainswift/mainswiftlogo1400x1400.png</url>\n" +
" <title>main.swift</title>\n" +
" <link>http://cocoalima.com/mainswift</link>\n" +
" </image>\n" +
" <itunes:author>main.swift</itunes:author>\n" +
" <itunes:image href=\"https://s3-us-west-2.amazonaws.com/mainswift/mainswiftlogo1400x1400.png\"/>\n" +
" <itunes:summary>Podcast en español con episodios de conversaciones sobre las últimas novedades en el mundo tecnológico de una manera casual y simple. Además de episodios más técnicos sobre las últimas novedades en el desarrollo para las plataformas de Apple.</itunes:summary>\n" +
" <itunes:subtitle>Podcast en español sobre novedades en el mundo tecnológico y desarrollo con Swift.</itunes:subtitle>\n" +
" <itunes:explicit>no</itunes:explicit>\n" +
" <itunes:keywords>technology, development, swift, apple, ios, programacion, tecnologia</itunes:keywords>\n" +
" <itunes:owner>\n" +
" <itunes:name>main.swift</itunes:name>\n" +
" <itunes:email>[email protected]</itunes:email>\n" +
" </itunes:owner>\n" +
" <itunes:category text=\"Technology\"/>\n" +
" <itunes:category text=\"Technology\">\n" +
" <itunes:category text=\"Tech News\"/>\n" +
" </itunes:category>\n" +
stringEpisodes +
" </channel>\n" +
"</rss>")
return xml
}
// MARK: - API
func APIGetHosts(_ request: Request) throws -> ResponseRepresentable {
return try JSON(node: Host.all())
}
func APIGetEpisodes(_ request: Request) throws -> ResponseRepresentable {
var tarrayEpisodes: [Episode]?
tarrayEpisodes = try? Episode.all()
guard var arrayEpisodes = tarrayEpisodes else {
throw Abort.badRequest
}
arrayEpisodes.sort(by: { return ($0.id?.int ?? 0) > ($1.id?.int ?? 0) })
return try arrayEpisodes.makeJSON()
}
func APIPostHost(_ request: Request) throws -> ResponseRepresentable {
guard let name = request.data["name"]?.string,
let url = request.data["url"]?.string,
let imageURL = request.data["imageurl"]?.string else {
throw Abort.badRequest
}
var host = Host(name: name, url: url, imageURL: imageURL)
try host.save()
return host
}
func APIPostEpisode(_ request: Request) throws -> ResponseRepresentable {
guard let title = request.data["title"]?.string,
let imageURL = request.data["imageurl"]?.string,
let audioURL = request.data["audiourl"]?.string,
let date = request.data["date"]?.string,
let shortDescription = request.data["shortdescription"]?.string,
let fullDescription = request.data["fulldescription"]?.string,
let duration = request.data["duration"]?.int else {
throw Abort.badRequest
}
var episode = Episode(title: title, shortDescription: shortDescription, fullDescription: fullDescription, imageURL: imageURL, audioURL: audioURL, date: date, duration: duration)
try episode.save()
return episode
}
func APIPutEpisode(_ episodeId: Int, _ request: Request) throws -> ResponseRepresentable {
var tepisode: Episode?
do {
tepisode = try Episode.find(episodeId)
} catch {
print(error)
tepisode = nil
}
guard var episode = tepisode else {
throw Abort.badRequest
}
if let title = request.data["title"]?.string {
episode.title = title
}
if let imageURL = request.data["imageurl"]?.string {
episode.imageURL = imageURL
}
if let audioURL = request.data["audiourl"]?.string {
episode.audioURL = audioURL
}
if let date = request.data["date"]?.string {
episode.date = date
}
if let shortDescription = request.data["shortdescription"]?.string {
episode.shortDescription = shortDescription
}
if let fullDescription = request.data["fulldescription"]?.string {
episode.fullDescription = fullDescription
}
if let duration = request.data["duration"]?.int {
episode.duration = duration
}
try episode.save()
return episode
}
}
|
mit
|
746ecf231f956d6f19769f0c422fc82d
| 34.983108 | 297 | 0.536194 | 4.386738 | false | false | false | false |
jiangboLee/huangpian
|
liubai/AppDelegate.swift
|
1
|
5323
|
//
// AppDelegate.swift
// liubai
//
// Created by 李江波 on 2017/2/25.
// Copyright © 2017年 lijiangbo. All rights reserved.
// 1219224872
// 58d4eac765b6d60c4e00040c 友盟
// 微信 AppID:wx29c9cba28ba18e06 AppSecret: 00ca41160f5cfe04287574220bc0d7c0
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate,UNUserNotificationCenterDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
//友盟推送58d4eac765b6d60c4e00040c
UMessage.start(withAppkey: "58d4eac765b6d60c4e00040c", launchOptions: launchOptions)
// UMessage.start(withAppkey: "58d4eac765b6d60c4e00040c", launchOptions: launchOptions, httpsEnable: true)
UMessage.registerForRemoteNotifications()
//iOS10必须加下面这段代码。
if #available(iOS 10.0, *) {
let center = UNUserNotificationCenter.current()
center.delegate = self
center.requestAuthorization(options: [.alert,.badge,.sound], completionHandler: { (granted, error) in
if granted {
//允许点击
} else {
//点击不允许
}
})
} else {
// Fallback on earlier versions
}
UMessage.setLogEnabled(true)
//友盟统计
UMAnalyticsConfig.sharedInstance().appKey = "58d4eac765b6d60c4e00040c"
UMAnalyticsConfig.sharedInstance().channelId = "App Store"
//版本
let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"]
MobClick.setAppVersion(version as? String ?? "")
MobClick.start(withConfigure: UMAnalyticsConfig.sharedInstance())
UMSocialManager.default().openLog(true)
// 设置友盟appkey
UMSocialManager.default().umSocialAppkey = "58d4eac765b6d60c4e00040c"
configUSharePlatforms()
return true
}
func configUSharePlatforms() {
/* 设置微信的appKey和appSecret */
UMSocialManager.default().setPlaform(.wechatSession, appKey: "wx29c9cba28ba18e06", appSecret: "00ca41160f5cfe04287574220bc0d7c0", redirectURL: "http://www.uupoop.com")
UMSocialManager.default().setPlaform(.QQ, appKey: "1105923615", appSecret: nil, redirectURL: "http://www.jianshu.com/u/3cd8d0f74b3a")
UMSocialManager.default().setPlaform(.sina, appKey: "1497207940", appSecret: "5d72cdca0afb7fc5cae8a0e99b2137be", redirectURL: "http://www.baidu.com")
}
//MARK: 完整的接受通知代码
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
UMessage.didReceiveRemoteNotification(userInfo)
}
//iOS10新增:处理前台收到通知的代理方法
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let useInfo = notification.request.content.userInfo
if (notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
//应用处于前台时的远程推送接受
//关闭U-Push自带的弹出框
UMessage.setAutoAlert(false)
//必须加这句代码
UMessage.didReceiveRemoteNotification(useInfo)
} else {
//应用处于前台时的本地推送接受
}
//当应用处于前台时提示设置,需要哪个可以设置哪一个
completionHandler([.sound, .badge, .alert])
}
//iOS10新增:处理后台点击通知的代理方法
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
let userInfo = response.notification.request.content.userInfo
if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self))! {
//应用处于后台时的远程推送接受
//必须加这句代码
UMessage.didReceiveRemoteNotification(userInfo)
} else {
//应用处于后台时的本地推送接受
}
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let result = UMSocialManager.default().handleOpen(url)
if !result {
}
return result
}
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let result = UMSocialManager.default().handleOpen(url)
if !result {
}
return result
}
func application(_ application: UIApplication, handleOpen url: URL) -> Bool {
let result = UMSocialManager.default().handleOpen(url)
if !result {
}
return result
}
}
|
apache-2.0
|
f5431443589ba61336ad1eae54ac1f44
| 35.865672 | 207 | 0.644534 | 4.42256 | false | false | false | false |
micchyboy1023/Today
|
TodayKit Shared Code/Utilities.swift
|
1
|
1630
|
//
// Utilities.swift
// Today
//
// Created by UetaMasamichi on 2015/12/24.
// Copyright © 2015年 Masamichi Ueta. All rights reserved.
//
import UIKit
public func localize(_ key: String) -> String {
return NSLocalizedString(key, comment: "")
}
extension UserDefaults {
public func clean() {
for key in self.dictionaryRepresentation().keys {
self.removeObject(forKey: key)
}
}
}
extension Date {
public static func numberOfDaysFromDateTime(_ fromDateTime: Date, toDateTime: Date, inTimeZone timeZone: TimeZone? = nil) -> Int {
var calendar = Calendar.current
if let timeZone = timeZone {
calendar.timeZone = timeZone
}
let difference = calendar.dateComponents([.day], from: fromDateTime, to: toDateTime)
return difference.day!
}
}
public enum ColorType {
case red, orange, yellow, green, blue
}
extension UIColor {
public class func applicationColor(type: ColorType) -> UIColor {
switch type {
case .red:
return UIColor(red: 250.0/255.0, green: 17.0/255.0, blue: 79.0/255.0, alpha: 1.0)
case .orange:
return UIColor(red: 255.0/255.0, green: 149.0/255.0, blue: 0.0/255.0, alpha: 1.0)
case .yellow:
return UIColor(red: 255.0/255.0, green: 230.0/255.0, blue: 32.0/255.0, alpha: 1.0)
case .green:
return UIColor(red: 4.0/255.0, green: 222.0/255.0, blue: 113.0/255.0, alpha: 1.0)
case .blue:
return UIColor(red: 32.0/255.0, green: 148.0/255.0, blue: 250.0/255.0, alpha: 1.0)
}
}
}
|
mit
|
67edf304b5c28cf0be3c00b76eef99c0
| 28.581818 | 134 | 0.604794 | 3.447034 | false | false | false | false |
mrdepth/Neocom
|
Neocom/Neocom/Mail/ComposeMail.swift
|
2
|
12745
|
//
// ComposeMail.swift
// Neocom
//
// Created by Artem Shimanski on 2/17/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import EVEAPI
import CoreData
import Combine
import Alamofire
import Expressible
struct ComposeMail: View {
var draft: MailDraft? = nil
var onComplete: () -> Void
@EnvironmentObject private var sharedState: SharedState
@Environment(\.managedObjectContext) private var managedObjectContext
var body: some View {
NavigationView {
if sharedState.account != nil {
ComposeMailContent(esi: sharedState.esi, account: sharedState.account!, managedObjectContext: managedObjectContext, draft: draft, onComplete: onComplete)
}
}
}
}
fileprivate struct ContactsSearchAlignmentID: AlignmentID {
static func defaultValue(in context: ViewDimensions) -> CGFloat {
return context[.top]
}
}
fileprivate struct ComposeMailContent: View {
var onComplete: () -> Void
private var account: Account
private var managedObjectContext: NSManagedObjectContext
private var esi: ESI
@State private var text = NSAttributedString()
@State private var subject: String
@State private var firstResponder: UITextView?
@State private var recipientsFieldFrame: CGRect?
@State private var sendSubscription: AnyCancellable?
@State private var error: IdentifiableWrapper<Error>?
@State private var needsSaveDraft = true
@State private var isSaveDraftAlertPresented = false
@State private var isLoadoutPickerPresented = false
@State private var selectedRange: NSRange = NSRange(location: 0, length: 0)
private var draft: MailDraft?
@Environment(\.self) private var environment
@EnvironmentObject private var sharedState: SharedState
@ObservedObject var contactsSearchController: SearchResultsController<[Contact]?, NSAttributedString>
@State private var contactsInitialLoading: AnyPublisher<[Int64:Contact], Never>
init(esi: ESI, account: Account, managedObjectContext: NSManagedObjectContext, draft: MailDraft?, onComplete: @escaping () -> Void) {
self.esi = esi
self.account = account
self.managedObjectContext = managedObjectContext
self.onComplete = onComplete
self.draft = draft
func search(_ string: NSAttributedString) -> AnyPublisher<[Contact]?, Never> {
let s = string.string.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines.union(.symbols))
guard !s.isEmpty else {return Just(nil).eraseToAnyPublisher()}
return Contact.searchContacts(containing: s, esi: esi, options: [.universe], managedObjectContext: managedObjectContext)
.map{$0 as Optional}
.eraseToAnyPublisher()
}
_subject = State(initialValue: draft?.subject ?? "")
_text = State(initialValue: draft?.body ?? NSAttributedString())
contactsSearchController = SearchResultsController(initialValue: nil, predicate: NSAttributedString(), search)
let contactsInitialLoading: AnyPublisher<[Int64:Contact], Never>
if let ids = draft?.to, !ids.isEmpty {
contactsInitialLoading = Contact.contacts(with: Set(ids), esi: esi, characterID: account.characterID, options: [.all], managedObjectContext: managedObjectContext).receive(on: RunLoop.main).eraseToAnyPublisher()
}
else {
contactsInitialLoading = Empty().eraseToAnyPublisher()
}
_contactsInitialLoading = State(initialValue: contactsInitialLoading)
}
private func loadContacts(_ contacts: [Int64: Contact]) {
let s = contacts.values.filter{$0.name != nil}.sorted{$0.name! < $1.name!}.map {
TextAttachmentContact($0, esi: esi)
}.reduce(into: NSMutableAttributedString()) {s, contact in s.append(NSAttributedString(attachment: contact))}
self.contactsSearchController.predicate = s
self.contactsInitialLoading = Empty().eraseToAnyPublisher()
}
private var currentMail: ESI.Mail {
let recipients = contactsSearchController.predicate.attachments.values
.compactMap{$0 as? TextAttachmentContact}
.map{ESI.Recipient(recipientID: Int($0.contact.contactID), recipientType: $0.contact.recipientType ?? .character)}
let data = try? text.data(from: NSRange(location: 0, length: text.length),
documentAttributes: [.documentType : NSAttributedString.DocumentType.html])
let html = data.flatMap{String(data: $0, encoding: .utf8)} ?? text.string
return ESI.Mail(approvedCost: 0, body: html, recipients: recipients, subject: self.subject)
}
private func sendMail() {
let mail = currentMail
self.sendSubscription = esi.characters.characterID(Int(account.characterID)).mail().post(mail: mail).sink(receiveCompletion: { (result) in
self.sendSubscription = nil
switch result {
case .finished:
self.onComplete()
case let .failure(error):
self.error = IdentifiableWrapper(error)
}
}, receiveValue: {_ in})
}
private var sendButton: some View {
let recipients = contactsSearchController.predicate.attachments.values.compactMap{$0 as? TextAttachmentContact}
return Button(action: {
self.sendMail()
}) {
Image(systemName: "paperplane").frame(minWidth: 24).contentShape(Rectangle())
}.disabled(recipients.isEmpty || text.length == 0 || sendSubscription != nil)
}
private var cancelButton: some View {
BarButtonItems.close {
if self.draft?.managedObjectContext == nil && (self.text.length > 0 || !self.subject.isEmpty) {
self.isSaveDraftAlertPresented = true
}
else {
self.onComplete()
}
}
}
private var saveDraftAlert: Alert {
Alert(title: Text("Save Draft"), primaryButton: Alert.Button.default(Text("Save"), action: {
self.needsSaveDraft = true
self.onComplete()
}), secondaryButton: Alert.Button.destructive(Text("Discard Changes"), action: {
self.needsSaveDraft = false
self.onComplete()
}))
}
private func saveDraft() {
let recipients = contactsSearchController.predicate.attachments.values
.compactMap{$0 as? TextAttachmentContact}
.map{$0.contact.contactID}
let draft = self.draft ?? MailDraft(context: managedObjectContext)
if draft.managedObjectContext == nil {
managedObjectContext.insert(draft)
}
draft.body = text
draft.subject = subject
draft.to = recipients
draft.date = Date()
}
private func attach(_ loadout: Loadout) {
guard let ship = loadout.ship, let dna = try? DNALoadoutEncoder().encode(ship), let url = URL(dna: dna) else {return}
guard let type = try? managedObjectContext.from(SDEInvType.self).filter(/\SDEInvType.typeID == loadout.typeID).first() else {return}
guard let mutableString = text.mutableCopy() as? NSMutableAttributedString else {return}
let name = ship.name?.isEmpty == false ? ship.name : type.typeName
let s = NSAttributedString(string: name ?? "", attributes: [.link: url, .font: UIFont.preferredFont(forTextStyle: .body)])
mutableString.replaceCharacters(in: selectedRange, with: s)
text = mutableString
}
private var attachmentButton: some View {
Button(action: {self.isLoadoutPickerPresented = true}) {
Image(systemName: "paperclip").frame(minWidth: 24).contentShape(Rectangle())
}
.sheet(isPresented: $isLoadoutPickerPresented) {
NavigationView {
ComposeMailLoadoutsPicker { loadout in
self.attach(loadout)
self.isLoadoutPickerPresented = false
}.navigationBarItems(leading: BarButtonItems.close {
self.isLoadoutPickerPresented = false
})
}
.modifier(ServicesViewModifier(environment: self.environment, sharedState: self.sharedState))
.navigationViewStyle(StackNavigationViewStyle())
}
}
private func recipients(_ rootGeometry: GeometryProxy) -> some View {
TextView(text: self.$contactsSearchController.predicate,
typingAttributes: [.font: UIFont.preferredFont(forTextStyle: .body)],
placeholder: NSAttributedString(string: NSLocalizedString("To:", comment: ""),
attributes: [.font: UIFont.preferredFont(forTextStyle: .headline),
.foregroundColor: UIColor.secondaryLabel]),
style: .fixedLayoutWidth(rootGeometry.size.width - 32),
onBeginEditing: { self.firstResponder = $0 },
onEndEditing: {
if self.firstResponder == $0 {
self.firstResponder = nil
}
}).alignmentGuide(VerticalAlignment(ContactsSearchAlignmentID.self)) {$0[.bottom]}
}
private var contactsSearchView: some View {
Group {
if firstResponder != nil && contactsSearchController.results != nil {
ZStack(alignment: Alignment(horizontal: .center, vertical: VerticalAlignment(ContactsSearchAlignmentID.self))) {
ContactsSearchResults(contacts: contactsSearchController.results ?? []) { contact in
var attachments = self.contactsSearchController.predicate.attachments.map{($0.key.location, $0.value)}.sorted{$0.0 < $1.0}.map{$0.1}
attachments.append(TextAttachmentContact(contact, esi: self.esi))
self.firstResponder?.resignFirstResponder()
self.contactsSearchController.predicate = attachments.reduce(into: NSMutableAttributedString()) { s, attachment in
s.append(NSAttributedString(attachment: attachment))
}
}
}
}
}
}
var body: some View {
GeometryReader { geometry in
VStack(alignment: .leading) {
VStack(alignment: .leading) {
HStack {
self.recipients(geometry)
}
HStack {
Text("From:").font(.headline).foregroundColor(.secondary)
ContactView(account: self.account, esi: self.esi)
}
HStack {
TextField("Subject", text: self.$subject)
}
}.padding(.horizontal, 16)
Divider()
TextView(text: self.$text, selectedRange: self.$selectedRange, typingAttributes: [.font: UIFont.preferredFont(forTextStyle: .body)]).padding(.horizontal, 16)
}.overlay(self.contactsSearchView, alignment: Alignment(horizontal: .center, vertical: VerticalAlignment(ContactsSearchAlignmentID.self)))
.overlay(self.sendSubscription != nil ? ActivityIndicator() : nil)
}
.onPreferenceChange(FramePreferenceKey.self) {
if self.recipientsFieldFrame?.size != $0.first?.integral.size {
self.recipientsFieldFrame = $0.first?.integral
}
}
.padding(.top)
.navigationBarTitle(Text("Compose Mail"))
.navigationBarItems(leading: cancelButton,
trailing: HStack{
attachmentButton
sendButton})
.alert(item: self.$error) { error in
Alert(title: Text("Error"), message: Text(error.wrappedValue.localizedDescription), dismissButton: .cancel(Text("Close")))
}
.alert(isPresented: $isSaveDraftAlertPresented) {
self.saveDraftAlert
}
.onDisappear {
if self.needsSaveDraft {
self.saveDraft()
}
}
.onReceive(contactsInitialLoading) { contacts in
self.loadContacts(contacts)
}
}
}
#if DEBUG
struct ComposeMail_Previews: PreviewProvider {
static var previews: some View {
ComposeMail {}
.modifier(ServicesViewModifier.testModifier())
}
}
#endif
|
lgpl-2.1
|
e1b233218d85ec0d03039ee2d774bcf4
| 43.873239 | 222 | 0.615035 | 5.235826 | false | false | false | false |
pmtao/SwiftUtilityFramework
|
SwiftUtilityFramework/UIKit/UIViewController+Extension.swift
|
1
|
1246
|
//
// UIViewController+Extension.swift
// SwiftUtilityFramework
//
// Created by 阿涛 on 18-6-27.
// Copyright © 2019年 SinkingSoul. All rights reserved.
//
import UIKit
extension UIViewController {
/// 只显示一个提示信息的提示框,点击按钮后可执行指定操作。
@available(*, deprecated, message: "This function has issue, please use UIInfo.hint(title:message:)")
public func simpleAlert(title: String,
message: String,
buttonTitle: String,
handler: ((UIAlertAction) -> Void)? = nil) {
let alertController = UIAlertController(title: title,
message: message,
preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "算了", style: .cancel, handler: nil)
let performAction = UIAlertAction(title: buttonTitle, style: .default, handler: handler)
alertController.addAction(cancelAction)
alertController.addAction(performAction)
if self.presentedViewController == nil {
self.present(alertController, animated: true, completion: nil)
}
}
}
|
mit
|
880e59c5f239baa251553fddf0281bfb
| 35.90625 | 105 | 0.591871 | 4.920833 | false | false | false | false |
zhaar/BrightFutures
|
BrightFutures/Future.swift
|
1
|
5142
|
// The MIT License (MIT)
//
// Copyright (c) 2014 Thomas Visser
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
import Result
/// Executes the given task on `Queue.global` and wraps the result of the task in a Future
public func future<T>(@autoclosure(escaping) task: () -> T) -> Future<T, NoError> {
return future(context: Queue.global.context, task: task)
}
/// Executes the given task on `Queue.global` and wraps the result of the task in a Future
public func future<T>(task: () -> T) -> Future<T, NoError> {
return future(context: Queue.global.context, task: task)
}
/// Executes the given task on the given context and wraps the result of the task in a Future
public func future<T>(context c: ExecutionContext, task: () -> T) -> Future<T, NoError> {
return future(context: c) { () -> Result<T, NoError> in
return Result(value: task())
}
}
/// Executes the given task on `Queue.global` and wraps the result of the task in a Future
public func future<T, E>(@autoclosure(escaping) task: () -> Result<T, E>) -> Future<T, E> {
return future(context: Queue.global.context, task: task)
}
/// Executes the given task on `Queue.global` and wraps the result of the task in a Future
public func future<T, E>(task: () -> Result<T, E>) -> Future<T, E> {
return future(context: Queue.global.context, task: task)
}
/// Executes the given task on the given context and wraps the result of the task in a Future
public func future<T, E>(context c: ExecutionContext, task: () -> Result<T, E>) -> Future<T, E> {
let future = Future<T, E>();
c {
future.complete(task())
}
return future
}
/// A Future represents the outcome of an asynchronous operation
/// The outcome will be represented as an instance of the `Result` enum and will be stored
/// in the `result` property. As long as the operation is not yet completed, `result` will be nil.
/// Interested parties can be informed of the completion by using one of the available callback
/// registration methods (e.g. onComplete, onSuccess & onFailure) or by immediately composing/chaining
/// subsequent actions (e.g. map, flatMap, recover, andThen, etc.).
///
/// For more info, see the project README.md
public final class Future<T, E: ErrorType>: Async<Result<T, E>> {
public typealias CompletionCallback = (result: Result<T,E>) -> Void
public typealias SuccessCallback = T -> Void
public typealias FailureCallback = E -> Void
public required init() {
super.init()
}
public required init(result: Future.Value) {
super.init(result: result)
}
public init(value: T, delay: NSTimeInterval) {
super.init(result: Result<T, E>(value: value), delay: delay)
}
public required init<A: AsyncType where A.Value == Value>(other: A) {
super.init(other: other)
}
public convenience init(value: T) {
self.init(result: Result(value: value))
}
public convenience init(error: E) {
self.init(result: Result(error: error))
}
public required init(@noescape resolver: (result: Value -> Void) -> Void) {
super.init(resolver: resolver)
}
}
/// Short-hand for `lhs.recover(rhs())`
/// `rhs` is executed according to the default threading model (see README.md)
public func ?? <T, E>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> T) -> Future<T, NoError> {
return lhs.recover(context: DefaultThreadingModel(), task: { _ in
return rhs()
})
}
/// Short-hand for `lhs.recoverWith(rhs())`
/// `rhs` is executed according to the default threading model (see README.md)
public func ?? <T, E, E1>(lhs: Future<T, E>, @autoclosure(escaping) rhs: () -> Future<T, E1>) -> Future<T, E1> {
return lhs.recoverWith(context: DefaultThreadingModel(), task: { _ in
return rhs()
})
}
/// Can be used as the value type of a `Future` or `Result` to indicate it can never be a success.
/// This is guaranteed by the type system, because `NoValue` has no possible values and thus cannot be created.
public enum NoValue { }
|
mit
|
1d89585de3710bbf3ec9e655566f4e72
| 39.809524 | 112 | 0.683392 | 3.949309 | false | false | false | false |
dps923/winter2017
|
notes/Project_Templates/WebServiceModel/Classes/WebServiceModel.swift
|
2
|
1593
|
//
// Model.swift
// Classes
//
// Created by Peter McIntyre on 2015-02-01.
// Copyright (c) 2017 School of ICT, Seneca College. All rights reserved.
//
import CoreData
struct Program {
var code = ""
var id = -1
var name = ""
}
protocol WebServiceModelDelegate : class {
func webServiceModelDidChangeContent(model: WebServiceModel)
}
class WebServiceModel {
// Property to hold/store the fetched collection
var programs = [Program]()
// The delegate gets called to report that the data has changed
weak var delegate: WebServiceModelDelegate? = nil
init() {
programsGet()
}
// Method to fetch the collection
func programsGet() {
let request = WebServiceRequest()
request.sendRequest(toUrlPath: "/programs", dataKeyName: nil, completion: {
(result: [AnyObject]) in
for item in result {
guard let programDict = item as? [String:AnyObject] else {
continue
}
var program = Program()
if let name = programDict["Name"] as? String {
program.name = name
}
if let code = programDict["Code"] as? String {
program.code = code
}
if let id = programDict["Id"] as? Int {
program.id = id
}
self.programs.append(program)
}
// notify the delegate
self.delegate?.webServiceModelDidChangeContent(model: self)
})
}
}
|
mit
|
10fc188817dc9e8b4311e08635b08ca8
| 26 | 83 | 0.550534 | 4.727003 | false | false | false | false |
codepath-volunteer-app/VolunteerMe
|
VolunteerMe/Pods/DateToolsSwift/DateToolsSwift/DateTools/Date+TimeAgo.swift
|
8
|
10466
|
//
// Date+TimeAgo.swift
// DateToolsTests
//
// Created by Matthew York on 8/23/16.
// Copyright © 2016 Matthew York. All rights reserved.
//
import Foundation
/**
* Extends the Date class by adding convenient methods to display the passage of
* time in String format.
*/
public extension Date {
//MARK: - Time Ago
/**
* Takes in a date and returns a string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - parameter date: Date to be measured from now
*
* - returns String - Formatted return string
*/
public static func timeAgo(since date:Date) -> String{
return date.timeAgo(since: Date(), numericDates: false, numericTimes: false)
}
/**
* Takes in a date and returns a shortened string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - parameter date: Date to be measured from now
*
* - returns String - Formatted return string
*/
public static func shortTimeAgo(since date:Date) -> String {
return date.shortTimeAgo(since:Date())
}
/**
* Returns a string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - returns String - Formatted return string
*/
public var timeAgoSinceNow: String {
return self.timeAgo(since:Date())
}
/**
* Returns a shortened string with the most convenient unit of time representing
* how far in the past that date is from now.
*
* - returns String - Formatted return string
*/
public var shortTimeAgoSinceNow: String {
return self.shortTimeAgo(since:Date())
}
public func timeAgo(since date:Date, numericDates: Bool = false, numericTimes: Bool = false) -> String {
let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.second,.minute,.hour,.day,.weekOfYear,.month,.year])
let earliest = self.earlierDate(date)
let latest = (earliest == self) ? date : self //Should be triple equals, but not extended to Date at this time
let components = calendar.dateComponents(unitFlags, from: earliest, to: latest)
let yesterday = date.subtract(1.days)
let isYesterday = yesterday.day == self.day
//Not Yet Implemented/Optional
//The following strings are present in the translation files but lack logic as of 2014.04.05
//@"Today", @"This week", @"This month", @"This year"
//and @"This morning", @"This afternoon"
if (components.year! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@years ago", value: components.year!)
}
else if (components.year! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 year ago");
}
return DateToolsLocalizedStrings("Last year");
}
else if (components.month! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@months ago", value: components.month!)
}
else if (components.month! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 month ago");
}
return DateToolsLocalizedStrings("Last month");
}
else if (components.weekOfYear! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@weeks ago", value: components.weekOfYear!)
}
else if (components.weekOfYear! >= 1) {
if (numericDates) {
return DateToolsLocalizedStrings("1 week ago");
}
return DateToolsLocalizedStrings("Last week");
}
else if (components.day! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@days ago", value: components.day!)
}
else if (isYesterday) {
if (numericDates) {
return DateToolsLocalizedStrings("1 day ago");
}
return DateToolsLocalizedStrings("Yesterday");
}
else if (components.hour! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@hours ago", value: components.hour!)
}
else if (components.hour! >= 1) {
if (numericTimes) {
return DateToolsLocalizedStrings("1 hour ago");
}
return DateToolsLocalizedStrings("An hour ago");
}
else if (components.minute! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@minutes ago", value: components.minute!)
}
else if (components.minute! >= 1) {
if (numericTimes) {
return DateToolsLocalizedStrings("1 minute ago");
}
return DateToolsLocalizedStrings("A minute ago");
}
else if (components.second! >= 3) {
return self.logicalLocalizedStringFromFormat(format: "%%d %@seconds ago", value: components.second!)
}
else {
if (numericTimes) {
return DateToolsLocalizedStrings("1 second ago");
}
return DateToolsLocalizedStrings("Just now");
}
}
public func shortTimeAgo(since date:Date) -> String {
let calendar = NSCalendar.current
let unitFlags = Set<Calendar.Component>([.second,.minute,.hour,.day,.weekOfYear,.month,.year])
let earliest = self.earlierDate(date)
let latest = (earliest == self) ? date : self //Should pbe triple equals, but not extended to Date at this time
let components = calendar.dateComponents(unitFlags, from: earliest, to: latest)
let yesterday = date.subtract(1.days)
let isYesterday = yesterday.day == self.day
if (components.year! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@y", value: components.year!)
}
else if (components.month! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@M", value: components.month!)
}
else if (components.weekOfYear! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@w", value: components.weekOfYear!)
}
else if (components.day! >= 2) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: components.day!)
}
else if (isYesterday) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@d", value: 1)
}
else if (components.hour! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@h", value: components.hour!)
}
else if (components.minute! >= 1) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@m", value: components.minute!)
}
else if (components.second! >= 3) {
return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!)
}
else {
return self.logicalLocalizedStringFromFormat(format: "%%d%@s", value: components.second!)
//return DateToolsLocalizedStrings(@"Now"); //string not yet translated 2014.04.05
}
}
private func logicalLocalizedStringFromFormat(format: String, value: Int) -> String{
#if os(Linux)
let localeFormat = String.init(format: format, getLocaleFormatUnderscoresWithValue(Double(value)) as! CVarArg) // this may not work, unclear!!
#else
let localeFormat = String.init(format: format, getLocaleFormatUnderscoresWithValue(Double(value)))
#endif
return String.init(format: DateToolsLocalizedStrings(localeFormat), value)
}
private func getLocaleFormatUnderscoresWithValue(_ value: Double) -> String{
let localCode = Bundle.main.preferredLocalizations[0]
if (localCode == "ru" || localCode == "uk") {
let XY = Int(floor(value).truncatingRemainder(dividingBy: 100))
let Y = Int(floor(value).truncatingRemainder(dividingBy: 10))
if(Y == 0 || Y > 4 || (XY > 10 && XY < 15)) {
return ""
}
if(Y > 1 && Y < 5 && (XY < 10 || XY > 20)) {
return "_"
}
if(Y == 1 && XY != 11) {
return "__"
}
}
return ""
}
// MARK: - Localization
private func DateToolsLocalizedStrings(_ string: String) -> String {
//let classBundle = Bundle(for:TimeChunk.self as! AnyClass.Type).resourcePath!.appending("DateTools.bundle")
//let bundelPath = Bundle(path:classBundle)!
#if os(Linux)
// NSLocalizedString() is not available yet, see: https://github.com/apple/swift-corelibs-foundation/blob/16f83ddcd311b768e30a93637af161676b0a5f2f/Foundation/NSData.swift
// However, a seemingly-equivalent method from NSBundle is: https://github.com/apple/swift-corelibs-foundation/blob/master/Foundation/NSBundle.swift
return Bundle.main.localizedString(forKey: string, value: "", table: "DateTools")
#else
return NSLocalizedString(string, tableName: "DateTools", bundle: Bundle.dateToolsBundle(), value: "", comment: "")
#endif
}
// MARK: - Date Earlier/Later
/**
* Return the earlier of two dates, between self and a given date.
*
* - parameter date: The date to compare to self
*
* - returns: The date that is earlier
*/
public func earlierDate(_ date:Date) -> Date{
return (self.timeIntervalSince1970 <= date.timeIntervalSince1970) ? self : date
}
/**
* Return the later of two dates, between self and a given date.
*
* - parameter date: The date to compare to self
*
* - returns: The date that is later
*/
public func laterDate(_ date:Date) -> Date{
return (self.timeIntervalSince1970 >= date.timeIntervalSince1970) ? self : date
}
}
|
mit
|
102075fbc749ed0028c37da8fa1cb602
| 37.054545 | 178 | 0.584615 | 4.626437 | false | false | false | false |
scinfu/SwiftSoup
|
Sources/CombiningEvaluator.swift
|
1
|
3586
|
//
// CombiningEvaluator.swift
// SwiftSoup
//
// Created by Nabil Chatbi on 23/10/16.
// Copyright © 2016 Nabil Chatbi.. All rights reserved.
//
import Foundation
/**
* Base combining (and, or) evaluator.
*/
public class CombiningEvaluator: Evaluator {
public private(set) var evaluators: Array<Evaluator>
var num: Int = 0
public override init() {
evaluators = Array<Evaluator>()
super.init()
}
public init(_ evaluators: Array<Evaluator>) {
self.evaluators = evaluators
super.init()
updateNumEvaluators()
}
public init(_ evaluators: Evaluator...) {
self.evaluators = evaluators
super.init()
updateNumEvaluators()
}
func rightMostEvaluator() -> Evaluator? {
return num > 0 && evaluators.count > 0 ? evaluators[num - 1] : nil
}
func replaceRightMostEvaluator(_ replacement: Evaluator) {
evaluators[num - 1] = replacement
}
func updateNumEvaluators() {
// used so we don't need to bash on size() for every match test
num = evaluators.count
}
public final class And: CombiningEvaluator {
public override init(_ evaluators: [Evaluator]) {
super.init(evaluators)
}
public override init(_ evaluators: Evaluator...) {
super.init(evaluators)
}
public override func matches(_ root: Element, _ node: Element) -> Bool {
for index in 0..<num {
let evaluator = evaluators[index]
do {
if (try !evaluator.matches(root, node)) {
return false
}
} catch {}
}
return true
}
public override func toString() -> String {
let array: [String] = evaluators.map { String($0.toString()) }
return StringUtil.join(array, sep: " ")
}
}
public final class Or: CombiningEvaluator {
/**
* Create a new Or evaluator. The initial evaluators are ANDed together and used as the first clause of the OR.
* @param evaluators initial OR clause (these are wrapped into an AND evaluator).
*/
public override init(_ evaluators: [Evaluator]) {
super.init()
if num > 1 {
self.evaluators.append(And(evaluators))
} else { // 0 or 1
self.evaluators.append(contentsOf: evaluators)
}
updateNumEvaluators()
}
override init(_ evaluators: Evaluator...) {
super.init()
if num > 1 {
self.evaluators.append(And(evaluators))
} else { // 0 or 1
self.evaluators.append(contentsOf: evaluators)
}
updateNumEvaluators()
}
override init() {
super.init()
}
public func add(_ evaluator: Evaluator) {
evaluators.append(evaluator)
updateNumEvaluators()
}
public override func matches(_ root: Element, _ node: Element) -> Bool {
for index in 0..<num {
let evaluator: Evaluator = evaluators[index]
do {
if (try evaluator.matches(root, node)) {
return true
}
} catch {}
}
return false
}
public override func toString() -> String {
return ":or\(evaluators.map {String($0.toString())})"
}
}
}
|
mit
|
4b78f485e88ab74122c1ad525c2164fd
| 27.228346 | 119 | 0.528033 | 4.979167 | false | false | false | false |
calebd/ReactiveCocoa
|
ReactiveCocoaTests/UIKit/UIViewSpec.swift
|
1
|
2039
|
import ReactiveSwift
import ReactiveCocoa
import UIKit
import Quick
import Nimble
import enum Result.NoError
class UIViewSpec: QuickSpec {
override func spec() {
var view: UIView!
weak var _view: UIView?
beforeEach {
view = UIView(frame: .zero)
_view = view
}
afterEach {
view = nil
expect(_view).to(beNil())
}
it("should accept changes from bindings to its hiding state") {
view.isHidden = true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
view.reactive.isHidden <~ SignalProducer(signal: pipeSignal)
observer.send(value: true)
expect(view.isHidden) == true
observer.send(value: false)
expect(view.isHidden) == false
}
it("should accept changes from bindings to its alpha value") {
view.alpha = 0.0
let firstChange = CGFloat(0.5)
let secondChange = CGFloat(0.7)
let (pipeSignal, observer) = Signal<CGFloat, NoError>.pipe()
view.reactive.alpha <~ SignalProducer(signal: pipeSignal)
observer.send(value: firstChange)
expect(view.alpha) ≈ firstChange
observer.send(value: secondChange)
expect(view.alpha) ≈ secondChange
}
it("should accept changes from bindings to its user interaction enabling state") {
view.isUserInteractionEnabled = true
let (pipeSignal, observer) = Signal<Bool, NoError>.pipe()
view.reactive.isUserInteractionEnabled <~ SignalProducer(signal: pipeSignal)
observer.send(value: true)
expect(view.isUserInteractionEnabled) == true
observer.send(value: false)
expect(view.isUserInteractionEnabled) == false
}
it("should accept changes from bindings to its background color") {
view.backgroundColor = .white
let (pipeSignal, observer) = Signal<UIColor, NoError>.pipe()
view.reactive.backgroundColor <~ SignalProducer(signal: pipeSignal)
observer.send(value: .yellow)
expect(view.backgroundColor) == .yellow
observer.send(value: .green)
expect(view.backgroundColor) == .green
observer.send(value: .red)
expect(view.backgroundColor) == .red
}
}
}
|
mit
|
413765e62b2b54ee371632341fb31859
| 24.123457 | 84 | 0.711057 | 3.727106 | false | false | false | false |
overtake/TelegramSwift
|
Telegram-Mac/CreateGroupViewController.swift
|
1
|
11383
|
//
// CreateGroupViewController.swift
// Telegram-Mac
//
// Created by keepcoder on 09/11/2016.
// Copyright © 2016 Telegram. All rights reserved.
//
import Cocoa
import TelegramCore
import Postbox
import SwiftSignalKit
import TGUIKit
fileprivate final class CreateGroupArguments {
let context: AccountContext
let choicePicture:(Bool)->Void
let updatedText:(String)->Void
init(context: AccountContext, choicePicture:@escaping(Bool)->Void, updatedText:@escaping(String)->Void) {
self.context = context
self.updatedText = updatedText
self.choicePicture = choicePicture
}
}
fileprivate enum CreateGroupEntry : Comparable, Identifiable {
case info(Int32, String?, String, GeneralViewType)
case peer(Int32, Peer, Int32, PeerPresence?, GeneralViewType)
case section(Int32)
fileprivate var stableId:AnyHashable {
switch self {
case .info:
return -1
case let .peer(_, peer, _, _, _):
return peer.id
case let .section(sectionId):
return sectionId
}
}
var index:Int32 {
switch self {
case let .info(sectionId, _, _, _):
return (sectionId * 1000) + 0
case let .peer(sectionId, _, index, _, _):
return (sectionId * 1000) + index
case let .section(sectionId):
return (sectionId + 1) * 1000 - sectionId
}
}
}
fileprivate func ==(lhs:CreateGroupEntry, rhs:CreateGroupEntry) -> Bool {
switch lhs {
case let .info(section, photo, text, viewType):
if case .info(section, photo, text, viewType) = rhs {
return true
} else {
return false
}
case let .section(sectionId):
if case .section(sectionId) = rhs {
return true
} else {
return false
}
case let .peer(sectionId, lhsPeer, index, lhsPresence, viewType):
if case .peer(sectionId, let rhsPeer, index, let rhsPresence, viewType) = rhs {
if let lhsPresence = lhsPresence, let rhsPresence = rhsPresence {
if !lhsPresence.isEqual(to: rhsPresence) {
return false
}
} else if (lhsPresence != nil) != (rhsPresence != nil) {
return false
}
return lhsPeer.isEqual(rhsPeer)
} else {
return false
}
}
}
fileprivate func <(lhs:CreateGroupEntry, rhs:CreateGroupEntry) -> Bool {
return lhs.index < rhs.index
}
struct CreateGroupResult {
let title:String
let picture: String?
let peerIds:[PeerId]
}
fileprivate func prepareEntries(from:[AppearanceWrapperEntry<CreateGroupEntry>], to:[AppearanceWrapperEntry<CreateGroupEntry>], arguments: CreateGroupArguments, initialSize:NSSize, animated:Bool) -> Signal<TableUpdateTransition, NoError> {
return Signal { subscriber in
let (deleted,inserted,updated) = proccessEntriesWithoutReverse(from, right: to, { entry -> TableRowItem in
switch entry.entry {
case let .info(_, photo, currentText, viewType):
return GroupNameRowItem(initialSize, stableId:entry.stableId, account: arguments.context.account, placeholder: strings().createGroupNameHolder, photo: photo, viewType: viewType, text: currentText, limit:140, textChangeHandler: arguments.updatedText, pickPicture: arguments.choicePicture)
case let .peer(_, peer, _, presence, viewType):
var color:NSColor = theme.colors.grayText
var string:String = strings().peerStatusRecently
if let presence = presence as? TelegramUserPresence {
let timestamp = CFAbsoluteTimeGetCurrent() + NSTimeIntervalSince1970
(string, _, color) = stringAndActivityForUserPresence(presence, timeDifference: arguments.context.timeDifference, relativeTo: Int32(timestamp))
}
return ShortPeerRowItem(initialSize, peer: peer, account: arguments.context.account, context: arguments.context, height:50, photoSize:NSMakeSize(36, 36), statusStyle: ControlStyle(foregroundColor: color), status: string, inset:NSEdgeInsets(left: 30, right:30), viewType: viewType)
case .section:
return GeneralRowItem(initialSize, height: 30, stableId: entry.stableId, viewType: .separator)
}
})
let transition = TableUpdateTransition(deleted: deleted, inserted: inserted, updated:updated, animated:animated, state:.none(nil))
subscriber.putNext(transition)
subscriber.putCompletion()
return EmptyDisposable
}
}
private func createGroupEntries(_ view: MultiplePeersView, picture: String?, text: String, appearance: Appearance) -> [AppearanceWrapperEntry<CreateGroupEntry>] {
var entries:[CreateGroupEntry] = []
var sectionId:Int32 = 0
entries.append(.section(sectionId))
sectionId += 1
entries.append(.info(sectionId, picture, text, .singleItem))
entries.append(.section(sectionId))
sectionId += 1
var index:Int32 = 0
let peers = view.peers.map({$1})
for (i, peer) in peers.enumerated() {
entries.append(.peer(sectionId, peer, index, view.presences[peer.id], bestGeneralViewType(peers, for: i)))
index += 1
}
entries.append(.section(sectionId))
sectionId += 1
return entries.map{AppearanceWrapperEntry(entry: $0, appearance: appearance)}
}
class CreateGroupViewController: ComposeViewController<CreateGroupResult, [PeerId], TableView> { // Title, photo path
private let entries:Atomic<[AppearanceWrapperEntry<CreateGroupEntry>]> = Atomic(value:[])
private let disposable:MetaDisposable = MetaDisposable()
private let pictureValue = Promise<String?>(nil)
private let textValue = ValuePromise<String>("", ignoreRepeated: true)
private let defaultText: String
init(titles: ComposeTitles, context: AccountContext, defaultText: String = "") {
self.defaultText = defaultText
super.init(titles: titles, context: context)
self.textValue.set(self.defaultText)
}
override func restart(with result: ComposeState<[PeerId]>) {
super.restart(with: result)
assert(isLoaded())
let initialSize = self.atomicSize
let table = self.genericView
let pictureValue = self.pictureValue
let textValue = self.textValue
let context = self.context
if self.defaultText == "" && result.result.count < 5 {
let peers: Signal<String, NoError> = context.account.postbox.transaction { transaction in
let main = transaction.getPeer(context.peerId)
let rest = result.result
.map {
transaction.getPeer($0)
}
.compactMap { $0 }
.map { $0.compactDisplayTitle }
.joined(separator: ", ")
if let main = main, !rest.isEmpty {
return main.compactDisplayTitle + " & " + rest
} else {
return ""
}
} |> deliverOnMainQueue
_ = peers.start(next: { [weak self] title in
self?.textValue.set(title)
delay(0.2, closure: { [weak self] in
self?.genericView.enumerateItems(with: { item in
if let item = item as? GroupNameRowItem {
let textView = item.view?.firstResponder as? NSTextView
textView?.selectAll(nil)
return false
}
return true
})
})
})
}
let entries = self.entries
let arguments = CreateGroupArguments(context: context, choicePicture: { select in
if select {
filePanel(with: photoExts, allowMultiple: false, canChooseDirectories: false, for: context.window, completion: { paths in
if let path = paths?.first, let image = NSImage(contentsOfFile: path) {
_ = (putToTemp(image: image, compress: true) |> deliverOnMainQueue).start(next: { path in
let controller = EditImageModalController(URL(fileURLWithPath: path), settings: .disableSizes(dimensions: .square))
showModal(with: controller, for: context.window, animationType: .scaleCenter)
pictureValue.set(controller.result |> map {Optional($0.0.path)})
controller.onClose = {
removeFile(at: path)
}
})
}
})
} else {
pictureValue.set(.single(nil))
}
}, updatedText: { text in
textValue.set(text)
})
let signal:Signal<TableUpdateTransition, NoError> = combineLatest(context.account.postbox.multiplePeersView(result.result) |> deliverOnPrepareQueue, appearanceSignal |> deliverOnPrepareQueue, pictureValue.get() |> deliverOnPrepareQueue, textValue.get() |> deliverOnPrepareQueue) |> mapToSignal { view, appearance, picture, text in
let list = createGroupEntries(view, picture: picture, text: text, appearance: appearance)
return prepareEntries(from: entries.swap(list), to: list, arguments: arguments, initialSize: initialSize.modify({$0}), animated: true)
} |> deliverOnMainQueue
disposable.set(signal.start(next: { (transition) in
table.merge(with: transition)
//table.reloadData()
}))
}
override var canBecomeResponder: Bool {
return true
}
override func becomeFirstResponder() -> Bool? {
return true
}
override func firstResponder() -> NSResponder? {
if let view = genericView.viewNecessary(at: 1) as? GroupNameRowView {
return view.textView
}
return nil
}
override func escapeKeyAction() -> KeyHandlerResult {
return .rejected
}
deinit {
disposable.dispose()
_ = entries.swap([])
}
override func viewDidLoad() {
super.viewDidLoad()
genericView.getBackgroundColor = {
theme.colors.listBackground
}
readyOnce()
}
override func executeNext() -> Void {
if let previousResult = previousResult {
let result = combineLatest(pictureValue.get() |> take(1), textValue.get() |> take(1)) |> map { value, text in
return CreateGroupResult(title: text, picture: value, peerIds: previousResult.result)
}
onComplete.set(result |> filter {
!$0.title.isEmpty
})
}
}
override func backKeyAction() -> KeyHandlerResult {
return .invokeNext
}
}
|
gpl-2.0
|
ae0cc84c8a0adcf07c11c9158c5d0677
| 36.318033 | 338 | 0.584168 | 5.065421 | false | false | false | false |
evnaz/Design-Patterns-In-Swift
|
source-cn/behavioral/interpreter.swift
|
2
|
2641
|
/*:
🎶 解释器(Interpreter)
------------------
给定一种语言,定义他的文法的一种表示,并定义一个解释器,该解释器使用该表示来解释语言中句子。
### 示例:
*/
protocol IntegerExpression {
func evaluate(_ context: IntegerContext) -> Int
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression
func copied() -> IntegerExpression
}
final class IntegerContext {
private var data: [Character:Int] = [:]
func lookup(name: Character) -> Int {
return self.data[name]!
}
func assign(expression: IntegerVariableExpression, value: Int) {
self.data[expression.name] = value
}
}
final class IntegerVariableExpression: IntegerExpression {
let name: Character
init(name: Character) {
self.name = name
}
func evaluate(_ context: IntegerContext) -> Int {
return context.lookup(name: self.name)
}
func replace(character name: Character, integerExpression: IntegerExpression) -> IntegerExpression {
if name == self.name {
return integerExpression.copied()
} else {
return IntegerVariableExpression(name: self.name)
}
}
func copied() -> IntegerExpression {
return IntegerVariableExpression(name: self.name)
}
}
final class AddExpression: IntegerExpression {
private var operand1: IntegerExpression
private var operand2: IntegerExpression
init(op1: IntegerExpression, op2: IntegerExpression) {
self.operand1 = op1
self.operand2 = op2
}
func evaluate(_ context: IntegerContext) -> Int {
return self.operand1.evaluate(context) + self.operand2.evaluate(context)
}
func replace(character: Character, integerExpression: IntegerExpression) -> IntegerExpression {
return AddExpression(op1: operand1.replace(character: character, integerExpression: integerExpression),
op2: operand2.replace(character: character, integerExpression: integerExpression))
}
func copied() -> IntegerExpression {
return AddExpression(op1: self.operand1, op2: self.operand2)
}
}
/*:
### 用法
*/
var context = IntegerContext()
var a = IntegerVariableExpression(name: "A")
var b = IntegerVariableExpression(name: "B")
var c = IntegerVariableExpression(name: "C")
var expression = AddExpression(op1: a, op2: AddExpression(op1: b, op2: c)) // a + (b + c)
context.assign(expression: a, value: 2)
context.assign(expression: b, value: 1)
context.assign(expression: c, value: 3)
var result = expression.evaluate(context)
|
gpl-3.0
|
ca687d7b9493a6860744c796fd668729
| 27.382022 | 111 | 0.677751 | 3.953052 | false | false | false | false |
ichu501/TKAnimatedCheckButton
|
TKAnimatedCheckButton/Classes/TKAnimatedCheckButton.swift
|
2
|
6208
|
//
// TKAnimatedCheckButton.swift
// TKAnimatedCheckButton
//
// Created by Takuya Okamoto on 2015/08/06.
// Copyright (c) 2015年 Uniface. All rights reserved.
// Inspired by
//http://robb.is/working-on/a-hamburger-button-transition/
//https://dribbble.com/shots/1631598-On-Off
import Foundation
import CoreGraphics
import QuartzCore
import UIKit
public class TKAnimatedCheckButton : UIButton {
public var color = UIColor.whiteColor().CGColor {
didSet {
self.shape.strokeColor = color
}
}
public var skeletonColor = UIColor.whiteColor().colorWithAlphaComponent(0.25).CGColor {
didSet {
circle.strokeColor = skeletonColor
check.strokeColor = skeletonColor
}
}
let path: CGPath = {
let p = CGPathCreateMutable()
CGPathMoveToPoint(p, nil, 5.07473346,20.2956615)
CGPathAddCurveToPoint(p, nil, 3.1031115,24.4497281, 2,29.0960413, 2,34)
CGPathAddCurveToPoint(p, nil, 2,51.673112, 16.326888,66, 34,66)
CGPathAddCurveToPoint(p, nil, 51.673112,66, 66,51.673112, 66,34)
CGPathAddCurveToPoint(p, nil, 66,16.326888, 51.673112,2, 34,2)
CGPathAddCurveToPoint(p, nil, 21.3077047,2, 10.3412842,9.38934836, 5.16807419,20.1007094)
CGPathAddLineToPoint(p, nil, 29.9939289,43.1625671)
CGPathAddLineToPoint(p, nil, 56.7161293,17.3530369)
return p
}()
let pathSize:CGFloat = 70
let circleStrokeStart: CGFloat = 0.0
let circleStrokeEnd: CGFloat = 0.738
let checkStrokeStart: CGFloat = 0.8
let checkStrokeEnd: CGFloat = 0.97
var shape: CAShapeLayer! = CAShapeLayer()
var circle: CAShapeLayer! = CAShapeLayer()
var check: CAShapeLayer! = CAShapeLayer()
let lineWidth:CGFloat = 4
let lineWidthBold:CGFloat = 5
public required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public override init(frame: CGRect) {
super.init(frame: frame)
let defaultPoint = self.frame.origin
var size = frame.width
if frame.width < frame.height {
size = frame.height
}
let scale:CGFloat = size / pathSize
self.frame.size = CGSize(width: pathSize, height: pathSize)
self.shape.path = path
self.circle.path = path
self.check.path = path
self.shape.strokeColor = color
self.circle.strokeColor = skeletonColor
self.check.strokeColor = skeletonColor
self.shape.position = CGPointMake(pathSize/2, pathSize/2)
self.circle.position = self.shape.position
self.check.position = self.shape.position
self.shape.strokeStart = circleStrokeStart
self.shape.strokeEnd = circleStrokeEnd
self.circle.strokeStart = circleStrokeStart
self.circle.strokeEnd = circleStrokeEnd
self.check.strokeStart = checkStrokeStart
self.check.strokeEnd = checkStrokeEnd
shape.lineWidth = lineWidth
circle.lineWidth = lineWidth
check.lineWidth = lineWidthBold
for layer in [ circle, check, self.shape ] {
layer.fillColor = nil
layer.miterLimit = 4
layer.lineCap = kCALineCapRound
layer.masksToBounds = true
let strokingPath:CGPath = CGPathCreateCopyByStrokingPath(layer.path, nil, 4, kCGLineCapRound, kCGLineJoinMiter, 4)
layer.bounds = CGPathGetPathBoundingBox(strokingPath)
layer.actions = [
"strokeStart": NSNull(),
"strokeEnd": NSNull(),
"transform": NSNull()
]
self.layer.transform = CATransform3DMakeScale(scale, scale, 1);
self.layer.addSublayer(layer)
}
self.frame.origin = defaultPoint
}
let timingFunc = CAMediaTimingFunction(controlPoints: 0.44,-0.04,0.64,1.4)//0.69,0.12,0.23,1.27)
let backFunc = CAMediaTimingFunction(controlPoints: 0.45,-0.36,0.44,0.92)
public var checked: Bool = false {
didSet {
let strokeStart = CABasicAnimation(keyPath: "strokeStart")
let strokeEnd = CABasicAnimation(keyPath: "strokeEnd")
let lineWidthAnim = CABasicAnimation(keyPath: "lineWidth")
if self.checked {
strokeStart.toValue = checkStrokeStart
strokeStart.duration = 0.3//0.5
strokeStart.timingFunction = timingFunc
strokeEnd.toValue = checkStrokeEnd
strokeEnd.duration = 0.3//0.6
strokeEnd.timingFunction = timingFunc
lineWidthAnim.toValue = lineWidthBold
lineWidthAnim.beginTime = 0.2
lineWidthAnim.duration = 0.1
lineWidthAnim.timingFunction = timingFunc
} else {
strokeStart.toValue = circleStrokeStart
strokeStart.duration = 0.2//0.5
strokeStart.timingFunction = backFunc//CAMediaTimingFunction(controlPoints: 0.25, 0, 0.5, 1.2)
// strokeStart.beginTime = CACurrentMediaTime() + 0.1
strokeStart.fillMode = kCAFillModeBackwards
strokeEnd.toValue = circleStrokeEnd
strokeEnd.duration = 0.3//0.6
strokeEnd.timingFunction = backFunc//CAMediaTimingFunction(controlPoints: 0.25, 0.3, 0.5, 0.9)
lineWidthAnim.toValue = lineWidth
lineWidthAnim.duration = 0.1
lineWidthAnim.timingFunction = backFunc
}
self.shape.ocb_applyAnimation(strokeStart)
self.shape.ocb_applyAnimation(strokeEnd)
self.shape.ocb_applyAnimation(lineWidthAnim)
}
}
}
extension CALayer {
func ocb_applyAnimation(animation: CABasicAnimation) {
let copy = animation.copy() as! CABasicAnimation
if copy.fromValue == nil {
copy.fromValue = self.presentationLayer().valueForKeyPath(copy.keyPath)
}
self.addAnimation(copy, forKey: copy.keyPath)
self.setValue(copy.toValue, forKeyPath:copy.keyPath)
}
}
|
mit
|
7987238a64093f4b0ff75d870b926c6c
| 34.872832 | 126 | 0.62069 | 4.432857 | false | false | false | false |
apple/swift-async-algorithms
|
Tests/AsyncAlgorithmsTests/Support/Indefinite.swift
|
1
|
661
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift Async Algorithms open source project
//
// Copyright (c) 2022 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
//
//===----------------------------------------------------------------------===//
struct Indefinite<Element: Sendable>: Sequence, IteratorProtocol, Sendable {
let value: Element
func next() -> Element? {
return value
}
func makeIterator() -> Indefinite<Element> {
self
}
}
|
apache-2.0
|
f4ea1ea00d5c6b3712d8d4594c615cfa
| 29.045455 | 80 | 0.534039 | 5.508333 | false | false | false | false |
CanyFrog/HCComponent
|
HCSource/HCAnimationEngine.swift
|
1
|
18411
|
//
// HCAnimationEngine.swift
// HCComponents
//
// Created by Magee Huang on 5/12/17.
// Copyright © 2017 Person Inc. All rights reserved.
//
import UIKit
extension CABasicAnimation {
/**
A convenience initializer that takes a given animateAnimationKeyPath.
- Parameter keyPath: An animateAnimationKeyPath.
*/
public convenience init(keyPath: HCAnimationProperty) {
self.init(keyPath: keyPath.rawValue)
}
}
open class HCAnimationEngine: NSObject {
/// A boolean indicating whether Animation is presenting a view controller.
open fileprivate(set) var isPresenting: Bool
/// A boolean indicating whether the view controller is a container.
open fileprivate(set) var isContainer: Bool
/**
An Array of UIView pairs with common animateIdentifiers in
the from and to view controllers.
*/
open fileprivate(set) var transitionPairs = [(UIView, UIView)]()
/// A reference to the transition snapshot.
open var transitionSnapshot: UIView!
/// A reference to the transition background view.
open let transitionBackgroundView = UIView()
/// A reference to the view controller that is being transitioned to.
open var toViewController: UIViewController {
return transitionContext.viewController(forKey: .to)!
}
/// A reference to the view controller that is being transitioned from.
open var fromViewController: UIViewController {
return transitionContext.viewController(forKey: .from)!
}
/// The transition context for the current transition.
open var transitionContext: UIViewControllerContextTransitioning!
/// The transition delay time.
open var delay: TimeInterval = 0
/// The transition duration time.
open var duration: TimeInterval = 0.35
/// The transition container view.
open var containerView: UIView!
/// The view that is used to animate the transitions between view controllers.
open var transitionView = UIView()
/// The view that is being transitioned to.
open var toView: UIView {
return toViewController.view
}
/// The subviews of the view being transitioned to.
open var toSubviews: [UIView] {
return HCAnimation.subviews(of: toView)
}
/// The view that is being transitioned from.
open var fromView: UIView {
return fromViewController.view
}
/// The subviews of the view being transitioned from.
open var fromSubviews: [UIView] {
return HCAnimation.subviews(of: fromView)
}
/// The default initializer.
public override init() {
isPresenting = false
isContainer = false
super.init()
}
/**
An initializer to modify the presenting and container state.
- Parameter isPresenting: A boolean value indicating if the
animate instance is presenting the view controller.
- Parameter isContainer: A boolean value indicating if the
animate instance is a container view controller.
*/
public init(isPresenting: Bool, isContainer: Bool) {
self.isPresenting = isPresenting
self.isContainer = isContainer
super.init()
}
/// Returns an Array of subviews for a given subview.
fileprivate class func subviews(of view: UIView) -> [UIView] {
var views: [UIView] = []
HCAnimation.subviews(of: view, views: &views)
return views
}
/// Populates an Array of views that are subviews of a given view.
fileprivate class func subviews(of view: UIView, views: inout [UIView]) {
for v in view.subviews {
if 0 < v.animateIdentifier.utf16.count {
views.append(v)
}
subviews(of: v, views: &views)
}
}
/**
Executes a block of code after a time delay.
- Parameter duration: An animation duration time.
- Parameter animations: An animation block.
- Parameter execute block: A completion block that is executed once
the animations have completed.
*/
@discardableResult
open class func delay(_ time: TimeInterval, execute block: @escaping () -> Void) -> HCAnimateDelayCancelBlock? {
func asyncAfter(completion: @escaping () -> Void) {
DispatchQueue.main.asyncAfter(deadline: .now() + time, execute: completion)
}
var cancelable: HCAnimateDelayCancelBlock?
let delayed: HCAnimateDelayCancelBlock = {
if !$0 {
DispatchQueue.main.async(execute: block)
}
cancelable = nil
}
cancelable = delayed
asyncAfter {
cancelable?(false)
}
return cancelable
}
/**
Cancels the delayed HCAnimateDelayCancelBlock.
- Parameter delayed completion: An HCAnimateDelayCancelBlock.
*/
open class func cancel(delayed completion: HCAnimateDelayCancelBlock) {
completion(true)
}
/**
Disables the default animations set on CALayers.
- Parameter animations: A callback that wraps the animations to disable.
*/
open class func disable(_ animations: (() -> Void)) {
animate(duration: 0, animations: animations)
}
/**
Runs an animation with a specified duration.
- Parameter duration: An animation duration time.
- Parameter animations: An animation block.
- Parameter timingFunction: An animateAnimationTimingFunction value.
- Parameter completion: A completion block that is executed once
the animations have completed.
*/
open class func animate(duration: CFTimeInterval, timingFunction: HCAnimationTimingFunction = .easeInEaseOut, animations: (() -> Void), completion: (() -> Void)? = nil) {
CATransaction.begin()
CATransaction.setAnimationDuration(duration)
CATransaction.setCompletionBlock(completion)
CATransaction.setAnimationTimingFunction(timingFunction.value)
animations()
CATransaction.commit()
}
}
extension HCAnimationEngine: UIViewControllerAnimatedTransitioning {
/**
The animation method that is used to coordinate the transition.
- Parameter using transitionContext: A UIViewControllerContextTransitioning.
*/
open func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
self.transitionContext = transitionContext
}
/**
Returns the transition duration time interval.
- Parameter using transitionContext: An optional UIViewControllerContextTransitioning.
- Returns: A TimeInterval that is the total animation time including delays.
*/
open func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return delay + duration
}
}
extension HCAnimationEngine {
/// Adds the available transition animations.
fileprivate func addTransitionAnimations() {
for (from, to) in transitionPairs {
var snapshotAnimations = [CABasicAnimation]()
var snapshotChildAnimations = [CABasicAnimation]()
let sizeAnimation = HCAnimation.size(to.bounds.size)
let cornerRadiusAnimation = HCAnimation.corner(radius: to.layer.cornerRadius)
snapshotAnimations.append(sizeAnimation)
snapshotAnimations.append(cornerRadiusAnimation)
snapshotAnimations.append(HCAnimation.position(to: to.animatePosition))
snapshotAnimations.append(HCAnimation.transform(transform: to.animateTransform))
snapshotAnimations.append(HCAnimation.background(color: to.backgroundColor ?? .clear))
if let path = to.layer.shadowPath {
let shadowPath = HCAnimation.shadow(path: path)
shadowPath.fromValue = fromView.layer.shadowPath
snapshotAnimations.append(shadowPath)
}
let shadowOffset = HCAnimation.shadow(offset: to.layer.shadowOffset)
shadowOffset.fromValue = fromView.layer.shadowOffset
snapshotAnimations.append(shadowOffset)
let shadowOpacity = HCAnimation.shadow(opacity: to.layer.shadowOpacity)
shadowOpacity.fromValue = fromView.layer.shadowOpacity
snapshotAnimations.append(shadowOpacity)
let shadowRadius = HCAnimation.shadow(radius: to.layer.shadowRadius)
shadowRadius.fromValue = fromView.layer.shadowRadius
snapshotAnimations.append(shadowRadius)
snapshotChildAnimations.append(cornerRadiusAnimation)
snapshotChildAnimations.append(sizeAnimation)
snapshotChildAnimations.append(HCAnimation.position(x: to.bounds.width / 2, y: to.bounds.height / 2))
let d = calculateAnimationTransitionDuration(animations: to.animationArgus)
let snapshot = from.transitionSnapshot(afterUpdates: true)
transitionView.addSubview(snapshot)
HCAnimation.delay(calculateAnimationDelayTimeInterval(animations: to.animationArgus)) { [weak self, weak to] in
guard let s = self else {
return
}
guard let v = to else {
return
}
let tf = s.calculateAnimationTimingFunction(animations: v.animationArgus)
let snapshotGroup = HCAnimation.animate(group: snapshotAnimations, duration: d)
snapshotGroup.fillMode = HCAnimationFillMode.forwards.value
snapshotGroup.isRemovedOnCompletion = false
snapshotGroup.timingFunction = tf.value
let snapshotChildGroup = HCAnimation.animate(group: snapshotChildAnimations, duration: d)
snapshotChildGroup.fillMode = HCAnimationFillMode.forwards.value
snapshotChildGroup.isRemovedOnCompletion = false
snapshotChildGroup.timingFunction = tf.value
snapshot.animate(snapshotGroup)
snapshot.subviews.first?.animate(snapshotChildGroup)
}
}
}
/// Adds the background animation.
fileprivate func addBackgroundAnimation() {
transitionBackgroundView.animate(.backgroundColor(isPresenting ? toView.backgroundColor ?? .clear : .clear), .duration(transitionDuration(using: transitionContext)))
}
}
extension HCAnimationEngine {
/**
Calculates the animation delay time based on the given Array of Animations.
- Parameter animations: An Array of Animations.
- Returns: A TimeInterval.
*/
fileprivate func calculateAnimationDelayTimeInterval(animations: [HCAnimationArguments]) -> TimeInterval {
var t: TimeInterval = 0
for a in animations {
switch a {
case let .delay(time):
if time > delay {
delay = time
}
t = time
default:break
}
}
return t
}
/**
Calculates the animation transition duration based on the given Array of animateAnimations.
- Parameter animations: An Array of animateAnimations.
- Returns: A TimeInterval.
*/
fileprivate func calculateAnimationTransitionDuration(animations: [HCAnimationArguments]) -> TimeInterval {
var t: TimeInterval = 0.35
for a in animations {
switch a {
case let .duration(time):
if time > duration {
duration = time
}
t = time
default:break
}
}
return t
}
/**
Calculates the animation timing function based on the given Array of animateAnimations.
- Parameter animations: An Array of animateAnimations.
- Returns: A animateAnimationTimingFunction.
*/
fileprivate func calculateAnimationTimingFunction(animations: [HCAnimationArguments]) -> HCAnimationTimingFunction {
var t = HCAnimationTimingFunction.easeInEaseOut
for a in animations {
switch a {
case let .timingFunction(timingFunction):
t = timingFunction
default:break
}
}
return t
}
}
open class HCAnimation: HCAnimationEngine {
/// A time value to delay the transition animation by.
fileprivate var delayTransitionByTimeInterval: TimeInterval {
return fromViewController.animateDelegate?.hcAnimateDelayTransitionByTimeInterval(animate: self) ?? 0
}
/**
The animation method that is used to coordinate the transition.
- Parameter using transitionContext: A UIViewControllerContextTransitioning.
*/
open override func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
super.animateTransition(using: transitionContext)
fromViewController.animateDelegate?.hcAnimate(animate: self, willTransition: fromView, toView: toView)
HCAnimation.delay(delayTransitionByTimeInterval) { [weak self] in
guard let s = self else {
return
}
s.prepareContainerView()
s.prepareTransitionSnapshot()
s.prepareTransitionPairs()
s.prepareTransitionView()
s.prepareTransitionBackgroundView()
s.prepareToView()
s.prepareTransitionAnimation()
}
}
/// Prepares the toView.
fileprivate func prepareToView() {
toView.isHidden = isPresenting
containerView.insertSubview(toView, belowSubview: transitionView)
toView.frame = fromView.frame
toView.updateConstraints()
toView.setNeedsLayout()
toView.layoutIfNeeded()
}
}
extension HCAnimation {
/// Prepares the containerView.
fileprivate func prepareContainerView() {
containerView = transitionContext.containerView
}
/// Prepares the transitionSnapshot.
fileprivate func prepareTransitionSnapshot() {
transitionSnapshot = fromView.transitionSnapshot(afterUpdates: true, shouldHide: false)
transitionSnapshot.frame = fromView.frame
containerView.addSubview(transitionSnapshot)
}
/// Prepares the transitionPairs.
fileprivate func prepareTransitionPairs() {
for from in fromSubviews {
for to in toSubviews {
guard to.animateIdentifier == from.animateIdentifier else {
continue
}
transitionPairs.append((from, to))
}
}
}
/// Prepares the transitionView.
fileprivate func prepareTransitionView() {
transitionView.frame = toView.bounds
transitionView.isUserInteractionEnabled = false
containerView.insertSubview(transitionView, belowSubview: transitionSnapshot)
}
/// Prepares the transitionBackgroundView.
fileprivate func prepareTransitionBackgroundView() {
transitionBackgroundView.backgroundColor = isPresenting ? .clear : fromView.backgroundColor ?? .clear
transitionBackgroundView.frame = transitionView.bounds
transitionView.addSubview(transitionBackgroundView)
}
/// Prepares the transition animation.
fileprivate func prepareTransitionAnimation() {
addTransitionAnimations()
addBackgroundAnimation()
cleanUpAnimation()
removeTransitionSnapshot()
}
}
extension HCAnimation {
/**
Creates a CAAnimationGroup.
- Parameter animations: An Array of CAAnimation objects.
- Parameter timingFunction: An animateAnimationTimingFunction value.
- Parameter duration: An animation duration time for the group.
- Returns: A CAAnimationGroup.
*/
open class func animate(group animations: [CAAnimation], timingFunction: HCAnimationTimingFunction = .easeInEaseOut, duration: CFTimeInterval = 0.5) -> CAAnimationGroup {
let group = CAAnimationGroup()
group.fillMode = HCAnimationFillMode.forwards.value
group.isRemovedOnCompletion = false
group.animations = animations
group.duration = duration
group.timingFunction = timingFunction.value
return group
}
}
extension HCAnimation {
/// Cleans up the animation transition.
fileprivate func cleanUpAnimation() {
HCAnimation.delay(transitionDuration(using: transitionContext) + delayTransitionByTimeInterval) { [weak self] in
guard let s = self else {
return
}
s.showToSubviews()
s.removeTransitionView()
s.clearTransitionPairs()
s.completeTransition()
}
}
/// Removes the transitionSnapshot from its superview.
fileprivate func removeTransitionSnapshot() {
HCAnimation.delay(delay) { [weak self] in
self?.transitionSnapshot.removeFromSuperview()
}
}
/// Shows the toView and its subviews.
fileprivate func showToSubviews() {
toSubviews.forEach {
$0.isHidden = false
}
toView.isHidden = false
}
/// Clears the transitionPairs Array.
fileprivate func clearTransitionPairs() {
transitionPairs.removeAll()
}
/// Removes the transitionView.
fileprivate func removeTransitionView() {
transitionView.removeFromSuperview()
}
/// Calls the completionTransition method.
fileprivate func completeTransition() {
toViewController.animateDelegate?.hcAnimate(animate: self, didTransition: fromView, toView: toView)
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
}
}
open class HCPresentAnimate: HCAnimation {}
open class HCDismissAnimate: HCAnimation {
/// Prepares the toView.
fileprivate override func prepareToView() {
toView.isHidden = true
toView.frame = fromView.frame
toView.updateConstraints()
toView.setNeedsLayout()
toView.layoutIfNeeded()
}
}
|
mit
|
9b025f900c977399e65e8f4f43d5effa
| 35.240157 | 174 | 0.649484 | 5.650706 | false | false | false | false |
forgo/BabySync
|
bbsync/mobile/iOS/Baby Sync/Baby Sync/Family.swift
|
1
|
955
|
//
// Family.swift
// Baby Sync
//
// Created by Elliott Richerson on 9/29/15.
// Copyright © 2015 Elliott Richerson. All rights reserved.
//
import Foundation
struct Family {
var id: Int = 0
var name: String = ""
var createdOn: Date = Date()
var updatedOn: Date = Date()
init?() {
self.id = 0
self.name = ""
self.createdOn = Date()
self.updatedOn = Date()
}
init?(family: JSON) {
self.id = family["id"].intValue
self.name = family["name"].stringValue
self.createdOn = ISO8601DateFormatter.sharedInstance.date(from: family["created_on"].stringValue)!
self.updatedOn = ISO8601DateFormatter.sharedInstance.date(from: family["updated_on"].stringValue)!
}
init?(family: Family) {
self.id = family.id
self.name = family.name
self.createdOn = family.createdOn
self.updatedOn = family.updatedOn
}
}
|
mit
|
765457881a430fc95070b6d1a1f8b694
| 24.105263 | 106 | 0.598532 | 3.909836 | false | false | false | false |
czerenkow/LublinWeather
|
App/Extensions/UIKit/UIView.swift
|
1
|
1930
|
//
// UIView.swift
// LublinWeather
//
// Created by Damian Rzeszot on 04/05/2018.
// Copyright © 2018 Damian Rzeszot. All rights reserved.
//
import UIKit
extension UIView {
@IBInspectable
var borderWidth: CGFloat {
set(value) {
layer.borderWidth = value
}
get {
return layer.borderWidth
}
}
@IBInspectable
var borderColor: UIColor? {
set(value) {
layer.borderColor = value?.cgColor
}
get {
guard let color = layer.borderColor else { return nil }
return UIColor(cgColor: color)
}
}
}
extension UIView {
@IBInspectable
var cornerRadius: CGFloat {
set(value) {
layer.cornerRadius = value
}
get {
return layer.cornerRadius
}
}
@available(iOS 11.0, *)
var maskedCorners: CACornerMask {
set(value) {
layer.maskedCorners = value
}
get {
return layer.maskedCorners
}
}
}
extension UIView {
@IBInspectable
var shadowColor: UIColor? {
set(value) {
layer.shadowColor = value?.cgColor
}
get {
guard let color = layer.shadowColor else { return nil }
return UIColor(cgColor: color)
}
}
@IBInspectable
var shadowOffset: CGSize {
set(value) {
layer.shadowOffset = value
}
get {
return layer.shadowOffset
}
}
@IBInspectable
var shadowRadius: CGFloat {
set(value) {
layer.shadowRadius = value
}
get {
return layer.shadowRadius
}
}
@IBInspectable
var shadowOpacity: Float {
set(value) {
layer.shadowOpacity = value
}
get {
return layer.shadowOpacity
}
}
}
|
mit
|
b683760d6ecda8ec0cf13d0961bb0ccf
| 17.198113 | 67 | 0.512182 | 4.8225 | false | false | false | false |
benlangmuir/swift
|
test/Constraints/tuple_arguments.swift
|
4
|
66067
|
// 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)) -> () = { x, y in }
// expected-error@-1 {{closure tuple parameter '(Int, Int)' does not support destructuring}} {{33-37=(arg)}} {{40-40= let (x, y) = 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 {{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
}
f2.forEach { block in
// expected-note@-1 {{'block' declared here}}
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 in
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) // expected-error {{parameter 'block' expects a single parameter of type '(Bool, Bool)'}}
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 {{'block' declared here}}
block(p) // expected-error {{parameter 'block' expects 2 separate arguments}}
}
f2.forEach { (block: (Bool, Bool) -> ()) in
// expected-note@-1 {{'block' declared here}}
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
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))
}
// https://github.com/apple/swift/issues/46957
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
))
// https://github.com/apple/swift/issues/47322
do {
let x = [1, 2]
let _ = x.enumerated().map { (count, element) in "\(count): \(element)" }
}
// https://github.com/apple/swift/issues/47315
do {
let tuple = (1, (2, 3))
[tuple].map { (x, (y, z)) -> Int in x + y + z } // expected-note 2 {{'x' declared here}}
// expected-error@-1 {{closure tuple parameter does not support destructuring}} {{21-27=arg1}} {{39-39=let (y, z) = arg1; }}
// expected-warning@-2 {{unnamed parameters must be written with the empty name '_'}} {{21-21=_: }}
// expected-error@-3 {{cannot find 'y' in scope; did you mean 'x'?}}
// expected-error@-4 {{cannot find 'z' in scope; did you mean 'x'?}}
}
// 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=_: }}
val + 1
// expected-error@-1 {{cannot find 'val' in scope}}
}
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(+)
}
// https://github.com/apple/swift/issues/47775
struct S_47775 {}
extension Sequence where Iterator.Element == (key: String, value: String?) {
func f() -> [S_47775] {
return self.map { (key, value) in
S_47775() // 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)
}
// https://github.com/apple/swift/issues/48003
func f_48003<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://github.com/apple/swift/issues/49059
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://github.com/apple/swift/issues/49386
// FIXME: Can't overload 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://github.com/apple/swift/issues/49345
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://github.com/apple/swift/issues/49739
do {
class Mappable<T> {
init(_: T) { }
func map<U>(_ body: (T) -> U) -> U { fatalError() }
}
let x = Mappable(())
x.map { (_: Void) in return () }
x.map { (_: ()) in () }
}
// https://github.com/apple/swift/issues/51932
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)
}
}
func variadicSplat() {
func takesFnWithVarg(fn: (Int, Int...) -> Void) {}
takesFnWithVarg { x in // expected-error {{contextual closure type '(Int, Int...) -> Void' expects 2 arguments, but 1 was used in closure body}}
_ = x.1.count
}
takesFnWithVarg { x, y in
_ = y.count
}
}
|
apache-2.0
|
25f2bec139101c469bb6aa2e3e91bc6a
| 35.683509 | 253 | 0.633962 | 3.415727 | false | false | false | false |
MartinOSix/DemoKit
|
dSwift/SwiftDemoKit/SwiftDemoKit/ShowCollectionViewController.swift
|
1
|
3529
|
//
// ShowCollectionViewController.swift
// SwiftDemoKit
//
// Created by runo on 17/5/16.
// Copyright © 2017年 com.runo. All rights reserved.
//
import UIKit
class ShowCollectionViewController: UIViewController,CustomWaterFallLayoutDelegate {
var style: String!
var collectionView: UICollectionView!
var reuseIdentifier = "cell"
var cellCount = 0
var cellHeight = [CGFloat]()
var lineDataSource = [UIColor.red,UIColor.blue,UIColor.yellow,UIColor.brown,UIColor.purple]
override func viewDidLoad() {
super.viewDidLoad()
edgesForExtendedLayout = []
self.automaticallyAdjustsScrollViewInsets = true
collectionView = UICollectionView(frame: kScreenBounds, collectionViewLayout: UICollectionViewLayout())
switch style {
case "line":
setLineLayout()
cellCount = lineDataSource.count
case "waterfall":
let layout = FlowWaterLayout()
layout.delegate = self
layout.numberOfColums = 4
cellCount = 100
collectionView.contentInset = UIEdgeInsets.init(top: 64, left: 0, bottom: 0, right: 0)
for _ in 0..<self.cellCount {
cellHeight.append(CGFloat(arc4random()%150 + 30))
}
collectionView.collectionViewLayout = layout
default:
break
}
collectionView.backgroundColor = UIColor.white
collectionView.dataSource = self
collectionView.delegate = self
collectionView.allowsMultipleSelection = true
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: reuseIdentifier)
view.addSubview(collectionView)
}
func heightForItemAtIndexPath(indexPath: IndexPath) -> CGFloat {
return cellHeight[indexPath.row]
}
func setLineLayout() {
let layout = LinerLayout()
layout.itemSize = CGSize.init(width: kScreenWidth-80, height: kScreenHeight-100)
layout.minimumInteritemSpacing = 20
layout.scrollDirection = .horizontal
layout.sectionInset = UIEdgeInsets.init(top: 84, left: 40, bottom: 0, right: 40)
//collectionView.isPagingEnabled = true
collectionView.collectionViewLayout = layout
}
}
extension ShowCollectionViewController: UICollectionViewDataSource, UICollectionViewDelegate {
func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return cellCount
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath)
cell.backgroundColor = lineDataSource[indexPath.row%5]
for view in cell.subviews {
view.removeFromSuperview()
}
collectionView .selectItem(at: indexPath, animated: false, scrollPosition: UICollectionViewScrollPosition.init(rawValue: 0))
return cell
}
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
print(indexPath)
}
func collectionView(_ collectionView: UICollectionView, didDeselectItemAt indexPath: IndexPath) {
print("dis select \(indexPath)")
}
}
|
apache-2.0
|
5f2ddaf4207da949d0caa33bfa1846fe
| 29.136752 | 132 | 0.667328 | 5.696284 | false | false | false | false |
iAugux/iBBS-Swift
|
iBBS/IBBSNodesCollectionViewController.swift
|
1
|
6206
|
//
// IBBSNodesCollectionViewController.swift
// iBBS
//
// Created by Augus on 9/2/15.
//
// http://iAugus.com
// https://github.com/iAugux
//
// Copyright © 2015 iAugus. All rights reserved.
//
import UIKit
import SwiftyJSON
import GearRefreshControl
class IBBSNodesCollectionViewController: UICollectionViewController {
private var gearRefreshControl: GearRefreshControl!
private var nodesArray: [JSON]? {
didSet {
dispatch_async(GlobalMainQueue) {
self.collectionView?.reloadData()
}
}
}
override func viewDidLoad() {
super.viewDidLoad()
configureNodesInfo()
gearRefreshManager()
collectionView?.addSubview(gearRefreshControl)
collectionView?.alwaysBounceVertical = true
collectionView?.backgroundColor = UIColor.whiteColor()
navigationController?.navigationBar.topItem?.title = TITLE_ALL_NODES
}
override func willAnimateRotationToInterfaceOrientation(toInterfaceOrientation: UIInterfaceOrientation, duration: NSTimeInterval) {
collectionView?.collectionViewLayout.invalidateLayout()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName: CUSTOM_THEME_COLOR]
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(updateTheme), name: kThemeDidChangeNotification, object: nil)
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
navigationController?.interactivePopGestureRecognizer?.enabled = false
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - update theme
@objc private func updateTheme() {
navigationController?.navigationBar.titleTextAttributes = [NSForegroundColorAttributeName : CUSTOM_THEME_COLOR]
if let cells = collectionView?.visibleCells() as? [IBBSNodesCollectionViewCell] {
for index in 0 ..< cells.count {
let cell = cells[index]
cell.imageView.backgroundColor = CUSTOM_THEME_COLOR.lighterColor(0.75)
cell.imageView.layer.shadowColor = CUSTOM_THEME_COLOR.darkerColor(0.9).CGColor
cell.customBackgroundView?.fillColor = CUSTOM_THEME_COLOR.lighterColor(0.8)
cell.customBackgroundView?.setNeedsDisplay()
}
}
gearRefreshControl?.removeFromSuperview()
gearRefreshManager()
collectionView?.addSubview(gearRefreshControl)
}
}
extension IBBSNodesCollectionViewController {
// MARK: - Collection view data source
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return nodesArray?.count ?? 0
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
guard let cell = collectionView.dequeueReusableCellWithReuseIdentifier(String(IBBSNodesCollectionViewCell), forIndexPath: indexPath) as? IBBSNodesCollectionViewCell else {
return UICollectionViewCell()
}
// nodesArray = IBBSConfigureNodesInfo.sharedInstance.nodesArray
if let array = nodesArray {
let json = array[indexPath.row]
let model = IBBSNodeModel(json: json)
cell.infoLabel?.text = model.name
}
return cell
}
// MARK: - Collection view delegate
override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
guard let array = nodesArray else { return }
guard let vc = UIStoryboard.Main.instantiateViewControllerWithIdentifier(String(IBBSNodeViewController)) as? IBBSNodeViewController else { return }
let json = array[indexPath.row]
vc.nodeJSON = json
navigationController?.pushViewController(vc, animated: true)
}
}
extension IBBSNodesCollectionViewController {
// MARK: - perform GearRefreshControl
override func scrollViewDidScroll(scrollView: UIScrollView) {
gearRefreshControl?.scrollViewDidScroll(scrollView)
executeAfterDelay(3) {
self.gearRefreshControl?.endRefreshing()
}
}
private func gearRefreshManager() {
gearRefreshControl = GearRefreshControl(frame: view.bounds)
gearRefreshControl.gearTintColor = CUSTOM_THEME_COLOR.lighterColor(0.7)
gearRefreshControl.addTarget(self, action: #selector(refreshData), forControlEvents: UIControlEvents.ValueChanged)
}
@objc private func refreshData() {
configureNodesInfo()
}
private func configureNodesInfo() {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), {
self.getNodesIfNeeded({ (nodes) in
if let json = nodes {
print(json)
self.nodesArray = json.arrayValue
} else {
IBBSToast.make(TRY_AGAIN, interval: 1)
}
})
})
}
func getNodesIfNeeded(completion: ((nodes: JSON?) -> ())? = nil) {
APIClient.defaultClient.getNodes({ (json) -> Void in
guard json.type == Type.Array else { return }
IBBSContext.saveNodes(json.object)
completion?(nodes: json)
}) { (error) -> Void in
IBBSToast.make(SERVER_ERROR, interval: TIME_OF_TOAST_OF_SERVER_ERROR)
}
}
}
|
mit
|
f38e653789ed9d5d2f96cb0853a8a336
| 32.005319 | 179 | 0.641418 | 5.560036 | false | false | false | false |
jopamer/swift
|
test/PlaygroundTransform/nested_function.swift
|
1
|
1777
|
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -Xfrontend -playground -o %t/main %S/Inputs/PlaygroundsRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -o %t/main %S/Inputs/PlaygroundsRuntime.swift %S/Inputs/SilentPCMacroRuntime.swift %t/main.swift
// RUN: %target-run %t/main | %FileCheck %s
// REQUIRES: executable_test
func returnSum() -> Int {
var y = 10
func add() {
y += 5
}
add()
let addAgain = {
y += 5
}
addAgain()
let addMulti = {
y += 5
_ = 0 // force a multi-statement closure
}
addMulti()
return y
}
returnSum()
// CHECK-NOT: __builtin
// CHECK: [9:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [10:{{.*}}] __builtin_log[y='10']
// CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [12:{{.*}}] __builtin_log[y='15']
// CHECK-NEXT: [11:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [15:{{.*}}] __builtin_log[addAgain='{{.*}}']
// CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_entry
// FIXME: We drop the log for the addition here.
// CHECK-NEXT: [16:{{.*}}] __builtin_log[='()']
// CHECK-NEXT: [15:{{.*}}] __builtin_log_scope_exit
// FIXME: There's an extra, unbalanced scope exit here.
// CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [19:{{.*}}] __builtin_log[addMulti='{{.*}}']
// CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_entry
// CHECK-NEXT: [20:{{.*}}] __builtin_log[y='25']
// CHECK-NEXT: [21:{{.*}}] __builtin_log[='0']
// CHECK-NEXT: [19:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [24:{{.*}}] __builtin_log[='25']
// CHECK-NEXT: [9:{{.*}}] __builtin_log_scope_exit
// CHECK-NEXT: [27:{{.*}}] __builtin_log[='25']
// CHECK-NOT: __builtin
|
apache-2.0
|
29220253a8e62c4348188c36745342d4
| 31.907407 | 168 | 0.584131 | 2.956739 | false | false | false | false |
bfortunato/aj-framework
|
platforms/ios/Libs/AJ/AJ/AJAssetsManager.swift
|
1
|
1758
|
//
// AJAssetsManager.swift
// AJ
//
// Created by Bruno Fortunato on 09/03/16.
// Copyright © 2016 Bruno Fortunato. All rights reserved.
//
import UIKit
import JavaScriptCore
import ApplicaFramework
@objc
public protocol AJAssetsManagerProtocol: JSExport {
func load(_ path: String, _ cb: JSValue)
}
@objc
open class AJAssetsManager: NSObject, AJAssetsManagerProtocol {
let runtime: AJRuntime
let handleQueue = DispatchQueue(label: "AJ.AJAssetsManager.handleQueue", attributes: DispatchQueue.Attributes.concurrent)
init(runtime: AJRuntime) {
self.runtime = runtime
super.init()
}
open func load(_ path: String, _ cb: JSValue) {
handleQueue.async {
let base = "/assets/"
let normalizedPath = AFPathUtils.normalizePath(path)
let dir = AFPathUtils.getBaseName(normalizedPath)
let fullDir = AFPathUtils.concat(base, dir)
let name = AFPathUtils.getName(normalizedPath, includingExtension: false)
let type = AFPathUtils.getExtension(normalizedPath)
guard let url = Bundle.main.path(forResource: name, ofType: type, inDirectory: fullDir) else {
cb.call(withArguments: [true, "Asset not found: \(path)"])
return
}
guard let data = try? Data(contentsOf: URL(fileURLWithPath: url)) else {
cb.call(withArguments: [true, "Error loading asset: \(path)"])
return
}
cb.call(withArguments: [false, AJBuffer.create(with: data)])
}
}
open func exists(_ path: String, _ cb: JSValue) {
cb.call(withArguments: [false, true])
}
}
|
apache-2.0
|
b9cea262adb1ac9b2b86fbf6aa03fbd7
| 29.824561 | 125 | 0.608993 | 4.370647 | false | false | false | false |
NordicSemiconductor/IOS-nRF-Toolbox
|
nRF Toolbox/Utilities/StoryboardInstantiable.swift
|
1
|
2765
|
/*
* Copyright (c) 2020, Nordic Semiconductor
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or
* other materials provided with the distribution.
*
* 3. Neither the name of the copyright holder nor the names of its contributors may
* be used to endorse or promote products derived from this software without
* specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
* ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
* IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
* NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
protocol StoryboardInstantiable {
static func instance(storyboard: UIStoryboard, storyboardId: String) -> Self
static func instance(storyboardId: String) -> Self
static func instance(storyboard: UIStoryboard) -> Self
static func instance() -> Self
}
extension StoryboardInstantiable where Self: UIViewController {
static func instance(storyboard: UIStoryboard, storyboardId: String) -> Self {
return storyboard.instantiateViewController(withIdentifier: storyboardId) as! Self
}
static func instance(storyboardId: String) -> Self {
let name = String(describing: self)
let storyboard = UIStoryboard(name: name, bundle: Bundle.main)
return instance(storyboard: storyboard, storyboardId: storyboardId)
}
static func instance(storyboard: UIStoryboard) -> Self {
let name = String(describing: self)
return instance(storyboard: storyboard, storyboardId: name)
}
static func instance() -> Self {
let name = String(describing: self)
let storyboard = UIStoryboard(name: name, bundle: Bundle.main)
return instance(storyboard: storyboard, storyboardId: name)
}
}
|
bsd-3-clause
|
59f0ae43d6cbdcb5f2b8b06d221b8f5f
| 42.888889 | 90 | 0.746112 | 4.859402 | false | false | false | false |
Darr758/Swift-Algorithms-and-Data-Structures
|
Algorithms/RotateN*NMatrix90Degrees.playground/Contents.swift
|
1
|
485
|
//Flip an n*n matric 90% left
func rotateMatrix(_ matrix: inout [[Int]]){
let count = matrix[0].count
for x in 0..<count{
for y in x..<count{
if x == y {continue}
swap(&matrix[x][y],&matrix[y][x])
}
}
var opposite = count - 1
for x in 0..<count{
for y in 0..<count{
if x == opposite {break}
swap(&matrix[x][y],&matrix[opposite][y])
}
opposite -= 1
}
}
|
mit
|
5a422cf9f7b8048c97629657aaf31a3c
| 21.045455 | 52 | 0.451546 | 3.592593 | false | false | false | false |
crossroadlabs/Twist
|
Sources/Twist/NSObjectProperties.swift
|
1
|
3955
|
//===--- NSObjectProperties.swift ----------------------------------------------===//
//Copyright (c) 2016 Crossroad Labs s.r.o.
//
//Licensed under the Apache License, Version 2.0 (the "License");
//you may not use this file except in compliance with the License.
//You may obtain a copy of the License at
//
//http://www.apache.org/licenses/LICENSE-2.0
//
//Unless required by applicable law or agreed to in writing, software
//distributed under the License is distributed on an "AS IS" BASIS,
//WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
//See the License for the specific language governing permissions and
//limitations under the License.
//===----------------------------------------------------------------------===//
import Foundation
import ExecutionContext
import Event
//TODO: uncycle the chains for NSObject
private class KVOProcessor<T> : NSObject {
private unowned let _stream:KVOSignalStream<T>
init(stream:KVOSignalStream<T>) {
self._stream = stream
}
@objc override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let old = change?[.oldKey].flatMap { val in
val as? T
}
let new = change?[.newKey].flatMap { val in
val as? T
}
_stream <= (old!, new!)
}
}
private class KVOSignalStream<T> : SignalNode<(T, T)> {
private var _ap:KVOProcessor<T>?
private weak var _object:NSObject?
private let _property:String
//TODO: handle early, fuck
init(context:ExecutionContextProtocol, object:NSObject, property:String, early:Bool) {
_object = object
_property = property
//TODO: should not be main
super.init(context: context)
_ap = KVOProcessor(stream: self)
object.addObserver(_ap!, forKeyPath: property, options: [.new, .old], context: nil)
}
deinit {
_object?.removeObserver(_ap!, forKeyPath: _property)
}
}
public class NSPropertyDescriptor<Component: ExecutionContextTenantProtocol, T> : MutablePropertyDescriptor<Component, MutableObservable<T>> where Component : NSObject {
public init(name:String) {
super.init(subscribe: { component, early in
return KVOSignalStream(context: component.context, object: component, property: name, early: early)
}, accessor: { component in
return component.value(forKey: name).flatMap { value in
value as? T
}!
}, mutator: { component, value in
component.setValue(value, forKey: name)
})
}
}
public extension NSObjectProtocol where Self : NSObject, Self : ExecutionContextTenantProtocol {
public func property<T>(name: String, type: T.Type) -> MutableObservable<T> {
let context = self.context
return MutableObservable(context: context, subscriber: { early in
return KVOSignalStream(context: context, object: self, property: name, early: early)
}, accessor: {
return self.value(forKey: name).flatMap { value in
value as? T
}!
}, mutator: { value in
self.setValue(value, forKey: name)
})
}
public func p<T>(name: String, type: T.Type) -> MutableObservable<T> {
return property(name: name, type: type)
}
}
public extension NSObjectProtocol where Self : ExecutionContextTenantProtocol {
public func property<Observable : ParametrizableObservableProtocol>(_ pd:PropertyDescriptor<Self, Observable>) -> Observable {
return pd.makeProperty(for: self)
}
public func p<Observable : ParametrizableObservableProtocol>(_ pd:PropertyDescriptor<Self, Observable>) -> Observable {
return pd.makeProperty(for: self)
}
}
|
apache-2.0
|
40900a60997de69bb8b60b84de0e1056
| 35.962617 | 169 | 0.62225 | 4.598837 | false | false | false | false |
powerytg/Accented
|
Accented/UI/Home/Menu/Sections/MainMenuThemeSectionView.swift
|
1
|
2092
|
//
// MainMenuThemeSectionView.swift
// Accented
//
// Created by Tiangong You on 8/27/17.
// Copyright © 2017 Tiangong You. All rights reserved.
//
import UIKit
class MainMenuThemeSectionView: MainMenuSectionBase {
private let paddingTop : CGFloat = 15
private let paddingLeft : CGFloat = 20
private let paddingRight : CGFloat = 20
private let rowHeight : CGFloat = 150
private let gap : CGFloat = 14
var renderers = [MainMenuThemeRenderer]()
override func initialize() {
super.initialize()
for theme in ThemeManager.sharedInstance.themes {
let renderer = MainMenuThemeRenderer(theme)
contentView.addSubview(renderer)
renderers.append(renderer)
let tap = UITapGestureRecognizer(target: self, action: #selector(didSelectTheme(_:)))
renderer.addGestureRecognizer(tap)
}
}
override func calculateContentHeight(maxWidth: CGFloat) -> CGFloat {
return (rowHeight + gap) * CGFloat(ThemeManager.sharedInstance.themes.count) + paddingTop
}
override func layoutSubviews() {
super.layoutSubviews()
var nextY : CGFloat = paddingTop
for renderer in renderers {
var f = renderer.frame
f.size.width = contentView.bounds.size.width - paddingLeft - paddingRight
f.size.height = rowHeight
f.origin.x = paddingLeft
f.origin.y = nextY
renderer.frame = f
nextY += rowHeight + gap
}
}
@objc private func didSelectTheme(_ tap : UITapGestureRecognizer) {
guard tap.view != nil else { return }
guard tap.view! is MainMenuThemeRenderer else { return }
let renderer = tap.view! as! MainMenuThemeRenderer
let selectedTheme = renderer.theme
if selectedTheme != ThemeManager.sharedInstance.currentTheme {
ThemeManager.sharedInstance.currentTheme = selectedTheme
drawer?.dismiss(animated: true, completion: nil)
}
}
}
|
mit
|
5fc8f79eb94644837aedf6d1b37c4436
| 32.190476 | 97 | 0.63032 | 5.050725 | false | false | false | false |
krzysztofzablocki/Sourcery
|
SourceryFramework/Sources/Parsing/Utils/AnnotationsParser.swift
|
1
|
17091
|
//
// Created by Krzysztof Zablocki on 31/12/2016.
// Copyright (c) 2016 Pixle. All rights reserved.
//
import Foundation
import SwiftSyntax
import SourceryRuntime
/// Parser for annotations, and also documentation
public struct AnnotationsParser {
private enum AnnotationType {
case begin(Annotations)
case annotations(Annotations)
case end
case inlineStart
case file(Annotations)
}
private struct Line {
enum LineType {
case comment
case documentationComment
case blockStart
case blockEnd
case other
case inlineStart
case inlineEnd
case file
}
let content: String
let type: LineType
let annotations: Annotations
let blockAnnotations: Annotations
}
private let lines: [Line]
private let contents: String
private var parseDocumentation: Bool
internal var sourceLocationConverter: SourceLocationConverter?
/// Initializes parser
///
/// - Parameter contents: Contents to parse
init(contents: String, parseDocumentation: Bool = false, sourceLocationConverter: SourceLocationConverter? = nil) {
self.parseDocumentation = parseDocumentation
self.lines = AnnotationsParser.parse(contents: contents)
self.sourceLocationConverter = sourceLocationConverter
self.contents = contents
}
/// returns all annotations in the contents
var all: Annotations {
var all = Annotations()
lines.forEach {
$0.annotations.forEach {
AnnotationsParser.append(key: $0.key, value: $0.value, to: &all)
}
}
return all
}
func annotations(from node: IdentifierSyntax) -> Annotations {
from(
location: findLocation(syntax: node.identifier),
precedingComments: node.leadingTrivia?.compactMap({ $0.comment }) ?? []
)
}
func annotations(fromToken token: SyntaxProtocol) -> Annotations {
from(
location: findLocation(syntax: token),
precedingComments: token.leadingTrivia?.compactMap({ $0.comment }) ?? []
)
}
func documentation(from node: IdentifierSyntax) -> Documentation {
guard parseDocumentation else {
return []
}
return documentationFrom(
location: findLocation(syntax: node.identifier),
precedingComments: node.leadingTrivia?.compactMap({ $0.comment }) ?? []
)
}
func documentation(fromToken token: SyntaxProtocol) -> Documentation {
guard parseDocumentation else {
return []
}
return documentationFrom(
location: findLocation(syntax: token),
precedingComments: token.leadingTrivia?.compactMap({ $0.comment }) ?? []
)
}
// TODO: once removing SourceKitten just kill this optionality
private func findLocation(syntax: SyntaxProtocol) -> SwiftSyntax.SourceLocation {
return sourceLocationConverter!.location(for: syntax.positionAfterSkippingLeadingTrivia)
}
private func from(location: SwiftSyntax.SourceLocation, precedingComments: [String]) -> Annotations {
guard let lineNumber = location.line, let column = location.column else {
return [:]
}
var stop = false
var annotations = inlineFrom(line: (lineNumber, column), stop: &stop)
guard !stop else { return annotations }
for line in lines[0..<lineNumber-1].reversed() {
line.annotations.forEach { annotation in
AnnotationsParser.append(key: annotation.key, value: annotation.value, to: &annotations)
}
if line.type != .comment && line.type != .documentationComment {
break
}
}
lines[lineNumber-1].annotations.forEach { annotation in
AnnotationsParser.append(key: annotation.key, value: annotation.value, to: &annotations)
}
return annotations
}
private func documentationFrom(location: SwiftSyntax.SourceLocation, precedingComments: [String]) -> Documentation {
guard parseDocumentation,
let lineNumber = location.line, let column = location.column else {
return []
}
// Inline documentation not currently supported
_ = column
// var stop = false
// var documentation = inlineDocumentationFrom(line: (lineNumber, column), stop: &stop)
// guard !stop else { return annotations }
var documentation: Documentation = []
for line in lines[0..<lineNumber-1].reversed() {
if line.type == .documentationComment {
documentation.append(line.content.trimmingCharacters(in: .whitespaces).trimmingPrefix("///").trimmingPrefix("/**").trimmingPrefix(" "))
}
if line.type != .comment && line.type != .documentationComment {
break
}
}
return documentation.reversed()
}
func inlineFrom(line lineInfo: (line: Int, character: Int), stop: inout Bool) -> Annotations {
let sourceLine = lines[lineInfo.line - 1]
var prefix = sourceLine.content.bridge()
.substring(to: max(0, lineInfo.character - 1))
.trimmingCharacters(in: .whitespaces)
guard !prefix.isEmpty else { return [:] }
var annotations = sourceLine.blockAnnotations // get block annotations for this line
sourceLine.annotations.forEach { annotation in // TODO: verify
AnnotationsParser.append(key: annotation.key, value: annotation.value, to: &annotations)
}
// `case` is not included in the key of enum case definition, so we strip it manually
let isInsideCaseDefinition = prefix.trimmingCharacters(in: .whitespacesAndNewlines).hasPrefix("case")
prefix = prefix.trimmingPrefix("case").trimmingCharacters(in: .whitespaces)
var inlineCommentFound = false
while !prefix.isEmpty {
guard prefix.hasSuffix("*/"), let commentStart = prefix.range(of: "/*", options: [.backwards]) else {
break
}
inlineCommentFound = true
let comment = String(prefix[commentStart.lowerBound...])
for annotation in AnnotationsParser.parse(contents: comment)[0].annotations {
AnnotationsParser.append(key: annotation.key, value: annotation.value, to: &annotations)
}
prefix = prefix[..<commentStart.lowerBound].trimmingCharacters(in: .whitespaces)
}
if (inlineCommentFound || isInsideCaseDefinition) && !prefix.isEmpty {
stop = true
return annotations
}
// if previous line is not comment or has some trailing non-comment blocks
// we return currently aggregated annotations
// as annotations on previous line belong to previous declaration
if lineInfo.line - 2 > 0 {
let previousLine = lines[lineInfo.line - 2]
let content = previousLine.content.trimmingCharacters(in: .whitespaces)
guard previousLine.type == .comment || previousLine.type == .documentationComment, content.hasPrefix("//") || content.hasSuffix("*/") else {
stop = true
return annotations
}
}
return annotations
}
private static func parse(contents: String) -> [Line] {
var annotationsBlock: Annotations?
var fileAnnotationsBlock = Annotations()
return StringView(contents).lines
.map { line in
let content = line.content.trimmingCharacters(in: .whitespaces)
var annotations = Annotations()
let isComment = content.hasPrefix("//") || content.hasPrefix("/*") || content.hasPrefix("*")
let isDocumentationComment = content.hasPrefix("///") || content.hasPrefix("/**")
var type = Line.LineType.other
if isDocumentationComment {
type = .documentationComment
} else if isComment {
type = .comment
}
if isComment {
switch searchForAnnotations(commentLine: content) {
case let .begin(items):
type = .blockStart
annotationsBlock = Annotations()
items.forEach { annotationsBlock?[$0.key] = $0.value }
case let .annotations(items):
items.forEach { annotations[$0.key] = $0.value }
case .end:
if annotationsBlock != nil {
type = .blockEnd
annotationsBlock?.removeAll()
} else {
type = .inlineEnd
}
case .inlineStart:
type = .inlineStart
case let .file(items):
type = .file
items.forEach {
fileAnnotationsBlock[$0.key] = $0.value
}
}
} else {
searchForTrailingAnnotations(codeLine: content)
.forEach { annotations[$0.key] = $0.value }
}
annotationsBlock?.forEach { annotation in
annotations[annotation.key] = annotation.value
}
fileAnnotationsBlock.forEach { annotation in
annotations[annotation.key] = annotation.value
}
return Line(content: line.content,
type: type,
annotations: annotations,
blockAnnotations: annotationsBlock ?? [:])
}
}
private static func searchForTrailingAnnotations(codeLine: String) -> Annotations {
let blockComponents = codeLine.components(separatedBy: "/*", excludingDelimiterBetween: ("", ""))
if blockComponents.count > 1,
let lastBlockComponent = blockComponents.last,
let endBlockRange = lastBlockComponent.range(of: "*/"),
let lowerBound = lastBlockComponent.range(of: "sourcery:")?.upperBound {
let trailingStart = endBlockRange.upperBound
let trailing = String(lastBlockComponent[trailingStart...])
if trailing.components(separatedBy: "//", excludingDelimiterBetween: ("", "")).first?.trimmed.count == 0 {
let upperBound = endBlockRange.lowerBound
return AnnotationsParser.parse(line: String(lastBlockComponent[lowerBound..<upperBound]))
}
}
let components = codeLine.components(separatedBy: "//", excludingDelimiterBetween: ("", ""))
if components.count > 1,
let trailingComment = components.last?.stripped(),
let lowerBound = trailingComment.range(of: "sourcery:")?.upperBound {
return AnnotationsParser.parse(line: String(trailingComment[lowerBound...]))
}
return [:]
}
private static func searchForAnnotations(commentLine: String) -> AnnotationType {
let comment = commentLine.trimmingPrefix("///").trimmingPrefix("//").trimmingPrefix("/**").trimmingPrefix("/*").trimmingPrefix("*").stripped()
guard comment.hasPrefix("sourcery:") else { return .annotations([:]) }
if comment.hasPrefix("sourcery:inline:") {
return .inlineStart
}
let lowerBound: String.Index?
let upperBound: String.Index?
var insideBlock: Bool = false
var insideFileBlock: Bool = false
if comment.hasPrefix("sourcery:begin:") {
lowerBound = commentLine.range(of: "sourcery:begin:")?.upperBound
upperBound = commentLine.indices.endIndex
insideBlock = true
} else if comment.hasPrefix("sourcery:end") {
return .end
} else if comment.hasPrefix("sourcery:file") {
lowerBound = commentLine.range(of: "sourcery:file:")?.upperBound
upperBound = commentLine.indices.endIndex
insideFileBlock = true
} else {
lowerBound = commentLine.range(of: "sourcery:")?.upperBound
if commentLine.hasPrefix("//") || commentLine.hasPrefix("*") {
upperBound = commentLine.indices.endIndex
} else {
upperBound = commentLine.range(of: "*/")?.lowerBound
}
}
if let lowerBound = lowerBound, let upperBound = upperBound {
let annotations = AnnotationsParser.parse(line: String(commentLine[lowerBound..<upperBound]))
if insideBlock {
return .begin(annotations)
} else if insideFileBlock {
return .file(annotations)
} else {
return .annotations(annotations)
}
} else {
return .annotations([:])
}
}
/// Parses annotations from the given line
///
/// - Parameter line: Line to parse.
/// - Returns: Dictionary containing all annotations.
public static func parse(line: String) -> Annotations {
var annotationDefinitions = line.trimmingCharacters(in: .whitespaces)
.commaSeparated()
.map { $0.trimmingCharacters(in: .whitespaces) }
var namespaces = annotationDefinitions[0].components(separatedBy: ":", excludingDelimiterBetween: (open: "\"'", close: "\"'"))
annotationDefinitions[0] = namespaces.removeLast()
var annotations = Annotations()
annotationDefinitions.forEach { annotation in
let parts = annotation
.components(separatedBy: "=", excludingDelimiterBetween: ("", ""))
.map({ $0.trimmingCharacters(in: .whitespaces) })
if let name = parts.first, !name.isEmpty {
guard parts.count > 1, var value = parts.last, value.isEmpty == false else {
append(key: name, value: NSNumber(value: true), to: &annotations)
return
}
if let number = Float(value) {
append(key: name, value: NSNumber(value: number), to: &annotations)
} else {
if (value.hasPrefix("'") && value.hasSuffix("'")) || (value.hasPrefix("\"") && value.hasSuffix("\"")) {
value = String(value[value.index(after: value.startIndex) ..< value.index(before: value.endIndex)])
value = value.trimmingCharacters(in: .whitespaces)
}
guard let data = (value as String).data(using: .utf8),
let json = try? JSONSerialization.jsonObject(with: data, options: .allowFragments) else {
append(key: name, value: value as NSString, to: &annotations)
return
}
if let array = json as? [Any] {
append(key: name, value: array as NSArray, to: &annotations)
} else if let dict = json as? [String: Any] {
append(key: name, value: dict as NSDictionary, to: &annotations)
} else {
append(key: name, value: value as NSString, to: &annotations)
}
}
}
}
if namespaces.isEmpty {
return annotations
} else {
var namespaced = Annotations()
for namespace in namespaces.reversed() {
namespaced[namespace] = annotations as NSObject
annotations = namespaced
namespaced = Annotations()
}
return annotations
}
}
static func append(key: String, value: NSObject, to annotations: inout Annotations) {
if let oldValue = annotations[key] {
if var array = oldValue as? [NSObject] {
if !array.contains(value) {
array.append(value)
annotations[key] = array as NSObject
}
} else if var oldDict = oldValue as? [String: NSObject], let newDict = value as? [String: NSObject] {
newDict.forEach({ (key, value) in
append(key: key, value: value, to: &oldDict)
})
annotations[key] = oldDict as NSObject
} else if oldValue != value {
annotations[key] = [oldValue, value] as NSObject
}
} else {
annotations[key] = value
}
}
}
|
mit
|
a1210db48aa509b0ab5e69232a8f30ba
| 39.789976 | 152 | 0.563162 | 5.384688 | false | false | false | false |
Antondomashnev/FBSnapshotsViewer
|
FBSnapshotsViewerTests/FolderEventSpec.swift
|
1
|
6455
|
//
// FolderEventSpec.swift
// FBSnapshotsViewer
//
// Created by Anton Domashnev on 05/02/2017.
// Copyright © 2017 Anton Domashnev. All rights reserved.
//
import Quick
import Nimble
@testable import FBSnapshotsViewer
class FolderEventSpec: QuickSpec {
override func spec() {
describe(".object") {
context("when modified") {
it("returns correct object") {
expect(FolderEvent.modified(path: "lala", object: .folder).object).to(equal(FolderEventObject.folder))
}
}
context("when created") {
it("returns correct object") {
expect(FolderEvent.created(path: "lala", object: .file).object).to(equal(FolderEventObject.file))
}
}
context("when deleted") {
it("returns correct object") {
expect(FolderEvent.deleted(path: "lala", object: .folder).object).to(equal(FolderEventObject.folder))
}
}
context("when renamed") {
it("returns correct object") {
expect(FolderEvent.renamed(path: "lala", object: .file).object).to(equal(FolderEventObject.file))
}
}
context("when unknown") {
it("returns nil") {
expect(FolderEvent.unknown.object).to(beNil())
}
}
}
describe(".path") {
context("when modified") {
it("returns correct path") {
expect(FolderEvent.modified(path: "foo", object: .folder).path).to(equal("foo"))
}
}
context("when created") {
it("returns correct path") {
expect(FolderEvent.created(path: "buka", object: .file).path).to(equal("buka"))
}
}
context("when deleted") {
it("returns correct path") {
expect(FolderEvent.deleted(path: "lala", object: .folder).path).to(equal("lala"))
}
}
context("when renamed") {
it("returns correct path") {
expect(FolderEvent.renamed(path: "bar", object: .file).path).to(equal("bar"))
}
}
context("when unknown") {
it("returns nil") {
expect(FolderEvent.unknown.path).to(beNil())
}
}
}
context("when file event") {
var eventFlag: FileWatcher.EventFlag!
beforeEach {
eventFlag = FileWatcher.EventFlag.ItemIsFile
}
context("when renamed") {
it ("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemRenamed.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.renamed(path: "/temp", object: .file)
expect(event).to(equal(expectedEvent))
}
}
context("when modified") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemModified.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.modified(path: "/temp", object: .file)
expect(event).to(equal(expectedEvent))
}
}
context("when created") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemCreated.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.created(path: "/temp", object: .file)
expect(event).to(equal(expectedEvent))
}
}
context("when deleted") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemRemoved.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.deleted(path: "/temp", object: .file)
expect(event).to(equal(expectedEvent))
}
}
}
context("when folder event") {
var eventFlag: FileWatcher.EventFlag!
beforeEach {
eventFlag = FileWatcher.EventFlag.ItemIsDir
}
context("when unknown") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.None.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.unknown
expect(event).to(equal(expectedEvent))
}
}
context("when renamed") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemRenamed.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.renamed(path: "/temp", object: .folder)
expect(event).to(equal(expectedEvent))
}
}
context("when modified") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemModified.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.modified(path: "/temp", object: .folder)
expect(event).to(equal(expectedEvent))
}
}
context("when created") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemCreated.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.created(path: "/temp", object: .folder)
expect(event).to(equal(expectedEvent))
}
}
context("when deleted") {
it("returns correct folder event") {
let event = FolderEvent(eventFlag: FileWatcher.EventFlag.ItemRemoved.union(eventFlag), at: "/temp")
let expectedEvent = FolderEvent.deleted(path: "/temp", object: .folder)
expect(event).to(equal(expectedEvent))
}
}
}
}
}
|
mit
|
346e214496c126e643c7f02fc5574f0a
| 37.416667 | 122 | 0.508522 | 4.926718 | false | false | false | false |
whong7/swift-knowledge
|
思维导图/4-3:网易新闻/Pods/Kingfisher/Sources/KingfisherOptionsInfo.swift
|
66
|
13050
|
//
// KingfisherOptionsInfo.swift
// Kingfisher
//
// Created by Wei Wang on 15/4/23.
//
// Copyright (c) 2017 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.
#if os(macOS)
import AppKit
#else
import UIKit
#endif
/**
* KingfisherOptionsInfo is a typealias for [KingfisherOptionsInfoItem]. You can use the enum of option item with value to control some behaviors of Kingfisher.
*/
public typealias KingfisherOptionsInfo = [KingfisherOptionsInfoItem]
let KingfisherEmptyOptionsInfo = [KingfisherOptionsInfoItem]()
/**
Items could be added into KingfisherOptionsInfo.
*/
public enum KingfisherOptionsInfoItem {
/// The associated value of this member should be an ImageCache object. Kingfisher will use the specified
/// cache object when handling related operations, including trying to retrieve the cached images and store
/// the downloaded image to it.
case targetCache(ImageCache)
/// The associated value of this member should be an ImageDownloader object. Kingfisher will use this
/// downloader to download the images.
case downloader(ImageDownloader)
/// Member for animation transition when using UIImageView. Kingfisher will use the `ImageTransition` of
/// this enum to animate the image in if it is downloaded from web. The transition will not happen when the
/// image is retrieved from either memory or disk cache by default. If you need to do the transition even when
/// the image being retrieved from cache, set `ForceTransition` as well.
case transition(ImageTransition)
/// Associated `Float` value will be set as the priority of image download task. The value for it should be
/// between 0.0~1.0. If this option not set, the default value (`NSURLSessionTaskPriorityDefault`) will be used.
case downloadPriority(Float)
/// If set, `Kingfisher` will ignore the cache and try to fire a download task for the resource.
case forceRefresh
/// If set, setting the image to an image view will happen with transition even when retrieved from cache.
/// See `Transition` option for more.
case forceTransition
/// If set, `Kingfisher` will only cache the value in memory but not in disk.
case cacheMemoryOnly
/// If set, `Kingfisher` will only try to retrieve the image from cache not from network.
case onlyFromCache
/// Decode the image in background thread before using.
case backgroundDecode
/// The associated value of this member will be used as the target queue of dispatch callbacks when
/// retrieving images from cache. If not set, `Kingfisher` will use main quese for callbacks.
case callbackDispatchQueue(DispatchQueue?)
/// The associated value of this member will be used as the scale factor when converting retrieved data to an image.
/// It is the image scale, instead of your screen scale. You may need to specify the correct scale when you dealing
/// with 2x or 3x retina images.
case scaleFactor(CGFloat)
/// Whether all the GIF data should be preloaded. Default it false, which means following frames will be
/// loaded on need. If true, all the GIF data will be loaded and decoded into memory. This option is mainly
/// used for back compatibility internally. You should not set it directly. `AnimatedImageView` will not preload
/// all data, while a normal image view (`UIImageView` or `NSImageView`) will load all data. Choose to use
/// corresponding image view type instead of setting this option.
case preloadAllGIFData
/// The `ImageDownloadRequestModifier` contained will be used to change the request before it being sent.
/// This is the last chance you can modify the request. You can modify the request for some customizing purpose,
/// such as adding auth token to the header, do basic HTTP auth or something like url mapping. The original request
/// will be sent without any modification by default.
case requestModifier(ImageDownloadRequestModifier)
/// Processor for processing when the downloading finishes, a processor will convert the downloaded data to an image
/// and/or apply some filter on it. If a cache is connected to the downloader (it happenes when you are using
/// KingfisherManager or the image extension methods), the converted image will also be sent to cache as well as the
/// image view. `DefaultImageProcessor.default` will be used by default.
case processor(ImageProcessor)
/// Supply an `CacheSerializer` to convert some data to an image object for
/// retrieving from disk cache or vice versa for storing to disk cache.
/// `DefaultCacheSerializer.default` will be used by default.
case cacheSerializer(CacheSerializer)
/// Keep the existing image while setting another image to an image view.
/// By setting this option, the placeholder image parameter of imageview extension method
/// will be ignored and the current image will be kept while loading or downloading the new image.
case keepCurrentImageWhileLoading
/// If set, Kingfisher will only load the first frame from a GIF file as a single image.
/// Loading a lot of GIFs may take too much memory. It will be useful when you want to display a
/// static preview of the first frame from a GIF image.
/// This option will be ignored if the target image is not GIF.
case onlyLoadFirstFrame
}
precedencegroup ItemComparisonPrecedence {
associativity: none
higherThan: LogicalConjunctionPrecedence
}
infix operator <== : ItemComparisonPrecedence
// This operator returns true if two `KingfisherOptionsInfoItem` enum is the same, without considering the associated values.
func <== (lhs: KingfisherOptionsInfoItem, rhs: KingfisherOptionsInfoItem) -> Bool {
switch (lhs, rhs) {
case (.targetCache(_), .targetCache(_)): return true
case (.downloader(_), .downloader(_)): return true
case (.transition(_), .transition(_)): return true
case (.downloadPriority(_), .downloadPriority(_)): return true
case (.forceRefresh, .forceRefresh): return true
case (.forceTransition, .forceTransition): return true
case (.cacheMemoryOnly, .cacheMemoryOnly): return true
case (.onlyFromCache, .onlyFromCache): return true
case (.backgroundDecode, .backgroundDecode): return true
case (.callbackDispatchQueue(_), .callbackDispatchQueue(_)): return true
case (.scaleFactor(_), .scaleFactor(_)): return true
case (.preloadAllGIFData, .preloadAllGIFData): return true
case (.requestModifier(_), .requestModifier(_)): return true
case (.processor(_), .processor(_)): return true
case (.cacheSerializer(_), .cacheSerializer(_)): return true
case (.keepCurrentImageWhileLoading, .keepCurrentImageWhileLoading): return true
case (.onlyLoadFirstFrame, .onlyLoadFirstFrame): return true
default: return false
}
}
extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
func firstMatchIgnoringAssociatedValue(_ target: Iterator.Element) -> Iterator.Element? {
return index { $0 <== target }.flatMap { self[$0] }
}
func removeAllMatchesIgnoringAssociatedValue(_ target: Iterator.Element) -> [Iterator.Element] {
return self.filter { !($0 <== target) }
}
}
public extension Collection where Iterator.Element == KingfisherOptionsInfoItem {
/// The target `ImageCache` which is used.
public var targetCache: ImageCache {
if let item = firstMatchIgnoringAssociatedValue(.targetCache(.default)),
case .targetCache(let cache) = item
{
return cache
}
return ImageCache.default
}
/// The `ImageDownloader` which is specified.
public var downloader: ImageDownloader {
if let item = firstMatchIgnoringAssociatedValue(.downloader(.default)),
case .downloader(let downloader) = item
{
return downloader
}
return ImageDownloader.default
}
/// Member for animation transition when using UIImageView.
public var transition: ImageTransition {
if let item = firstMatchIgnoringAssociatedValue(.transition(.none)),
case .transition(let transition) = item
{
return transition
}
return ImageTransition.none
}
/// A `Float` value set as the priority of image download task. The value for it should be
/// between 0.0~1.0.
public var downloadPriority: Float {
if let item = firstMatchIgnoringAssociatedValue(.downloadPriority(0)),
case .downloadPriority(let priority) = item
{
return priority
}
return URLSessionTask.defaultPriority
}
/// Whether an image will be always downloaded again or not.
public var forceRefresh: Bool {
return contains{ $0 <== .forceRefresh }
}
/// Whether the transition should always happen or not.
public var forceTransition: Bool {
return contains{ $0 <== .forceTransition }
}
/// Whether cache the image only in memory or not.
public var cacheMemoryOnly: Bool {
return contains{ $0 <== .cacheMemoryOnly }
}
/// Whether only load the images from cache or not.
public var onlyFromCache: Bool {
return contains{ $0 <== .onlyFromCache }
}
/// Whether the image should be decoded in background or not.
public var backgroundDecode: Bool {
return contains{ $0 <== .backgroundDecode }
}
/// Whether the image data should be all loaded at once if it is a GIF.
public var preloadAllGIFData: Bool {
return contains { $0 <== .preloadAllGIFData }
}
/// The queue of callbacks should happen from Kingfisher.
public var callbackDispatchQueue: DispatchQueue {
if let item = firstMatchIgnoringAssociatedValue(.callbackDispatchQueue(nil)),
case .callbackDispatchQueue(let queue) = item
{
return queue ?? DispatchQueue.main
}
return DispatchQueue.main
}
/// The scale factor which should be used for the image.
public var scaleFactor: CGFloat {
if let item = firstMatchIgnoringAssociatedValue(.scaleFactor(0)),
case .scaleFactor(let scale) = item
{
return scale
}
return 1.0
}
/// The `ImageDownloadRequestModifier` will be used before sending a download request.
public var modifier: ImageDownloadRequestModifier {
if let item = firstMatchIgnoringAssociatedValue(.requestModifier(NoModifier.default)),
case .requestModifier(let modifier) = item
{
return modifier
}
return NoModifier.default
}
/// `ImageProcessor` for processing when the downloading finishes.
public var processor: ImageProcessor {
if let item = firstMatchIgnoringAssociatedValue(.processor(DefaultImageProcessor.default)),
case .processor(let processor) = item
{
return processor
}
return DefaultImageProcessor.default
}
/// `CacheSerializer` to convert image to data for storing in cache.
public var cacheSerializer: CacheSerializer {
if let item = firstMatchIgnoringAssociatedValue(.cacheSerializer(DefaultCacheSerializer.default)),
case .cacheSerializer(let cacheSerializer) = item
{
return cacheSerializer
}
return DefaultCacheSerializer.default
}
/// Keep the existing image while setting another image to an image view.
/// Or the placeholder will be used while downloading.
public var keepCurrentImageWhileLoading: Bool {
return contains { $0 <== .keepCurrentImageWhileLoading }
}
public var onlyLoadFirstFrame: Bool {
return contains { $0 <== .onlyLoadFirstFrame }
}
}
|
mit
|
b3a4bfea655a2b68a5db14eb05d455ba
| 43.087838 | 159 | 0.698161 | 5.352748 | false | false | false | false |
calebd/swift
|
test/Constraints/closures.swift
|
1
|
18424
|
// RUN: %target-typecheck-verify-swift
func myMap<T1, T2>(_ array: [T1], _ fn: (T1) -> T2) -> [T2] {}
var intArray : [Int]
_ = myMap(intArray, { String($0) })
_ = myMap(intArray, { x -> String in String(x) } )
// Closures with too few parameters.
func foo(_ x: (Int, Int) -> Int) {}
foo({$0}) // expected-error{{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 1 was used in closure body}}
struct X {}
func mySort(_ array: [String], _ predicate: (String, String) -> Bool) -> [String] {}
func mySort(_ array: [X], _ predicate: (X, X) -> Bool) -> [X] {}
var strings : [String]
_ = mySort(strings, { x, y in x < y })
// Closures with inout arguments.
func f0<T, U>(_ t: T, _ f: (inout T) -> U) -> U {
var t2 = t
return f(&t2)
}
struct X2 {
func g() -> Float { return 0 }
}
_ = f0(X2(), {$0.g()})
// Autoclosure
func f1(f: @autoclosure () -> Int) { }
func f2() -> Int { }
f1(f: f2) // expected-error{{function produces expected type 'Int'; did you mean to call it with '()'?}}{{9-9=()}}
f1(f: 5)
// Ternary in closure
var evenOrOdd : (Int) -> String = {$0 % 2 == 0 ? "even" : "odd"}
// <rdar://problem/15367882>
func foo() {
not_declared({ $0 + 1 }) // expected-error{{use of unresolved identifier 'not_declared'}}
}
// <rdar://problem/15536725>
struct X3<T> {
init(_: (T) -> ()) {}
}
func testX3(_ x: Int) {
var x = x
_ = X3({ x = $0 })
_ = x
}
// <rdar://problem/13811882>
func test13811882() {
var _ : (Int) -> (Int, Int) = {($0, $0)}
var x = 1
var _ : (Int) -> (Int, Int) = {($0, x)}
x = 2
}
// <rdar://problem/21544303> QoI: "Unexpected trailing closure" should have a fixit to insert a 'do' statement
// <https://bugs.swift.org/browse/SR-3671>
func r21544303() {
var inSubcall = true
{
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
// This is a problem, but isn't clear what was intended.
var somethingElse = true {
} // expected-error {{computed property must have accessors specified}}
inSubcall = false
var v2 : Bool = false
v2 = inSubcall
{ // expected-error {{cannot call value of non-function type 'Bool'}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }}
}
}
// <https://bugs.swift.org/browse/SR-3671>
func SR3671() {
let n = 42
func consume(_ x: Int) {}
{ consume($0) }(42)
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-note {{did you mean to use a 'do' statement?}} {{3-3=do }} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ print($0) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ [n] in print(42) } // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) } { consume($0) }) // expected-note {{callee is here}}
{ (x: Int) in consume(x) }(42) // expected-warning {{braces here form a trailing closure separated from its callee by multiple newlines}} expected-error {{cannot call value of non-function type '()'}}
;
// This is technically a valid call, so nothing goes wrong until (42)
{ $0(3) }
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
{ $0(3) }
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
({ $0(42) })
{ [n] in consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
;
// Equivalent but more obviously unintended.
{ $0(3) } // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
({ $0(3) }) // expected-note {{callee is here}}
{ consume($0) }(42) // expected-error {{cannot call value of non-function type '()'}}
// expected-warning@-1 {{braces here form a trailing closure separated from its callee by multiple newlines}}
;
// Also a valid call (!!)
{ $0 { $0 } } { $0 { 1 } } // expected-error {{expression resolves to an unused function}}
consume(111)
}
// <rdar://problem/22162441> Crash from failing to diagnose nonexistent method access inside closure
func r22162441(_ lines: [String]) {
_ = lines.map { line in line.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
_ = lines.map { $0.fooBar() } // expected-error {{value of type 'String' has no member 'fooBar'}}
}
func testMap() {
let a = 42
[1,a].map { $0 + 1.0 } // expected-error {{binary operator '+' cannot be applied to operands of type 'Int' and 'Double'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: }}
}
// <rdar://problem/22414757> "UnresolvedDot" "in wrong phase" assertion from verifier
[].reduce { $0 + $1 } // expected-error {{missing argument for parameter #1 in call}}
// <rdar://problem/22333281> QoI: improve diagnostic when contextual type of closure disagrees with arguments
var _: () -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24=_ in }}
var _: (Int) -> Int = {0}
// expected-error @+1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}} {{24-24= _ in}}
var _: (Int) -> Int = { 0 }
// expected-error @+1 {{contextual type for closure argument list expects 2 arguments, which cannot be implicitly ignored}} {{29-29=_,_ in }}
var _: (Int, Int) -> Int = {0}
// expected-error @+1 {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
var _: (Int,Int) -> Int = {$0+$1+$2}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {$0+$1}
var _: () -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 2 were used in closure body}}
var _: (Int) -> Int = {a,b in 0}
// expected-error @+1 {{contextual closure type '(Int) -> Int' expects 1 argument, but 3 were used in closure body}}
var _: (Int) -> Int = {a,b,c in 0}
var _: (Int, Int) -> Int = {a in 0}
// expected-error @+1 {{contextual closure type '(Int, Int, Int) -> Int' expects 3 arguments, but 2 were used in closure body}}
var _: (Int, Int, Int) -> Int = {a, b in a+b}
// <rdar://problem/15998821> Fail to infer types for closure that takes an inout argument
func r15998821() {
func take_closure(_ x : (inout Int) -> ()) { }
func test1() {
take_closure { (a : inout Int) in
a = 42
}
}
func test2() {
take_closure { a in
a = 42
}
}
func withPtr(_ body: (inout Int) -> Int) {}
func f() { withPtr { p in return p } }
let g = { x in x = 3 }
take_closure(g)
}
// <rdar://problem/22602657> better diagnostics for closures w/o "in" clause
var _: (Int,Int) -> Int = {$0+$1+$2} // expected-error {{contextual closure type '(Int, Int) -> Int' expects 2 arguments, but 3 were used in closure body}}
// Crash when re-typechecking bodies of non-single expression closures
struct CC {}
func callCC<U>(_ f: (CC) -> U) -> () {}
func typeCheckMultiStmtClosureCrash() {
callCC { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{11-11= () -> Int in }}
_ = $0
return 1
}
}
// SR-832 - both these should be ok
func someFunc(_ foo: ((String) -> String)?,
bar: @escaping (String) -> String) {
let _: (String) -> String = foo != nil ? foo! : bar
let _: (String) -> String = foo ?? bar
}
// SR-1069 - Error diagnostic refers to wrong argument
class SR1069_W<T> {
func append<Key: AnyObject>(value: T, forKey key: Key) where Key: Hashable {}
}
class SR1069_C<T> { let w: SR1069_W<(AnyObject, T) -> ()> = SR1069_W() }
struct S<T> {
let cs: [SR1069_C<T>] = []
func subscribe<Object: AnyObject>(object: Object?, method: (Object, T) -> ()) where Object: Hashable {
let wrappedMethod = { (object: AnyObject, value: T) in }
// expected-error @+1 {{value of optional type 'Object?' not unwrapped; did you mean to use '!' or '?'?}}
cs.forEach { $0.w.append(value: wrappedMethod, forKey: object) }
}
}
// Make sure we cannot infer an () argument from an empty parameter list.
func acceptNothingToInt (_: () -> Int) {}
func testAcceptNothingToInt(ac1: @autoclosure () -> Int) {
acceptNothingToInt({ac1($0)})
// expected-error@-1{{contextual closure type '() -> Int' expects 0 arguments, but 1 was used in closure body}}
}
// <rdar://problem/23570873> QoI: Poor error calling map without being able to infer "U" (closure result inference)
struct Thing {
init?() {}
}
// This throws a compiler error
let things = Thing().map { thing in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{34-34=-> (Thing) }}
// Commenting out this makes it compile
_ = thing
return thing
}
// <rdar://problem/21675896> QoI: [Closure return type inference] Swift cannot find members for the result of inlined lambdas with branches
func r21675896(file : String) {
let x: String = { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{20-20= () -> String in }}
if true {
return "foo"
}
else {
return file
}
}().pathExtension
}
// <rdar://problem/19870975> Incorrect diagnostic for failed member lookups within closures passed as arguments ("(_) -> _")
func ident<T>(_ t: T) -> T {}
var c = ident({1.DOESNT_EXIST}) // error: expected-error {{value of type 'Int' has no member 'DOESNT_EXIST'}}
// <rdar://problem/20712541> QoI: Int/UInt mismatch produces useless error inside a block
var afterMessageCount : Int?
func uintFunc() -> UInt {}
func takeVoidVoidFn(_ a : () -> ()) {}
takeVoidVoidFn { () -> Void in
afterMessageCount = uintFunc() // expected-error {{cannot assign value of type 'UInt' to type 'Int?'}}
}
// <rdar://problem/19997471> Swift: Incorrect compile error when calling a function inside a closure
func f19997471(_ x: String) {}
func f19997471(_ x: Int) {}
func someGeneric19997471<T>(_ x: T) {
takeVoidVoidFn {
f19997471(x) // expected-error {{cannot invoke 'f19997471' with an argument list of type '(T)'}}
// expected-note @-1 {{overloads for 'f19997471' exist with these partially matching parameter lists: (String), (Int)}}
}
}
// <rdar://problem/20371273> Type errors inside anonymous functions don't provide enough information
func f20371273() {
let x: [Int] = [1, 2, 3, 4]
let y: UInt = 4
_ = x.filter { ($0 + y) > 42 } // expected-warning {{deprecated}}
}
// <rdar://problem/20921068> Swift fails to compile: [0].map() { _ in let r = (1,2).0; return r }
[0].map { // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{5-5=-> Int }}
_ in
let r = (1,2).0
return r
}
// <rdar://problem/21078316> Less than useful error message when using map on optional dictionary type
func rdar21078316() {
var foo : [String : String]?
var bar : [(String, String)]?
bar = foo.map { ($0, $1) } // expected-error {{contextual closure type '([String : String]) -> [(String, String)]' expects 1 argument, but 2 were used in closure body}}
}
// <rdar://problem/20978044> QoI: Poor diagnostic when using an incorrect tuple element in a closure
var numbers = [1, 2, 3]
zip(numbers, numbers).filter { $0.2 > 1 } // expected-error {{value of tuple type '(Int, Int)' has no member '2'}}
// <rdar://problem/20868864> QoI: Cannot invoke 'function' with an argument list of type 'type'
func foo20868864(_ callback: ([String]) -> ()) { }
func rdar20868864(_ s: String) {
var s = s
foo20868864 { (strings: [String]) in
s = strings // expected-error {{cannot assign value of type '[String]' to type 'String'}}
}
}
// <rdar://problem/22058555> crash in cs diags in withCString
func r22058555() {
var firstChar: UInt8 = 0
"abc".withCString { chars in
// FIXME https://bugs.swift.org/browse/SR-4836: was {{cannot assign value of type 'Int8' to type 'UInt8'}}
firstChar = chars[0] // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
}
}
// <rdar://problem/20789423> Unclear diagnostic for multi-statement closure with no return type
func r20789423() {
class C {
func f(_ value: Int) { }
}
let p: C
print(p.f(p)()) // expected-error {{cannot convert value of type 'C' to expected argument type 'Int'}}
let _f = { (v: Int) in // expected-error {{unable to infer complex closure return type; add explicit type to disambiguate}} {{23-23=-> String }}
print("a")
return "hi"
}
}
// Make sure that behavior related to allowing trailing closures to match functions
// with Any as a final parameter is the same after the changes made by SR-2505, namely:
// that we continue to select function that does _not_ have Any as a final parameter in
// presence of other possibilities.
protocol SR_2505_Initable { init() }
struct SR_2505_II : SR_2505_Initable {}
protocol P_SR_2505 {
associatedtype T: SR_2505_Initable
}
extension P_SR_2505 {
func test(it o: (T) -> Bool) -> Bool {
return o(T.self())
}
}
class C_SR_2505 : P_SR_2505 {
typealias T = SR_2505_II
func test(_ o: Any) -> Bool {
return false
}
func call(_ c: C_SR_2505) -> Bool {
// Note: no diagnostic about capturing 'self', because this is a
// non-escaping closure -- that's how we know we have selected
// test(it:) and not test(_)
return c.test { o in test(o) }
}
}
let _ = C_SR_2505().call(C_SR_2505())
// <rdar://problem/28909024> Returning incorrect result type from method invocation can result in nonsense diagnostic
extension Collection {
func r28909024(_ predicate: (Iterator.Element)->Bool) -> Index {
return startIndex
}
}
func fn_r28909024(n: Int) {
return (0..<10).r28909024 { // expected-error {{unexpected non-void return value in void function}}
_ in true
}
}
// SR-2994: Unexpected ambiguous expression in closure with generics
struct S_2994 {
var dataOffset: Int
}
class C_2994<R> {
init(arg: (R) -> Void) {}
}
func f_2994(arg: String) {}
func g_2994(arg: Int) -> Double {
return 2
}
C_2994<S_2994>(arg: { (r: S_2994) in f_2994(arg: g_2994(arg: r.dataOffset)) }) // expected-error {{cannot convert value of type 'Double' to expected argument type 'String'}}
let _ = { $0[$1] }(1, 1) // expected-error {{cannot subscript a value of incorrect or ambiguous type}}
let _ = { $0 = ($0 = {}) } // expected-error {{assigning a variable to itself}}
let _ = { $0 = $0 = 42 } // expected-error {{assigning a variable to itself}}
// https://bugs.swift.org/browse/SR-403
// The () -> T => () -> () implicit conversion was kicking in anywhere
// inside a closure result, not just at the top-level.
let mismatchInClosureResultType : (String) -> ((Int) -> Void) = {
(String) -> ((Int) -> Void) in
return { }
// expected-error@-1 {{contextual type for closure argument list expects 1 argument, which cannot be implicitly ignored}}
}
// SR-3520: Generic function taking closure with inout parameter can result in a variety of compiler errors or EXC_BAD_ACCESS
func sr3520_1<T>(_ g: (inout T) -> Int) {}
sr3520_1 { $0 = 1 } // expected-error {{cannot convert value of type '()' to closure result type 'Int'}}
func sr3520_2<T>(_ item: T, _ update: (inout T) -> Void) {
var x = item
update(&x)
}
var sr3250_arg = 42
sr3520_2(sr3250_arg) { $0 += 3 } // ok
// This test makes sure that having closure with inout argument doesn't crash with member lookup
struct S_3520 {
var number1: Int
}
func sr3520_set_via_closure<S, T>(_ closure: (inout S, T) -> ()) {}
sr3520_set_via_closure({ $0.number1 = $1 }) // expected-error {{type of expression is ambiguous without more context}}
// SR-1976/SR-3073: Inference of inout
func sr1976<T>(_ closure: (inout T) -> Void) {}
sr1976({ $0 += 2 }) // ok
// SR-3073: UnresolvedDotExpr in single expression closure
struct SR3073Lense<Whole, Part> {
let set: (inout Whole, Part) -> ()
}
struct SR3073 {
var number1: Int
func lenses() {
let _: SR3073Lense<SR3073, Int> = SR3073Lense(
set: { $0.number1 = $1 } // ok
)
}
}
// SR-3479: Segmentation fault and other error for closure with inout parameter
func sr3497_unfold<A, B>(_ a0: A, next: (inout A) -> B) {}
func sr3497() {
let _ = sr3497_unfold((0, 0)) { s in 0 } // ok
}
// SR-3758: Swift 3.1 fails to compile 3.0 code involving closures and IUOs
let _: ((Any?) -> Void) = { (arg: Any!) in }
// This example was rejected in 3.0 as well, but accepting it is correct.
let _: ((Int?) -> Void) = { (arg: Int!) in }
// rdar://30429709 - We should not attempt an implicit conversion from
// () -> T to () -> Optional<()>.
func returnsArray() -> [Int] { return [] }
returnsArray().flatMap { $0 }.flatMap { }
// expected-warning@-1 {{expression of type 'Int' is unused}}
// expected-warning@-2 {{result of call to 'flatMap' is unused}}
// rdar://problem/30271695
_ = ["hi"].flatMap { $0.isEmpty ? nil : $0 }
// rdar://problem/32432145 - compiler should emit fixit to remove "_ in" in closures if 0 parameters is expected
func r32432145(_ a: () -> ()) {}
r32432145 { _ in let _ = 42 } // Ok in Swift 3
r32432145 { _ in // Ok in Swift 3
print("answer is 42")
}
r32432145 { _,_ in
// expected-error@-1 {{contextual closure type '() -> ()' expects 0 arguments, but 2 were used in closure body}} {{13-19=}}
print("answer is 42")
}
|
apache-2.0
|
f275c566a4624a0933666192ad7291eb
| 33.696798 | 254 | 0.637538 | 3.363885 | false | false | false | false |
padawan/smartphone-app
|
MT_iOS/MT_iOS/Classes/Model/EntrySelectItem.swift
|
1
|
1075
|
//
// EntrySelectItem.swift
// MT_iOS
//
// Created by CHEEBOW on 2015/06/02.
// Copyright (c) 2015年 Six Apart, Ltd. All rights reserved.
//
import UIKit
class EntrySelectItem: BaseEntryItem {
var list = [String]()
var selected = ""
override init() {
super.init()
type = "select"
}
override func encodeWithCoder(aCoder: NSCoder) {
super.encodeWithCoder(aCoder)
aCoder.encodeObject(self.list, forKey: "list")
aCoder.encodeObject(self.selected, forKey: "selected")
}
required init(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.list = aDecoder.decodeObjectForKey("list") as! [String]
self.selected = aDecoder.decodeObjectForKey("selected") as! String
}
override func value()-> String {
if selected.isEmpty || list.count == 0 {
return ""
}
return selected
}
override func dispValue()-> String {
return self.value()
}
override func clear() {
selected = ""
}
}
|
mit
|
713cea4ca95c56a02fdbf4e206ff37b2
| 21.851064 | 74 | 0.587139 | 4.257937 | false | false | false | false |
AnneBlair/YYGRegular
|
YYGRegular/UIView.swift
|
1
|
1819
|
//
// UIView.swift
// shopDemo
//
// Created by 区块国际-yin on 2017/4/19.
// Copyright © 2017年 blog.aiyinyu.com. All rights reserved.
//
import UIKit
public extension UIView {
@IBInspectable public var cornerRadius: CGFloat {
get {
return layer.cornerRadius
}
set {
layer.cornerRadius = newValue
}
}
@IBInspectable public var shadowRadius: CGFloat {
get {
return layer.shadowRadius
}
set {
layer.shadowRadius = newValue
}
}
@IBInspectable public var shadowOpacity: Float {
get {
return layer.shadowOpacity
}
set {
layer.shadowOpacity = newValue
}
}
@IBInspectable public var shadowColor: UIColor? {
get {
return layer.shadowColor != nil ? UIColor(cgColor: layer.shadowColor!) : nil
}
set {
layer.shadowColor = newValue?.cgColor
}
}
@IBInspectable public var shadowOffset: CGSize {
get {
return layer.shadowOffset
}
set {
layer.shadowOffset = newValue
}
}
@IBInspectable public var zPosition: CGFloat {
get {
return layer.zPosition
}
set {
layer.zPosition = newValue
}
}
}
//public func viewController(forStoryboardName: String) -> UIViewController {
// return UIStoryboard(name: forStoryboardName, bundle: nil).instantiateInitialViewController()!
//}
//
//class TemplateImageView: UIImageView {
// @IBInspectable var templateImage: UIImage? {
// didSet {
// image = templateImage?.withRenderingMode(.alwaysTemplate)
// }
// }
//}
|
mit
|
caf5897001e63a69b0a69ca77a2c220d
| 22.153846 | 99 | 0.547619 | 5.073034 | false | false | false | false |
TrustWallet/trust-wallet-ios
|
Trust/Tokens/ViewModels/EditTokenViewModel.swift
|
1
|
2150
|
// Copyright DApps Platform Inc. All rights reserved.
import Foundation
import UIKit
import Moya
import RealmSwift
final class EditTokenViewModel {
let network: NetworkProtocol
let storage: TokensDataStore
private var tokens: Results<TokenObject> {
return storage.realm.objects(TokenObject.self).sorted(byKeyPath: "order", ascending: true)
}
var localSet = Set<TokenObject>()
init(
network: NetworkProtocol,
storage: TokensDataStore
) {
self.network = network
self.storage = storage
self.localSet = Set(tokens)
}
var title: String {
return R.string.localizable.tokens()
}
var searchPlaceholder: String {
return R.string.localizable.editTokensSearchBarPlaceholderTitle()
}
var numberOfSections: Int {
return 1
}
func numberOfRowsInSection(_ section: Int) -> Int {
return tokens.count
}
func token(for indexPath: IndexPath) -> (token: TokenObject, local: Bool) {
return (tokens[indexPath.row], true)
}
func canEdit(for path: IndexPath) -> Bool {
return tokens[path.row].isCustom
}
func searchNetwork(token: String, completion: (([TokenObject]) -> Void)?) {
network.search(query: token).done { [weak self] tokens in
var filterSet = Set<TokenObject>()
if let localSet = self?.localSet {
filterSet = localSet
}
tokens.forEach {
$0.isCustom = true
$0.isDisabled = false
}
completion?(tokens.filter { !filterSet.contains($0) })
}.catch { _ in }
}
func searchLocal(token searchText: String?) -> [TokenObject] {
let text = searchText?.lowercased() ?? ""
let filteredTokens = storage.objects.filter { $0.name.lowercased().contains(text) || $0.symbol.lowercased().contains(text) }
return filteredTokens
}
func updateToken(indexPath: IndexPath, action: TokenAction) {
let token = self.token(for: indexPath)
self.storage.update(tokens: [token.token], action: action)
}
}
|
gpl-3.0
|
3d527e190aca16f79d86e04f0b9a89cc
| 26.922078 | 132 | 0.617674 | 4.405738 | false | false | false | false |
xedin/swift
|
test/PlaygroundTransform/high_performance.swift
|
9
|
1494
|
// RUN: %empty-directory(%t)
// RUN: cp %s %t/main.swift
// RUN: %target-build-swift -force-single-frontend-invocation -module-name PlaygroundSupport -emit-module-path %t/PlaygroundSupport.swiftmodule -parse-as-library -c -o %t/PlaygroundSupport.o %S/Inputs/SilentPCMacroRuntime.swift %S/Inputs/PlaygroundsRuntime.swift
// RUN: %target-build-swift -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main
// RUN: %target-run %t/main | %FileCheck %s
// RUN: %target-build-swift -Xfrontend -pc-macro -Xfrontend -playground -Xfrontend -playground-high-performance -o %t/main2 -I=%t %t/PlaygroundSupport.o %t/main.swift
// RUN: %target-codesign %t/main2
// RUN: %target-run %t/main2 | %FileCheck %s
// REQUIRES: executable_test
import PlaygroundSupport
var a = true
if (a) {
5
} else {
7
}
for i in 0..<3 {
i
}
// CHECK: [{{.*}}] __builtin_log[a='true']
// CHECK-NEXT: [{{.*}}] __builtin_log[='5']
// CHECK-NEXT: [{{.*}}] __builtin_log[='0']
// CHECK-NEXT: [{{.*}}] __builtin_log[='1']
// CHECK-NEXT: [{{.*}}] __builtin_log[='2']
var b = true
for i in 0..<3 {
i
continue
}
// CHECK-NEXT: [{{.*}}] __builtin_log[b='true']
// CHECK-NEXT: [{{.*}}] __builtin_log[='0']
// CHECK-NEXT: [{{.*}}] __builtin_log[='1']
// CHECK-NEXT: [{{.*}}] __builtin_log[='2']
var c = true
for i in 0..<3 {
i
break
}
// CHECK-NEXT: [{{.*}}] __builtin_log[c='true']
// CHECK-NEXT: [{{.*}}] __builtin_log[='0']
|
apache-2.0
|
0cb75754692078a40e6805292a0ddd94
| 31.478261 | 262 | 0.62249 | 3.04277 | false | false | false | false |
koher/CGPointVector
|
Tests/CGPointVectorTests/CGSizeTests.swift
|
2
|
7689
|
import XCTest
import CGPointVector
class CGSizeTests: XCTestCase {
let torelance: CGFloat = 1.0e-5;
func testisNearlyEqual() {
XCTAssertFalse(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 0.5, height: 2.0), epsilon: 0.5))
XCTAssertTrue(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 0.51, height: 2.0), epsilon: 0.5))
XCTAssertTrue(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 1.49, height: 2.0), epsilon: 0.5))
XCTAssertFalse(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 0.4, height: 2.0), epsilon: 0.5))
XCTAssertFalse(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 1.0, height: 1.0), epsilon: 1.0))
XCTAssertTrue(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 1.0, height: 1.1), epsilon: 1.0))
XCTAssertTrue(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 1.0, height: 2.9), epsilon: 1.0))
XCTAssertFalse(CGSize(width: 1.0, height: 2.0).isNearlyEqual(to: CGSize(width: 1.0, height: 3.0), epsilon: 1.0))
}
func testLength() {
XCTAssertEqual(CGSize(width: 3.0, height: -4.0).length, 5.0, accuracy: torelance)
XCTAssertEqual(CGSize(width: .greatestFiniteMagnitude, height: 0.0).length, .greatestFiniteMagnitude)
XCTAssertEqual(CGSize(width: 0.0, height: .leastNonzeroMagnitude).length, .leastNonzeroMagnitude)
}
func testSquareLength() {
XCTAssertEqual(CGSize(width: 3.0, height: -4.0).squareLength, 25.0, accuracy: torelance)
}
func testUnit() {
XCTAssertTrue(CGSize(width: 3.0, height: -4.0).unit.isNearlyEqual(to: CGSize(width: 0.6, height: -0.8), epsilon: torelance))
}
func testPhase() {
XCTAssertEqual(CGSize(width: 1.0, height: sqrt(3)).phase, CGFloat.pi / 3, accuracy: torelance)
}
func testDistance() {
XCTAssertEqual(CGSize(width: 1.0, height: 2.0).distance(from: CGSize(width: -3.0, height: 5.0)), 5.0, accuracy: torelance)
}
func testSquareDistance() {
XCTAssertEqual(CGSize(width: 1.0, height: 2.0).squareDistance(from: CGSize(width: -3.0, height: 5.0)), 25.0, accuracy: torelance)
}
func testAngle() {
XCTAssertEqual(CGSize(width: 1.0, height: 0.0).angle(from: CGSize(width: sqrt(3.0), height: 1.0)), CGFloat.pi / 6, accuracy: torelance)
XCTAssertEqual(CGSize(width: 1.0, height: 0.0).angle(from: .zero), 0.0, accuracy: torelance)
XCTAssertEqual(CGSize.zero.angle(from: CGSize(width: 0.0, height: 1.0)), 0.0, accuracy: torelance)
XCTAssertEqual(CGSize.zero.angle(from: .zero), 0.0, accuracy: torelance)
}
func testCos() {
XCTAssertEqual(CGSize(width: 1.0, height: 0.0).cos(from: CGSize(width: 1.0, height: sqrt(3.0))), 0.5, accuracy: torelance)
XCTAssertEqual(CGSize(width: 1.0, height: 0.0).cos(from: .zero), 1.0, accuracy: torelance)
XCTAssertEqual(CGSize.zero.cos(from: CGSize(width: 0.0, height: 1.0)), 1.0, accuracy: torelance)
XCTAssertEqual(CGSize.zero.cos(from: .zero), 1.0, accuracy: torelance)
}
func testDot() {
XCTAssertEqual(CGSize(width: 1.0, height: 2.0).dot(CGSize(width: -3.0, height: 4.0)), 5.0, accuracy: torelance)
}
func testDescription() {
XCTAssertEqual(CGSize(width: 1.0, height: 2.0).description, "(1.0, 2.0)")
}
func testPrefixPlus() {
XCTAssertTrue((+CGSize(width: 1.0, height: -2.0)).isNearlyEqual(to: CGSize(width: 1.0, height: -2.0), epsilon: torelance))
}
func testNegate() {
XCTAssertTrue((-CGSize(width: 1.0, height: -2.0)).isNearlyEqual(to: CGSize(width: -1.0, height: 2.0), epsilon: torelance))
}
func testAdd() {
XCTAssertTrue((CGSize(width: 1.0, height: 2.0) + CGSize(width: 3.0, height: -4.0)).isNearlyEqual(to: CGSize(width: 4.0, height: -2.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 1.0, height: 2.0) + CGPoint(x: 3.0, y: -4.0)).isNearlyEqual(to: CGPoint(x: 4.0, y: -2.0), epsilon: torelance))
}
func testSubtract() {
XCTAssertTrue((CGSize(width: 3.0, height: 2.0) - CGSize(width: 1.0, height: 4.0)).isNearlyEqual(to: CGSize(width: 2.0, height: -2.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 3.0, height: 2.0) - CGPoint(x: 1.0, y: 4.0)).isNearlyEqual(to: CGPoint(x: 2.0, y: -2.0), epsilon: torelance))
}
func testMultiply() {
XCTAssertTrue((CGSize(width: 2.0, height: 3.0) * CGSize(width: 5.0, height: 7.0)).isNearlyEqual(to: CGSize(width: 10.0, height: 21.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 2.0, height: 3.0) * CGPoint(x: 5.0, y: 7.0)).isNearlyEqual(to: CGPoint(x: 10.0, y: 21.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 1.0, height: -2.0) * 3.0).isNearlyEqual(to: CGSize(width: 3.0, height: -6.0), epsilon: torelance))
XCTAssertTrue((3.0 * CGSize(width: 1.0, height: -2.0)).isNearlyEqual(to: CGSize(width: 3.0, height: -6.0), epsilon: torelance))
}
func testDivide() {
XCTAssertTrue((CGSize(width: 8.0, height: 27.0) / CGSize(width: 2.0, height: 3.0)).isNearlyEqual(to: CGSize(width: 4.0, height: 9.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 8.0, height: 27.0) / CGPoint(x: 2.0, y: 3.0)).isNearlyEqual(to: CGPoint(x: 4.0, y: 9.0), epsilon: torelance))
XCTAssertTrue((CGSize(width: 8.0, height: -2.0) / 4.0).isNearlyEqual(to: CGSize(width: 2.0, height: -0.5), epsilon: torelance))
}
func testAdditionAssignment() {
var a = CGSize(width: 1.0, height: 2.0)
a += CGSize(width: 3.0, height: -4.0)
XCTAssertTrue(a.isNearlyEqual(to: CGSize(width: 1.0, height: 2.0)
+ CGSize(width: 3.0, height: -4.0), epsilon: torelance))
}
func testSuntractionAssignment() {
var a = CGSize(width: 3.0, height: 2.0)
a -= CGSize(width: 1.0, height: 4.0)
XCTAssertTrue(a.isNearlyEqual(to: CGSize(width: 3.0, height: 2.0)
- CGSize(width: 1.0, height: 4.0), epsilon: torelance))
}
func testMultiplicationAssignment() {
var a = CGSize(width: 1.0, height: -2.0)
a *= 3.0
XCTAssertTrue(a.isNearlyEqual(to: CGSize(width: 1.0, height: -2.0) * 3, epsilon: torelance))
}
func testDivisionAssignment() {
var a = CGSize(width: 8.0, height: -2.0)
a /= 4.0
XCTAssertTrue(a.isNearlyEqual(to: CGSize(width: 8.0, height: -2.0) / 4.0, epsilon: torelance))
}
static var allTests : [(String, (CGSizeTests) -> () throws -> Void)] {
return [
("testisNearlyEqual", testisNearlyEqual),
("testLength", testLength),
("testSquareLength", testSquareLength),
("testUnit", testUnit),
("testPhase", testPhase),
("testDistance", testDistance),
("testSquareDistance", testSquareDistance),
("testAngle", testAngle),
("testCos", testCos),
("testDot", testDot),
("testDescription", testDescription),
("testPrefixPlus", testPrefixPlus),
("testNegate", testNegate),
("testAdd", testAdd),
("testSubtract", testSubtract),
("testMultiply", testMultiply),
("testDivide", testDivide),
("testAdditionAssignment", testAdditionAssignment),
("testSuntractionAssignment", testSuntractionAssignment),
("testMultiplicationAssignment", testMultiplicationAssignment),
("testDivisionAssignment", testDivisionAssignment),
]
}
}
|
mit
|
156fc9f8be016d29cd5b2a4f4a74b003
| 50.604027 | 163 | 0.617115 | 3.321382 | false | true | false | false |
tensorflow/swift-apis
|
Sources/TensorFlow/Core/ArrayOps.swift
|
1
|
4819
|
// Copyright 2019 The TensorFlow Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import CTensorFlow
extension _Raw {
/// Saves tensors in V2 checkpoint format.
///
/// By default, saves the named tensors in full. If the caller wishes to save specific slices
/// of full tensors, "shape_and_slices" should be non-empty strings and correspondingly
/// well-formed.
///
/// - Parameters:
/// - prefix: Must have a single element. The prefix of the V2 checkpoint to which we write
/// the tensors.
/// - tensor_names: shape {N}. The names of the tensors to be saved.
/// - shape_and_slices: shape {N}. The slice specs of the tensors to be saved. Empty strings
/// indicate that they are non-partitioned tensors.
/// - tensors: `N` tensors to save.
@inlinable
public static func saveV2(
prefix: StringTensor,
tensorNames: StringTensor,
shapeAndSlices: StringTensor,
tensors: [AnyTensor]
) {
let s: CTFStatus = TF_NewStatus()
defer { TF_DeleteStatus(s) }
let op: CTFEOp = TFE_NewOp(_ExecutionContext.global.eagerContext, "SaveV2", s)
defer { TFE_DeleteOp(op) }
let _ = _TFCOpAddInputFromTensorGroup(op, prefix, s)
let _ = _TFCOpAddInputFromTensorGroup(op, tensorNames, s)
let _ = _TFCOpAddInputFromTensorGroup(op, shapeAndSlices, s)
let _ = _TFCOpAddInputFromAnyTensors(op, tensors, s)
let _ = _TFCOpSetAttrTypeArray(op, "dtypes", tensors.map { $0._tensorFlowDataType })
// Execute the op.
var count: Int32 = 0
var unused: CTensorHandle?
_TFCOpSetDeviceFromScope(op, s)
checkOk(s)
_TFCEagerExecute(op, &unused, &count, s)
checkOk(s)
TFE_DeleteOp(op)
TF_DeleteStatus(s)
}
/// Restores tensors from a V2 checkpoint.
///
/// For backward compatibility with the V1 format, this Op currently allows restoring from a V1
/// checkpoint as well:
/// - This Op first attempts to find the V2 index file pointed to by "prefix", and if found
/// proceed to read it as a V2 checkpoint;
/// - Otherwise the V1 read path is invoked.
/// Relying on this behavior is not recommended, as the ability to fall back to read V1 might be
/// deprecated and eventually removed.
///
/// By default, restores the named tensors in full. If the caller wishes to restore specific
/// slices of stored tensors, "shape_and_slices" should be non-empty strings and correspondingly
/// well-formed.
///
/// Callers must ensure all the named tensors are indeed stored in the checkpoint.
///
/// - Parameters:
/// - prefix: Must have a single element. The prefix of a V2 checkpoint.
/// - tensor_names: shape {N}. The names of the tensors to be restored.
/// - shape_and_slices: shape {N}. The slice specs of the tensors to be restored. Empty
/// strings indicate that they are non-partitioned tensors.
///
/// - Attr dtypes: shape {N}. The list of expected dtype for the tensors. Must match those
/// stored in the checkpoint.
///
/// - Output tensors: shape {N}. The restored tensors, whose shapes are read from the
/// checkpoint directly.
@inlinable
public static func restoreV2(
prefix: StringTensor,
tensorNames: StringTensor,
shapeAndSlices: StringTensor,
dtypes: [TensorDataType]
) -> [AnyTensor] {
let s: CTFStatus = TF_NewStatus()
defer { TF_DeleteStatus(s) }
let op: CTFEOp = TFE_NewOp(_ExecutionContext.global.eagerContext, "RestoreV2", s)
defer { TFE_DeleteOp(op) }
let _ = _TFCOpAddInputFromTensorGroup(op, prefix, s)
let _ = _TFCOpAddInputFromTensorGroup(op, tensorNames, s)
let _ = _TFCOpAddInputFromTensorGroup(op, shapeAndSlices, s)
let _ = _TFCOpSetAttrTypeArray(op, "dtypes", dtypes)
var count: Int32 = Int32(dtypes.count)
let buffer: UnsafeMutablePointer<CTensorHandle> =
UnsafeMutablePointer.allocate(capacity: Int(count))
defer { buffer.deallocate() }
_TFCOpSetDeviceFromScope(op, s)
_TFCEagerExecute(op, UnsafeMutablePointer<CTensorHandle?>(buffer), &count, s)
checkOk(s)
var out: [AnyTensor] = []
var cursor = buffer
for type in dtypes {
out.append(makeTensor(dataType: type, owning: cursor.pointee))
cursor = cursor.advanced(by: 1)
}
return out
}
}
|
apache-2.0
|
fa678cdee83aae4c5f71eb4eb83232c7
| 39.838983 | 98 | 0.685619 | 3.729876 | false | false | false | false |
natecook1000/swift
|
test/attr/attr_specialize.swift
|
1
|
14390
|
// RUN: %target-typecheck-verify-swift
// RUN: %target-swift-ide-test -print-ast-typechecked -source-filename=%s -disable-objc-attr-requires-foundation-module | %FileCheck %s
struct S<T> {}
public protocol P {
}
extension Int: P {
}
public protocol ProtocolWithDep {
associatedtype Element
}
public class C1 {
}
class Base {}
class Sub : Base {}
class NonSub {}
// Specialize freestanding functions with the correct number of concrete types.
// ----------------------------------------------------------------------------
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
// CHECK: @_specialize(exported: false, kind: full, where T == S<Int>)
@_specialize(where T == S<Int>)
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}},
// expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}}
@_specialize(where T == T1) // expected-error{{use of undeclared type 'T1'}}
public func oneGenericParam<T>(_ t: T) -> T {
return t
}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Int)
@_specialize(where T == Int, U == Int)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'U' in '_specialize' attribute}}
public func twoGenericParams<T, U>(_ t: T, u: U) -> (T, U) {
return (t, u)
}
@_specialize(where T == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'nonGenericParam(x:)'}}
func nonGenericParam(x: Int) {}
// Specialize contextual types.
// ----------------------------
class G<T> {
// CHECK: @_specialize(exported: false, kind: full, where T == Int)
@_specialize(where T == Int)
@_specialize(where T == T) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
@_specialize(where T == S<T>) // expected-error{{Only concrete type same-type requirements are supported by '_specialize' attribute}}
@_specialize(where T == Int, U == Int) // expected-error{{use of undeclared type 'U'}}
// expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}}
func noGenericParams() {}
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == Float)
@_specialize(where T == Int, U == Float)
// CHECK: @_specialize(exported: false, kind: full, where T == Int, U == S<Int>)
@_specialize(where T == Int, U == S<Int>)
@_specialize(where T == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error {{Missing constraint for 'U' in '_specialize' attribute}}
func oneGenericParam<U>(_ t: T, u: U) -> (U, T) {
return (u, t)
}
}
// Specialize with requirements.
// -----------------------------
protocol Thing {}
struct AThing : Thing {}
// CHECK: @_specialize(exported: false, kind: full, where T == AThing)
@_specialize(where T == AThing)
@_specialize(where T == Int) // expected-error{{same-type constraint type 'Int' does not conform to required protocol 'Thing'}}
func oneRequirement<T : Thing>(_ t: T) {}
protocol HasElt {
associatedtype Element
}
struct IntElement : HasElt {
typealias Element = Int
}
struct FloatElement : HasElt {
typealias Element = Float
}
@_specialize(where T == FloatElement)
@_specialize(where T == IntElement) // expected-error{{'T.Element' cannot be equal to both 'IntElement.Element' (aka 'Int') and 'Float'}}
func sameTypeRequirement<T : HasElt>(_ t: T) where T.Element == Float {}
@_specialize(where T == Sub)
@_specialize(where T == NonSub) // expected-error{{'T' requires that 'NonSub' inherit from 'Base'}}
func superTypeRequirement<T : Base>(_ t: T) {}
@_specialize(where X:_Trivial(8), Y == Int) // expected-error{{trailing 'where' clause in '_specialize' attribute of non-generic function 'requirementOnNonGenericFunction(x:y:)'}}
public func requirementOnNonGenericFunction(x: Int, y: Int) {
}
@_specialize(where Y == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
public func missingRequirement<X:P, Y>(x: X, y: Y) {
}
@_specialize(where) // expected-error{{expected identifier for type name}}
@_specialize() // expected-error{{expected a parameter label or a where clause in '_specialize' attribute}} expected-error{{expected declaration}}
public func funcWithEmptySpecializeAttr<X: P, Y>(x: X, y: Y) {
}
@_specialize(where X:_Trivial(8), Y:_Trivial(32), Z == Int) // expected-error{{use of undeclared type 'Z'}}
// expected-error@-1{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y:_Trivial(32, 4))
@_specialize(where X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
@_specialize(where Y:_Trivial(32)) // expected-error {{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
@_specialize(where Y: MyClass) // expected-error{{use of undeclared type 'MyClass'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}}
// expected-error@-1{{Only conformances to protocol types are supported by '_specialize' attribute}}
@_specialize(where X:_Trivial(8), Y == Int)
@_specialize(where X == Int, Y == Int)
@_specialize(where X == Int, X == Int) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 1, but expected 2)}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
// expected-warning@-1{{redundant same-type constraint 'X' == 'Int'}}
// expected-note@-2{{same-type constraint 'X' == 'Int' written here}}
@_specialize(where Y:_Trivial(32), X == Float)
@_specialize(where X1 == Int, Y1 == Int) // expected-error{{use of undeclared type 'X1'}} expected-error{{use of undeclared type 'Y1'}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 2)}} expected-error{{Missing constraint for 'X' in '_specialize' attribute}} expected-error{{Missing constraint for 'Y' in '_specialize' attribute}}
// expected-error@-1 2{{Only one concrete type should be used in the same-type requirement in '_specialize' attribute}}
public func funcWithTwoGenericParameters<X, Y>(x: X, y: Y) {
}
@_specialize(where X == Int, Y == Int)
@_specialize(exported: true, where X == Int, Y == Int)
@_specialize(exported: false, where X == Int, Y == Int)
@_specialize(exported: false where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(exported: yes, where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(exported: , where X == Int, Y == Int) // expected-error{{expected a boolean true or false value in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: partial, where X == Int)
@_specialize(kind: full, where X == Int, Y == Int)
@_specialize(kind: any, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: false, where X == Int, Y == Int) // expected-error{{expected 'partial' or 'full' as values of the 'kind' parameter in '_specialize' attribute}}
@_specialize(kind: partial where X == Int, Y == Int) // expected-error{{missing ',' in '_specialize' attribute}}
@_specialize(kind: partial, where X == Int, Y == Int)
@_specialize(kind: , where X == Int, Y == Int)
@_specialize(exported: true, kind: partial, where X == Int, Y == Int)
@_specialize(exported: true, exported: true, where X == Int, Y == Int) // expected-error{{parameter 'exported' was already defined in '_specialize' attribute}}
@_specialize(kind: partial, exported: true, where X == Int, Y == Int)
@_specialize(kind: partial, kind: partial, where X == Int, Y == Int) // expected-error{{parameter 'kind' was already defined in '_specialize' attribute}}
@_specialize(where X == Int, Y == Int, exported: true, kind: partial) // expected-error{{use of undeclared type 'exported'}} expected-error{{use of undeclared type 'kind'}} expected-error{{use of undeclared type 'partial'}} expected-error{{expected type}}
// expected-error@-1 2{{Only conformances to protocol types are supported by '_specialize' attribute}}
public func anotherFuncWithTwoGenericParameters<X: P, Y>(x: X, y: Y) {
}
@_specialize(where T: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}}
@_specialize(where T: Int) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}}
@_specialize(where T: S1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}}
@_specialize(where T: C1) // expected-error{{Only conformances to protocol types are supported by '_specialize' attribute}}
@_specialize(where Int: P) // expected-error{{Only same-type and layout requirements are supported by '_specialize' attribute}} expected-error{{too few type parameters are specified in '_specialize' attribute (got 0, but expected 1)}} expected-error{{Missing constraint for 'T' in '_specialize' attribute}}
func funcWithForbiddenSpecializeRequirement<T>(_ t: T) {
}
@_specialize(where T: _Trivial(32), T: _Trivial(64), T: _Trivial, T: _RefCountedObject)
// expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_Trivial(32)'}}
// expected-error@-2{{generic parameter 'T' has conflicting constraints '_RefCountedObject' and '_Trivial(32)'}}
// expected-warning@-3{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-4 3{{constraint 'T' : '_Trivial(32)' written here}}
@_specialize(where T: _Trivial, T: _Trivial(64))
// expected-warning@-1{{redundant constraint 'T' : '_Trivial'}}
// expected-note@-2 1{{constraint 'T' : '_Trivial(64)' written here}}
@_specialize(where T: _RefCountedObject, T: _NativeRefCountedObject)
// expected-warning@-1{{redundant constraint 'T' : '_RefCountedObject'}}
// expected-note@-2 1{{constraint 'T' : '_NativeRefCountedObject' written here}}
@_specialize(where Array<T> == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
@_specialize(where T.Element == Int) // expected-error{{Only requirements on generic parameters are supported by '_specialize' attribute}}
public func funcWithComplexSpecializeRequirements<T: ProtocolWithDep>(t: T) -> Int {
return 55555
}
public protocol Proto: class {
}
@_specialize(where T: _RefCountedObject)
@_specialize(where T: _Trivial)
// expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial' and '_NativeClass'}}
@_specialize(where T: _Trivial(64))
// expected-error@-1{{generic parameter 'T' has conflicting constraints '_Trivial(64)' and '_NativeClass'}}
public func funcWithABaseClassRequirement<T>(t: T) -> Int where T: C1 {
return 44444
}
public struct S1 {
}
@_specialize(exported: false, where T == Int64)
public func simpleGeneric<T>(t: T) -> T {
return t
}
@_specialize(exported: true, where S: _Trivial(64))
// Check that any bitsize size is OK, not only powers of 8.
@_specialize(where S: _Trivial(60))
@_specialize(exported: true, where S: _RefCountedObject)
@inline(never)
public func copyValue<S>(_ t: S, s: inout S) -> Int64 where S: P{
return 1
}
@_specialize(exported: true, where S: _Trivial)
@_specialize(exported: true, where S: _Trivial(64))
@_specialize(exported: true, where S: _Trivial(32))
@_specialize(exported: true, where S: _RefCountedObject)
@_specialize(exported: true, where S: _NativeRefCountedObject)
@_specialize(exported: true, where S: _Class)
@_specialize(exported: true, where S: _NativeClass)
@inline(never)
public func copyValueAndReturn<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
struct OuterStruct<S> {
struct MyStruct<T> {
@_specialize(where T == Int, U == Float) // expected-error{{too few type parameters are specified in '_specialize' attribute (got 2, but expected 3)}} expected-error{{Missing constraint for 'S' in '_specialize' attribute}}
public func foo<U>(u : U) {
}
@_specialize(where T == Int, U == Float, S == Int)
public func bar<U>(u : U) {
}
}
}
// Check _TrivialAtMostN constraints.
@_specialize(exported: true, where S: _TrivialAtMost(64))
@inline(never)
public func copy2<S>(_ t: S, s: inout S) -> S where S: P{
return s
}
// Check missing alignment.
@_specialize(where S: _Trivial(64, )) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
// Check non-numeric size.
@_specialize(where S: _Trivial(Int)) // expected-error{{expected non-negative size to be specified in layout constraint}}
// Check non-numeric alignment.
@_specialize(where S: _Trivial(64, X)) // expected-error{{expected non-negative alignment to be specified in layout constraint}}
@inline(never)
public func copy3<S>(_ s: S) -> S {
return s
}
public func funcWithWhereClause<T>(t: T) where T:P, T: _Trivial(64) { // expected-error{{layout constraints are only allowed inside '_specialize' attributes}}
}
// rdar://problem/29333056
public protocol P1 {
associatedtype DP1
associatedtype DP11
}
public protocol P2 {
associatedtype DP2 : P1
}
public struct H<T> {
}
public struct MyStruct3 : P1 {
public typealias DP1 = Int
public typealias DP11 = H<Int>
}
public struct MyStruct4 : P2 {
public typealias DP2 = MyStruct3
}
@_specialize(where T==MyStruct4)
public func foo<T: P2>(_ t: T) where T.DP2.DP11 == H<T.DP2.DP1> {
}
|
apache-2.0
|
675ab814f9d59ef89d41dc0ded9bd23a
| 50.209964 | 386 | 0.699653 | 3.715466 | false | false | false | false |
PetroccoCo/Lock.iOS-OSX
|
Examples/Firebase/Firebase.Swift/FirebaseExample/ViewController.swift
|
3
|
4680
|
// ViewController.swift
//
// Copyright (c) 2014 Auth0 (http://auth0.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
let FirebaseURLString = "https://sizzling-heat-5516.firebaseio.com/"
class ViewController: UIViewController {
@IBOutlet weak var firstStepLabel: UILabel!
@IBOutlet weak var seconStepLabel: UILabel!
@IBOutlet weak var thirdStepLabel: UILabel!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let idToken = A0SimpleKeychain().stringForKey("id_token")
self.firstStepLabel.text = idToken == nil ? nil : "Auth0 JWT \(idToken)"
if idToken == nil {
self.showLogin()
}
}
@IBAction func logout(sender: AnyObject) {
A0SimpleKeychain().clearAll()
self.showLogin()
self.seconStepLabel.text = nil
self.thirdStepLabel.text = nil
}
@IBAction func fetchFromFirebase(sender: AnyObject) {
let button = sender as! UIButton
self.setInProgress(true, button: button)
let client = A0APIClient.sharedClient()
let jwt = A0SimpleKeychain().stringForKey("id_token")
let parameters = A0AuthParameters.newWithDictionary([
A0ParameterAPIType: "firebase",
"id_token": jwt
])
client.fetchDelegationTokenWithParameters(parameters,
success: { (response) -> Void in
let credentials = response as! Dictionary<String, AnyObject>
let firebaseToken = credentials["id_token"] as? String
self.seconStepLabel.text = "Firebase JWT \(firebaseToken!)"
println("Obtained Firebase credentials \(credentials)")
let ref = Firebase(url: FirebaseURLString)
ref.authWithCustomToken(firebaseToken, withCompletionBlock: { (error, data) -> () in
if error == nil {
self.thirdStepLabel.text = "\(data)"
println("Obtained data \(data)")
} else {
self.thirdStepLabel.text = error.localizedDescription
println("Failed to auth with Firebase. Error \(error)")
}
self.setInProgress(false, button: button)
})
},
failure: { (error) -> Void in
self.seconStepLabel.text = error.localizedDescription
println("An error ocurred \(error)")
self.setInProgress(false, button: button)
})
}
func setInProgress(inProgress: Bool, button: UIButton) {
if inProgress {
button.enabled = false
self.activityIndicator.startAnimating()
self.activityIndicator.hidden = false
self.seconStepLabel.text = nil
self.thirdStepLabel.text = nil
} else {
button.enabled = true
self.activityIndicator.stopAnimating()
}
}
func showLogin() {
let lock = A0LockViewController()
lock.closable = false
lock.onAuthenticationBlock = {(profile: A0UserProfile!, token: A0Token!) -> () in
A0SimpleKeychain().setString(token.idToken, forKey: "id_token")
self.dismissViewControllerAnimated(true, completion: nil)
self.firstStepLabel.text = "Auth0 JWT \(token.idToken)"
return;
}
self.presentViewController(lock, animated: true, completion: nil)
}
}
|
mit
|
0cb502a7b043f9bd3c2b65ea30bea1de
| 39.344828 | 100 | 0.633547 | 4.829721 | false | false | false | false |
ATFinke-Productions/Steppy-2
|
Shared/Helpers/STPYDataHelper.swift
|
1
|
1770
|
//
// STPYDataHelper.swift
// SwiftSteppy
//
// Created by Andrew Finke on 12/21/14.
// Copyright (c) 2014 Andrew Finke. All rights reserved.
//
import UIKit
import Foundation
class STPYDataHelper: NSObject {
/**
Gets an NSUserDefaults NSData value and unarchives it
:param: key The NSUserDefaults key
:returns: The object
*/
class func getObjectForKey(key : String) -> AnyObject? {
let data = NSUserDefaults.standardUserDefaults().objectForKey(key) as! NSData?
if data != nil {
return NSKeyedUnarchiver.unarchiveObjectWithData(data!)
}
return nil
}
/**
Saves an object as NSData to NSUserDefaults for specified key
:param: object The bool value
:param: key The NSUserDefaults key
*/
class func saveDataForKey(object : AnyObject?, key : String) {
if let object: AnyObject = object {
let defaults = NSUserDefaults.standardUserDefaults()
let dataObject = NSKeyedArchiver.archivedDataWithRootObject(object)
defaults.setObject(dataObject, forKey: key)
defaults.synchronize()
}
}
/**
Gets an NSUserDefaults key bool value
:param: key The NSUserDefaults key
:returns: value The bool value
*/
class func key(key : String) -> Bool {
return NSUserDefaults.standardUserDefaults().boolForKey(key)
}
/**
Sets an NSUserDefaults key to a bool value
:param: value The bool value
:param: key The NSUserDefaults key
*/
class func keyIs(value : Bool, key : String) {
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setBool(value, forKey: key)
defaults.synchronize()
}
}
|
mit
|
8068a3030d99690a8d139e4c364bfeaa
| 25.833333 | 86 | 0.636158 | 4.957983 | false | false | false | false |
JGiola/swift-package-manager
|
Sources/Build/BuildDelegate.swift
|
1
|
9973
|
/*
This source file is part of the Swift.org open source project
Copyright (c) 2018 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 Basic
import Utility
import SPMLLBuild
import Dispatch
/// Diagnostic error when a llbuild command encounters an error.
struct LLBuildCommandErrorDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildCommandErrorDiagnostic.self,
name: "org.swift.diags.llbuild-command-error",
defaultBehavior: .error,
description: { $0 <<< { $0.message } }
)
let message: String
}
/// Diagnostic warning when a llbuild command encounters a warning.
struct LLBuildCommandWarningDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildCommandWarningDiagnostic.self,
name: "org.swift.diags.llbuild-command-warning",
defaultBehavior: .warning,
description: { $0 <<< { $0.message } }
)
let message: String
}
/// Diagnostic note when a llbuild command encounters a warning.
struct LLBuildCommandNoteDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildCommandNoteDiagnostic.self,
name: "org.swift.diags.llbuild-command-note",
defaultBehavior: .note,
description: { $0 <<< { $0.message } }
)
let message: String
}
/// Diagnostic error when llbuild detects a cycle.
struct LLBuildCycleErrorDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildCycleErrorDiagnostic.self,
name: "org.swift.diags.llbuild-cycle",
defaultBehavior: .error,
description: {
$0 <<< "build cycle detected: "
$0 <<< { $0.rules.map({ $0.key }).joined(separator: ", ") }
}
)
let rules: [BuildKey]
}
/// Diagnostic error from llbuild
struct LLBuildErrorDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildErrorDiagnostic.self,
name: "org.swift.diags.llbuild-error",
defaultBehavior: .error,
description: {
$0 <<< { $0.message }
}
)
let message: String
}
/// Diagnostic warning from llbuild
struct LLBuildWarningDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildWarningDiagnostic.self,
name: "org.swift.diags.llbuild-warning",
defaultBehavior: .warning,
description: {
$0 <<< { $0.message }
}
)
let message: String
}
/// Diagnostic note from llbuild
struct LLBuildNoteDiagnostic: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildNoteDiagnostic.self,
name: "org.swift.diags.llbuild-note",
defaultBehavior: .note,
description: {
$0 <<< { $0.message }
}
)
let message: String
}
/// Missing inptus from LLBuild
struct LLBuildMissingInputs: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildMissingInputs.self,
name: "org.swift.diags.llbuild-missing-inputs",
defaultBehavior: .error,
description: {
$0 <<< "couldn't build "
$0 <<< { $0.output.key }
$0 <<< " because of missing inputs: "
$0 <<< { $0.inputs.map({ $0.key }).joined(separator: ", ") }
}
)
let output: BuildKey
let inputs: [BuildKey]
}
/// Multiple producers from LLBuild
struct LLBuildMultipleProducers: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildMultipleProducers.self,
name: "org.swift.diags.llbuild-multiple-producers",
defaultBehavior: .error,
description: {
$0 <<< "couldn't build "
$0 <<< { $0.output.key }
$0 <<< " because of multiple producers: "
$0 <<< { $0.commands.map({ $0.description }).joined(separator: ", ") }
}
)
let output: BuildKey
let commands: [SPMLLBuild.Command]
}
/// Command error from LLBuild
struct LLBuildCommandError: DiagnosticData {
static let id = DiagnosticID(
type: LLBuildCommandError.self,
name: "org.swift.diags.llbuild-command-error",
defaultBehavior: .error,
description: {
$0 <<< "command "
$0 <<< { $0.command.description }
$0 <<< " failed: "
$0 <<< { $0.message }
}
)
let command: SPMLLBuild.Command
let message: String
}
extension SPMLLBuild.Diagnostic: DiagnosticDataConvertible {
public var diagnosticData: DiagnosticData {
switch kind {
case .error: return LLBuildErrorDiagnostic(message: message)
case .warning: return LLBuildWarningDiagnostic(message: message)
case .note: return LLBuildNoteDiagnostic(message: message)
}
}
}
private let newLineByte: UInt8 = 10
public final class BuildDelegate: BuildSystemDelegate {
// Track counts of commands based on their CommandStatusKind
private struct CommandCounter {
var scanningCount = 0
var upToDateCount = 0
var completedCount = 0
var startedCount = 0
var estimatedMaximum: Int {
return completedCount + scanningCount - upToDateCount
}
mutating func update(command: SPMLLBuild.Command, kind: CommandStatusKind) {
guard command.shouldShowStatus else { return }
switch kind {
case .isScanning:
scanningCount += 1
case .isUpToDate:
scanningCount -= 1
upToDateCount += 1
completedCount += 1
case .isComplete:
scanningCount -= 1
completedCount += 1
}
}
}
private let diagnostics: DiagnosticsEngine
public var outputStream: ThreadSafeOutputByteStream
public var progressAnimation: ProgressAnimationProtocol
public var isVerbose: Bool = false
public var onCommmandFailure: (() -> Void)?
private var commandCounter = CommandCounter()
private let queue = DispatchQueue(label: "org.swift.swiftpm.build-delegate")
public init(
diagnostics: DiagnosticsEngine,
outputStream: OutputByteStream,
progressAnimation: ProgressAnimationProtocol
) {
self.diagnostics = diagnostics
// FIXME: Implement a class convenience initializer that does this once they are supported
// https://forums.swift.org/t/allow-self-x-in-class-convenience-initializers/15924
self.outputStream = outputStream as? ThreadSafeOutputByteStream ?? ThreadSafeOutputByteStream(outputStream)
self.progressAnimation = progressAnimation
}
public var fs: SPMLLBuild.FileSystem? {
return nil
}
public func lookupTool(_ name: String) -> Tool? {
return nil
}
public func hadCommandFailure() {
onCommmandFailure?()
}
public func handleDiagnostic(_ diagnostic: SPMLLBuild.Diagnostic) {
diagnostics.emit(diagnostic)
}
public func commandStatusChanged(_ command: SPMLLBuild.Command, kind: CommandStatusKind) {
queue.sync {
commandCounter.update(command: command, kind: kind)
}
}
public func commandPreparing(_ command: SPMLLBuild.Command) {
}
public func commandStarted(_ command: SPMLLBuild.Command) {
guard command.shouldShowStatus else { return }
queue.sync {
commandCounter.startedCount += 1
progressAnimation.update(
step: commandCounter.startedCount,
total: commandCounter.estimatedMaximum,
text: isVerbose ? command.verboseDescription : command.description)
}
}
public func shouldCommandStart(_ command: SPMLLBuild.Command) -> Bool {
return true
}
public func commandFinished(_ command: SPMLLBuild.Command, result: CommandResult) {
}
public func commandHadError(_ command: SPMLLBuild.Command, message: String) {
diagnostics.emit(data: LLBuildCommandErrorDiagnostic(message: message))
}
public func commandHadNote(_ command: SPMLLBuild.Command, message: String) {
diagnostics.emit(data: LLBuildCommandNoteDiagnostic(message: message))
}
public func commandHadWarning(_ command: SPMLLBuild.Command, message: String) {
diagnostics.emit(data: LLBuildCommandWarningDiagnostic(message: message))
}
public func commandCannotBuildOutputDueToMissingInputs(
_ command: SPMLLBuild.Command,
output: BuildKey,
inputs: [BuildKey]
) {
diagnostics.emit(data: LLBuildMissingInputs(output: output, inputs: inputs))
}
public func cannotBuildNodeDueToMultipleProducers(output: BuildKey, commands: [SPMLLBuild.Command]) {
diagnostics.emit(data: LLBuildMultipleProducers(output: output, commands: commands))
}
public func commandProcessStarted(_ command: SPMLLBuild.Command, process: ProcessHandle) {
}
public func commandProcessHadError(_ command: SPMLLBuild.Command, process: ProcessHandle, message: String) {
diagnostics.emit(data: LLBuildCommandError(command: command, message: message))
}
public func commandProcessHadOutput(_ command: SPMLLBuild.Command, process: ProcessHandle, data: [UInt8]) {
progressAnimation.clear()
outputStream <<< data
outputStream.flush()
}
public func commandProcessFinished(
_ command: SPMLLBuild.Command,
process: ProcessHandle,
result: CommandExtendedResult
) {
}
public func cycleDetected(rules: [BuildKey]) {
diagnostics.emit(data: LLBuildCycleErrorDiagnostic(rules: rules))
}
public func shouldResolveCycle(rules: [BuildKey], candidate: BuildKey, action: CycleAction) -> Bool {
return false
}
}
|
apache-2.0
|
05f239713baaf6b1cc93f2c25ce77bd7
| 30.361635 | 115 | 0.649052 | 4.484263 | false | false | false | false |
ibm-bluemix-mobile-services/bms-clientsdk-swift-security
|
Source/mca/internal/certificate/SecurityUtils.swift
|
1
|
32225
|
/*
* Copyright 2015 IBM 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.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
#if swift (>=3.0)
internal class SecurityUtils {
private static func savePublicKeyToKeyChain(_ key:SecKey,tag:String) throws {
let publicKeyAttr : [NSString:AnyObject] = [
kSecValueRef: key,
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : tag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPublic
]
let addStatus:OSStatus = SecItemAdd(publicKeyAttr as CFDictionary, nil)
guard addStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
}
private static func getKeyBitsFromKeyChain(_ tag:String) throws -> Data {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnData : true as AnyObject
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! Data
}
internal static func generateKeyPair(_ keySize:Int, publicTag:String, privateTag:String)throws -> (publicKey: SecKey, privateKey: SecKey) {
//make sure keys are deleted
SecurityUtils.deleteKeyFromKeyChain(publicTag)
SecurityUtils.deleteKeyFromKeyChain(privateTag)
var status:OSStatus = noErr
var privateKey:SecKey?
var publicKey:SecKey?
let privateKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : privateTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPrivate
]
let publicKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true as AnyObject,
kSecAttrApplicationTag : publicTag as AnyObject,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
]
let keyPairAttr : [NSString:AnyObject] = [
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits : keySize as AnyObject,
kSecPublicKeyAttrs : publicKeyAttr as AnyObject,
kSecPrivateKeyAttrs : privateKeyAttr as AnyObject
]
status = SecKeyGeneratePair(keyPairAttr as CFDictionary, &publicKey, &privateKey)
if (status != errSecSuccess) {
throw BMSSecurityError.generalError
} else {
return (publicKey!, privateKey!)
}
}
private static func getKeyPairBitsFromKeyChain(_ publicTag:String, privateTag:String) throws -> (publicKey: Data, privateKey: Data) {
return try (getKeyBitsFromKeyChain(publicTag),getKeyBitsFromKeyChain(privateTag))
}
private static func getKeyPairRefFromKeyChain(_ publicTag:String, privateTag:String) throws -> (publicKey: SecKey, privateKey: SecKey) {
return try (getKeyRefFromKeyChain(publicTag),getKeyRefFromKeyChain(privateTag))
}
private static func getKeyRefFromKeyChain(_ tag:String) throws -> SecKey {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag as AnyObject,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnRef : kCFBooleanTrue
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr as CFDictionary, &result)
guard status == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! SecKey
}
internal static func getCertificateFromKeyChain(_ certificateLabel:String) throws -> SecCertificate {
let getQuery : [NSString: AnyObject] = [
kSecClass : kSecClassCertificate,
kSecReturnRef : true as AnyObject,
kSecAttrLabel : certificateLabel as AnyObject
]
var result: AnyObject?
let getStatus = SecItemCopyMatching(getQuery as CFDictionary, &result)
guard getStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! SecCertificate
}
internal static func getItemFromKeyChain(_ label:String) -> String? {
let query: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecReturnData: kCFBooleanTrue
]
var results: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &results)
if status == errSecSuccess {
let data = results as! Data
let password = String(data: data, encoding: String.Encoding.utf8)!
return password
}
return nil
}
internal static func signCsr(_ payloadJSON:[String : Any], keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String {
do {
let strPayloadJSON = try Utils.JSONStringify(payloadJSON as AnyObject)
let keys = try getKeyPairBitsFromKeyChain(ids.publicKey, privateTag: ids.privateKey)
let publicKey = keys.publicKey
let privateKeySec = try getKeyPairRefFromKeyChain(ids.publicKey, privateTag: ids.privateKey).privateKey
let strJwsHeaderJSON = try Utils.JSONStringify(getJWSHeaderForPublicKey(publicKey) as AnyObject)
guard let jwsHeaderData : Data = strJwsHeaderJSON.data(using: String.Encoding.utf8), let payloadJSONData : Data = strPayloadJSON.data(using: String.Encoding.utf8) else {
throw BMSSecurityError.generalError
}
let jwsHeaderBase64 = Utils.base64StringFromData(jwsHeaderData, isSafeUrl: true)
let payloadJSONBase64 = Utils.base64StringFromData(payloadJSONData, isSafeUrl: true)
let jwsHeaderAndPayload = jwsHeaderBase64 + ("." + payloadJSONBase64)
let signedData = try signData(jwsHeaderAndPayload, privateKey:privateKeySec)
let signedDataBase64 = Utils.base64StringFromData(signedData, isSafeUrl: true)
return jwsHeaderAndPayload + ("." + signedDataBase64)
}
catch {
throw BMSSecurityError.generalError
}
}
private static func getJWSHeaderForPublicKey(_ publicKey: Data) throws ->[String:Any]
{
let base64Options = NSData.Base64EncodingOptions(rawValue:0)
guard let pkModulus : Data = getPublicKeyMod(publicKey), let pkExponent : Data = getPublicKeyExp(publicKey) else {
throw BMSSecurityError.generalError
}
let mod:String = pkModulus.base64EncodedString(options: base64Options)
let exp:String = pkExponent.base64EncodedString(options: base64Options)
let publicKeyJSON : [String:Any] = [
BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RSA_VALUE as AnyObject,
BMSSecurityConstants.JSON_MOD_KEY : mod as AnyObject,
BMSSecurityConstants.JSON_EXP_KEY : exp as AnyObject
]
let jwsHeaderJSON :[String:Any] = [
BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RS256_VALUE as AnyObject,
BMSSecurityConstants.JSON_JPK_KEY : publicKeyJSON as AnyObject
]
return jwsHeaderJSON
}
private static func getPublicKeyMod(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1 // TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
if(mod_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, mod_size).toRange()!)
}
//Return public key exponent
private static func getPublicKeyExp(_ publicKeyBits: Data) -> Data? {
var iterator : Int = 0
iterator += 1 // TYPE - bit stream - mod + exp
derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator += 1// TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
iterator += mod_size
iterator += 1 // TYPE - bit stream exp
let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
//Ensure we got an exponent size
if(exp_size == -1) {
return nil
}
return publicKeyBits.subdata(in: NSMakeRange(iterator, exp_size).toRange()!)
}
private static func derEncodingGetSizeFrom(_ buf : Data, at iterator: inout Int) -> Int{
// Have to cast the pointer to the right size
//let pointer = UnsafePointer<UInt8>((buf as NSData).bytes)
//let count = buf.count
// Get our buffer pointer and make an array out of it
//let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
let data = buf//[UInt8](buffer)
var itr : Int = iterator
var num_bytes :UInt8 = 1
var ret : Int = 0
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80
itr += 1
}
for i in 0 ..< Int(num_bytes) {
ret = (ret * 0x100) + Int(data[itr + i])
}
iterator = itr + Int(num_bytes)
return ret
}
private static func signData(_ payload:String, privateKey:SecKey) throws -> Data {
guard let data:Data = payload.data(using: String.Encoding.utf8) else {
throw BMSSecurityError.generalError
}
func doSha256(_ dataIn:Data) throws -> Data {
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
dataIn.withUnsafeBytes {
_ = CC_SHA256($0, CC_LONG(dataIn.count), &hash)
}
return Data(bytes: hash)
}
guard let digest:Data = try? doSha256(data), let signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else {
throw BMSSecurityError.generalError
}
var signedDataLength: Int = signedData.length
let digestBytes: UnsafePointer<UInt8> = ((digest as NSData).bytes).bindMemory(to: UInt8.self, capacity: digest.count)
let digestlen = digest.count
let mutableBytes: UnsafeMutablePointer<UInt8> = signedData.mutableBytes.assumingMemoryBound(to: UInt8.self)
let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen,
mutableBytes, &signedDataLength)
guard signStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
return signedData as Data
}
internal static func saveItemToKeyChain(_ data:String, label: String) -> Bool{
guard let stringData = data.data(using: String.Encoding.utf8) else {
return false
}
let key: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject,
kSecValueData: stringData as AnyObject
]
var status = SecItemAdd(key as CFDictionary, nil)
if(status != errSecSuccess){
if(SecurityUtils.removeItemFromKeyChain(label) == true) {
status = SecItemAdd(key as CFDictionary, nil)
}
}
return status == errSecSuccess
}
internal static func removeItemFromKeyChain(_ label: String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
internal static func getCertificateFromString(_ stringData:String) throws -> SecCertificate{
if let data:Data = Data(base64Encoded: stringData, options: NSData.Base64DecodingOptions.ignoreUnknownCharacters) {
if let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, data as CFData) {
return certificate
}
}
throw BMSSecurityError.generalError
}
internal static func deleteCertificateFromKeyChain(_ certificateLabel:String, uuid:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassCertificate,
kSecAttrLabel: certificateLabel as AnyObject,
kSecAttrSerialNumber : uuid as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
private static func deleteKeyFromKeyChain(_ tag:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag : tag as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery as CFDictionary)
return delStatus == errSecSuccess
}
internal static func saveCertificateToKeyChain(_ certificate:SecCertificate, certificateLabel:String, uuid:String) throws {
//make sure certificate is deleted
deleteCertificateFromKeyChain(certificateLabel, uuid:uuid)
//set certificate in key chain
let setQuery: [NSString: AnyObject] = [
kSecClass: kSecClassCertificate,
kSecValueRef: certificate,
kSecAttrSerialNumber : uuid as AnyObject,
kSecAttrLabel: certificateLabel as AnyObject,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
]
let addStatus:OSStatus = SecItemAdd(setQuery as CFDictionary, nil)
guard addStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
}
internal static func checkCertificatePublicKeyValidity(_ certificate:SecCertificate, publicKeyTag:String) throws -> Bool{
let certificatePublicKeyTag = "checkCertificatePublicKeyValidity : publicKeyFromCertificate"
var publicKeyBits = try getKeyBitsFromKeyChain(publicKeyTag)
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
var status = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let unWrappedTrust = trust, status == errSecSuccess {
if let certificatePublicKey = SecTrustCopyPublicKey(unWrappedTrust) {
defer {
SecurityUtils.deleteKeyFromKeyChain(certificatePublicKeyTag)
}
try savePublicKeyToKeyChain(certificatePublicKey, tag: certificatePublicKeyTag)
let ceritificatePublicKeyBits = try getKeyBitsFromKeyChain(certificatePublicKeyTag)
if(ceritificatePublicKeyBits == publicKeyBits){
return true
}
}
}
throw BMSSecurityError.generalError
}
internal static func clearDictValuesFromKeyChain(_ dict : [String : NSString], uuid:String) {
for (tag, kSecClassName) in dict {
if kSecClassName == kSecClassCertificate {
deleteCertificateFromKeyChain(tag, uuid: uuid)
} else if kSecClassName == kSecClassKey {
deleteKeyFromKeyChain(tag)
} else if kSecClassName == kSecClassGenericPassword {
removeItemFromKeyChain(tag)
}
}
}
}
#else
internal class SecurityUtils {
private static func savePublicKeyToKeyChain(key:SecKey,tag:String) throws {
let publicKeyAttr : [NSString:AnyObject] = [
kSecValueRef: key,
kSecAttrIsPermanent : true,
kSecAttrApplicationTag : tag,
kSecAttrKeyClass : kSecAttrKeyClassPublic
]
let addStatus:OSStatus = SecItemAdd(publicKeyAttr, nil)
guard addStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
}
private static func getKeyBitsFromKeyChain(tag:String) throws -> NSData {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnData : true
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr, &result)
guard status == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! NSData
}
internal static func generateKeyPair(keySize:Int, publicTag:String, privateTag:String)throws -> (publicKey: SecKey, privateKey: SecKey) {
//make sure keys are deleted
SecurityUtils.deleteKeyFromKeyChain(publicTag)
SecurityUtils.deleteKeyFromKeyChain(privateTag)
var status:OSStatus = noErr
var privateKey:SecKey?
var publicKey:SecKey?
let privateKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true,
kSecAttrApplicationTag : privateTag,
kSecAttrKeyClass : kSecAttrKeyClassPrivate
]
let publicKeyAttr : [NSString:AnyObject] = [
kSecAttrIsPermanent : true,
kSecAttrApplicationTag : publicTag,
kSecAttrKeyClass : kSecAttrKeyClassPublic,
]
let keyPairAttr : [NSString:AnyObject] = [
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecAttrKeySizeInBits : keySize,
kSecPublicKeyAttrs : publicKeyAttr,
kSecPrivateKeyAttrs : privateKeyAttr
]
status = SecKeyGeneratePair(keyPairAttr, &publicKey, &privateKey)
if (status != errSecSuccess) {
throw BMSSecurityError.generalError
} else {
return (publicKey!, privateKey!)
}
}
private static func getKeyPairBitsFromKeyChain(publicTag:String, privateTag:String) throws -> (publicKey: NSData, privateKey: NSData) {
return try (getKeyBitsFromKeyChain(publicTag),getKeyBitsFromKeyChain(privateTag))
}
private static func getKeyPairRefFromKeyChain(publicTag:String, privateTag:String) throws -> (publicKey: SecKey, privateKey: SecKey) {
return try (getKeyRefFromKeyChain(publicTag),getKeyRefFromKeyChain(privateTag))
}
private static func getKeyRefFromKeyChain(tag:String) throws -> SecKey {
let keyAttr : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag: tag,
kSecAttrKeyType : kSecAttrKeyTypeRSA,
kSecReturnRef : kCFBooleanTrue
]
var result: AnyObject?
let status = SecItemCopyMatching(keyAttr, &result)
guard status == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! SecKey
}
internal static func getCertificateFromKeyChain(certificateLabel:String) throws -> SecCertificate {
let getQuery : [NSString: AnyObject] = [
kSecClass : kSecClassCertificate,
kSecReturnRef : true,
kSecAttrLabel : certificateLabel
]
var result: AnyObject?
let getStatus = SecItemCopyMatching(getQuery, &result)
guard getStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
return result as! SecCertificate
}
internal static func getItemFromKeyChain(label:String) -> String? {
let query: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label,
kSecReturnData: kCFBooleanTrue
]
var results: AnyObject?
let status = SecItemCopyMatching(query, &results)
if status == errSecSuccess {
let data = results as! NSData
let password = String(data: data, encoding: NSUTF8StringEncoding)!
return password
}
return nil
}
internal static func signCsr(payloadJSON:[String : AnyObject], keyIds ids:(publicKey: String, privateKey: String), keySize: Int) throws -> String {
do {
let strPayloadJSON = try Utils.JSONStringify(payloadJSON)
let keys = try getKeyPairBitsFromKeyChain(ids.publicKey, privateTag: ids.privateKey)
let publicKey = keys.publicKey
let privateKeySec = try getKeyPairRefFromKeyChain(ids.publicKey, privateTag: ids.privateKey).privateKey
let strJwsHeaderJSON = try Utils.JSONStringify(getJWSHeaderForPublicKey(publicKey))
guard let jwsHeaderData : NSData = strJwsHeaderJSON.dataUsingEncoding(NSUTF8StringEncoding), payloadJSONData : NSData = strPayloadJSON.dataUsingEncoding(NSUTF8StringEncoding) else {
throw BMSSecurityError.generalError
}
let jwsHeaderBase64 = Utils.base64StringFromData(jwsHeaderData, isSafeUrl: true)
let payloadJSONBase64 = Utils.base64StringFromData(payloadJSONData, isSafeUrl: true)
let jwsHeaderAndPayload = jwsHeaderBase64.stringByAppendingString(".".stringByAppendingString(payloadJSONBase64))
let signedData = try signData(jwsHeaderAndPayload, privateKey:privateKeySec)
let signedDataBase64 = Utils.base64StringFromData(signedData, isSafeUrl: true)
return jwsHeaderAndPayload.stringByAppendingString(".".stringByAppendingString(signedDataBase64))
}
catch {
throw BMSSecurityError.generalError
}
}
private static func getJWSHeaderForPublicKey(publicKey: NSData) throws ->[String:AnyObject]
{
let base64Options = NSDataBase64EncodingOptions(rawValue:0)
guard let pkModulus : NSData = getPublicKeyMod(publicKey), let pkExponent : NSData = getPublicKeyExp(publicKey) else {
throw BMSSecurityError.generalError
}
let mod:String = pkModulus.base64EncodedStringWithOptions(base64Options)
let exp:String = pkExponent.base64EncodedStringWithOptions(base64Options)
let publicKeyJSON : [String:AnyObject] = [
BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RSA_VALUE,
BMSSecurityConstants.JSON_MOD_KEY : mod,
BMSSecurityConstants.JSON_EXP_KEY : exp
]
let jwsHeaderJSON :[String:AnyObject] = [
BMSSecurityConstants.JSON_ALG_KEY : BMSSecurityConstants.JSON_RS256_VALUE,
BMSSecurityConstants.JSON_JPK_KEY : publicKeyJSON
]
return jwsHeaderJSON
}
private static func getPublicKeyMod(publicKeyBits: NSData) -> NSData? {
var iterator : Int = 0
iterator+=1 // TYPE - bit stream - mod + exp
derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator+=1 // TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
if(mod_size == -1) {
return nil
}
return publicKeyBits.subdataWithRange(NSMakeRange(iterator, mod_size))
}
//Return public key exponent
private static func getPublicKeyExp(publicKeyBits: NSData) -> NSData? {
var iterator : Int = 0
iterator+=1 // TYPE - bit stream - mod + exp
derEncodingGetSizeFrom(publicKeyBits, at:&iterator) // Total size
iterator+=1// TYPE - bit stream mod
let mod_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
iterator += mod_size
iterator+=1 // TYPE - bit stream exp
let exp_size : Int = derEncodingGetSizeFrom(publicKeyBits, at:&iterator)
//Ensure we got an exponent size
if(exp_size == -1) {
return nil
}
return publicKeyBits.subdataWithRange(NSMakeRange(iterator, exp_size))
}
private static func derEncodingGetSizeFrom(buf : NSData, inout at iterator: Int) -> Int{
// Have to cast the pointer to the right size
let pointer = UnsafePointer<UInt8>(buf.bytes)
let count = buf.length
// Get our buffer pointer and make an array out of it
let buffer = UnsafeBufferPointer<UInt8>(start:pointer, count:count)
let data = [UInt8](buffer)
var itr : Int = iterator
var num_bytes :UInt8 = 1
var ret : Int = 0
if (data[itr] > 0x80) {
num_bytes = data[itr] - 0x80
itr += 1
}
for i in 0 ..< Int(num_bytes) {
ret = (ret * 0x100) + Int(data[itr + i])
}
iterator = itr + Int(num_bytes)
return ret
}
private static func signData(payload:String, privateKey:SecKey) throws -> NSData {
guard let data:NSData = payload.dataUsingEncoding(NSUTF8StringEncoding) else {
throw BMSSecurityError.generalError
}
func doSha256(dataIn:NSData) throws -> NSData {
guard let shaOut: NSMutableData = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH)) else {
throw BMSSecurityError.generalError
}
CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(shaOut.mutableBytes))
return shaOut
}
guard let digest:NSData = try? doSha256(data), signedData: NSMutableData = NSMutableData(length: SecKeyGetBlockSize(privateKey)) else {
throw BMSSecurityError.generalError
}
var signedDataLength: Int = signedData.length
let digestBytes = UnsafePointer<UInt8>(digest.bytes)
let digestlen = digest.length
let signStatus:OSStatus = SecKeyRawSign(privateKey, SecPadding.PKCS1SHA256, digestBytes, digestlen, UnsafeMutablePointer<UInt8>(signedData.mutableBytes),
&signedDataLength)
guard signStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
return signedData
}
internal static func saveItemToKeyChain(data:String, label: String) -> Bool{
guard let stringData = data.dataUsingEncoding(NSUTF8StringEncoding) else {
return false
}
let key: [NSString: AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label,
kSecValueData: stringData
]
var status = SecItemAdd(key, nil)
if(status != errSecSuccess){
if(SecurityUtils.removeItemFromKeyChain(label) == true) {
status = SecItemAdd(key, nil)
}
}
return status == errSecSuccess
}
internal static func removeItemFromKeyChain(label: String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: label
]
let delStatus:OSStatus = SecItemDelete(delQuery)
return delStatus == errSecSuccess
}
internal static func getCertificateFromString(stringData:String) throws -> SecCertificate{
if let data:NSData = NSData(base64EncodedString: stringData, options: NSDataBase64DecodingOptions.IgnoreUnknownCharacters) {
if let certificate = SecCertificateCreateWithData(kCFAllocatorDefault, data) {
return certificate
}
}
throw BMSSecurityError.generalError
}
internal static func deleteCertificateFromKeyChain(_ certificateLabel:String, uuid:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass: kSecClassCertificate,
kSecAttrLabel: certificateLabel,
kSecAttrSerialNumber : uuid as AnyObject
]
let delStatus:OSStatus = SecItemDelete(delQuery)
return delStatus == errSecSuccess
}
private static func deleteKeyFromKeyChain(tag:String) -> Bool{
let delQuery : [NSString:AnyObject] = [
kSecClass : kSecClassKey,
kSecAttrApplicationTag : tag
]
let delStatus:OSStatus = SecItemDelete(delQuery)
return delStatus == errSecSuccess
}
internal static func saveCertificateToKeyChain(certificate:SecCertificate, certificateLabel:String, uuid:String) throws {
//make sure certificate is deleted
deleteCertificateFromKeyChain(certificateLabel, uuid:uuid)
//set certificate in key chain
let setQuery: [NSString: AnyObject] = [
kSecClass: kSecClassCertificate,
kSecValueRef: certificate,
kSecAttrSerialNumber : uuid as AnyObject,
kSecAttrLabel: certificateLabel,
kSecAttrAccessible: kSecAttrAccessibleWhenUnlockedThisDeviceOnly,
]
let addStatus:OSStatus = SecItemAdd(setQuery, nil)
guard addStatus == errSecSuccess else {
throw BMSSecurityError.generalError
}
}
internal static func checkCertificatePublicKeyValidity(certificate:SecCertificate, publicKeyTag:String) throws -> Bool{
let certificatePublicKeyTag = "checkCertificatePublicKeyValidity : publicKeyFromCertificate"
var publicKeyBits = try getKeyBitsFromKeyChain(publicKeyTag)
let policy = SecPolicyCreateBasicX509()
var trust: SecTrust?
var status = SecTrustCreateWithCertificates(certificate, policy, &trust)
if let unWrappedTrust = trust where status == errSecSuccess {
if let certificatePublicKey = SecTrustCopyPublicKey(unWrappedTrust) {
defer {
SecurityUtils.deleteKeyFromKeyChain(certificatePublicKeyTag)
}
try savePublicKeyToKeyChain(certificatePublicKey, tag: certificatePublicKeyTag)
let ceritificatePublicKeyBits = try getKeyBitsFromKeyChain(certificatePublicKeyTag)
if(ceritificatePublicKeyBits == publicKeyBits){
return true
}
}
}
throw BMSSecurityError.generalError
}
internal static func clearDictValuesFromKeyChain(_ dict : [String : NSString], uuid:String) {
for (tag, kSecClassName) in dict {
if kSecClassName == kSecClassCertificate {
deleteCertificateFromKeyChain(tag, uuid: uuid)
} else if kSecClassName == kSecClassKey {
deleteKeyFromKeyChain(tag)
} else if kSecClassName == kSecClassGenericPassword {
removeItemFromKeyChain(tag)
}
}
}
}
#endif
|
apache-2.0
|
5064505820a4d7ed0b81fddee37597e1
| 38.993789 | 193 | 0.624538 | 5.503419 | false | false | false | false |
bastienFalcou/SoundWave
|
SoundWave/Classes/BaseNibView.swift
|
1
|
2425
|
//
// BaseNibView.swift
// Pods
//
// Created by Bastien Falcou on 12/6/16.
//
import UIKit
/**
* Subclass this class to use
* @note
* Instructions:
* - Subclass this class
* - Associate it with a nib via File's Owner (Whose name is defined by [-nibName])
* - Bind contentView to the root view of the nib
* - Then you can insert it either in code or in a xib/storyboard, your choice
*/
public class BaseNibView: UIView {
@IBOutlet var contentView: UIView!
/**
* Is called when the nib name associated with the class is going to be loaded.
*
* @return The nib name (Default implementation returns class name: `NSStringFromClass([self class])`)
* You will want to override this method in swift as the class name is prefixed with the module in that case
*/
var nibName: String {
return String(describing: type(of: self))
}
/**
* Called when first loading the nib.
* Defaults to `[NSBundle bundleForClass:[self class]]`
*
* @return The bundle in which to find the nib.
*/
var nibBundle: Bundle {
return Bundle(for: type(of: self))
}
/**
* Use the 2 methods above to instanciate the correct instance of UINib for the view.
* You can override this if you need more customization.
*
* @return An instance of UINib
*/
var nib: UINib {
return UINib(nibName: self.nibName, bundle: self.nibBundle)
}
private var shouldAwakeFromNib: Bool = true
override init(frame: CGRect) {
super.init(frame: frame)
self.createFromNib()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override public func awakeFromNib() {
super.awakeFromNib()
self.shouldAwakeFromNib = false
self.createFromNib()
}
private func createFromNib() {
if self.contentView == nil {
return
}
self.nib.instantiate(withOwner: self, options: nil)
assert(self.contentView != nil, "contentView is nil. Did you forgot to link it in IB?")
if self.shouldAwakeFromNib {
self.awakeFromNib()
}
self.contentView.translatesAutoresizingMaskIntoConstraints = false
self.addSubview(self.contentView)
self.contentView.topAnchor.constraint(equalTo: self.topAnchor).isActive = true
self.contentView.bottomAnchor.constraint(equalTo: self.bottomAnchor).isActive = true
self.contentView.leftAnchor.constraint(equalTo: self.leftAnchor).isActive = true
self.contentView.rightAnchor.constraint(equalTo: self.rightAnchor).isActive = true
}
}
|
mit
|
43ac303996585b56a69744545e3dcf82
| 25.648352 | 109 | 0.718763 | 3.652108 | false | false | false | false |
omise/omise-ios
|
OmiseSDK/CardExpiryDatePicker.swift
|
1
|
3168
|
import UIKit
/// UIPickerView subclass pre-configured for picking card expiration month and year.
@objc(OMSCardExpiryDatePicker) public
class CardExpiryDatePicker: UIPickerView {
/// Callback function that will be called when picker value changes.
public var onDateSelected: ((_ month: Int, _ year: Int) -> Void)?
/// Currently selected month.
public var month: Int = Calendar.creditCardInformationCalendar.component(.month, from: Date())
/// Currently selected year.
public var year: Int = Calendar.creditCardInformationCalendar.component(.year, from: Date())
private static let maximumYear = 21
private static let monthPicker = 0
private static let yearPicker = 1
private let months: [String] = {
let validRange = Calendar.creditCardInformationCalendar.maximumRange(of: Calendar.Component.month) ?? Range<Int>(1...12)
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
formatter.alwaysShowsDecimalSeparator = false
formatter.minimumIntegerDigits = 2
return validRange.map { formatter.string(from: $0 as NSNumber)! } // swiftlint:disable:this force_unwrapping
}()
private let years: [Int] = {
let currentYear = Calendar.creditCardInformationCalendar.component(.year, from: Date())
return Array(currentYear...(currentYear.advanced(by: maximumYear)))
}()
public override init(frame: CGRect) {
super.init(frame: frame)
initializeInstance()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
initializeInstance()
}
private func initializeInstance() {
delegate = self
dataSource = self
selectRow(month - 1, inComponent: 0, animated: false)
}
}
extension CardExpiryDatePicker: UIPickerViewDataSource {
public func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 2
}
public func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
switch component {
case CardExpiryDatePicker.monthPicker:
return months.count
case CardExpiryDatePicker.yearPicker:
return years.count
default:
return 0
}
}
}
extension CardExpiryDatePicker: UIPickerViewDelegate {
public func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
switch component {
case CardExpiryDatePicker.monthPicker:
return months[row]
case CardExpiryDatePicker.yearPicker:
return String(years[row])
default:
return nil
}
}
public func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let month = selectedRow(inComponent: CardExpiryDatePicker.monthPicker) + 1
let year = years[selectedRow(inComponent: CardExpiryDatePicker.yearPicker)]
if let block = onDateSelected {
block(month, year)
}
self.month = month
self.year = year
}
}
|
mit
|
ccb506214dcdca92d1e3f22c2e52a226
| 35 | 128 | 0.664141 | 5.028571 | false | false | false | false |
hhsolar/MemoryMaster-iOS
|
MemoryMaster/Utility/MyTextAttachment.swift
|
1
|
832
|
//
// MyTextAttachment.swift
// MemoryMaster
//
// Created by apple on 26/10/2017.
// Copyright © 2017 greatwall. All rights reserved.
//
import UIKit
class MyTextAttachment: NSTextAttachment {
override func attachmentBounds(for textContainer: NSTextContainer?, proposedLineFragment lineFrag: CGRect, glyphPosition position: CGPoint, characterIndex charIndex: Int) -> CGRect
{
guard let image = self.image else {
return CGRect.zero
}
let width = lineFrag.size.width
var scalingFactor = CGFloat(1)
let imageSize = image.size
if width < imageSize.width {
scalingFactor = width / imageSize.width
}
return CGRect(x: 0, y: 0, width: imageSize.width * scalingFactor, height: imageSize.height * scalingFactor)
}
}
|
mit
|
35340128821bd2a17d75fdc4f722e069
| 29.777778 | 184 | 0.654633 | 4.59116 | false | false | false | false |
ByteriX/BxInputController
|
BxInputController/Sources/Common/View/Selector/BxInputSelectorRowBinder.swift
|
1
|
3595
|
/**
* @file BxInputSelectorRowBinder.swift
* @namespace BxInputController
*
* @details Binder for a selector row
* @date 06.03.2017
* @author Sergey Balalaev
*
* @version last in https://github.com/ByteriX/BxInputController.git
* @copyright The MIT License (MIT) https://opensource.org/licenses/MIT
* Copyright (c) 2017 ByteriX. See http://byterix.com
*/
import UIKit
#warning("change BxInputBaseFieldRowBinder to BxInputBaseRowBinder")
/// Binder for a selector row
open class BxInputSelectorRowBinder<Row: BxInputSelectorRow, Cell: BxInputSelectorCell>: BxInputBaseFieldRowBinder<Row, Cell>
{
/// call when user selected this cell
override open func didSelected()
{
super.didSelected()
row.isOpened = !row.isOpened
refreshOpened(animated: true)
if row.isOpened {
//owner?.beginUpdates() init crash
owner?.addRows(row.children, after: row)
if let owner = owner, owner.settings.isAutodissmissSelector {
owner.dissmissAllRows(exclude: row)
}
//owner?.endUpdates()
if row.children.count > 1 {
owner?.scrollRow(row, at: .top, animated: true)
} else if let firstItem = row.children.first {
owner?.selectRow(firstItem, at: .middle, animated: true)
} else {
owner?.scrollRow(row, at: .middle, animated: true)
}
owner?.activeRow = row
} else {
owner?.deleteRows(row.children)
}
}
/// update cell from model data
override open func update()
{
super.update()
//
cell?.arrowImage.image = BxInputUtils.getImage(resourceId: "bx_arrow_to_bottom")
//
refreshOpened(animated: false)
}
/// event of change isEnabled
override open func didSetEnabled(_ value: Bool)
{
super.didSetEnabled(value)
guard let cell = cell else {
return
}
// UI part
if needChangeDisabledCell {
if let changeViewEnableHandler = owner?.settings.changeViewEnableHandler {
changeViewEnableHandler(cell.arrowImage, isEnabled)
} else {
cell.arrowImage.alpha = value ? 1 : alphaForDisabledView
}
} else {
cell.arrowImage.isHidden = !value
}
}
/// visual updating of state from opened/closed
open func refreshOpened(animated: Bool) {
if animated {
UIView.beginAnimations(nil, context: nil)
}
if row.isOpened {
cell?.arrowImage.transform = CGAffineTransform(rotationAngle: CGFloat(Double.pi))
} else {
cell?.arrowImage.transform = CGAffineTransform.identity
}
checkValue()
if animated {
UIView.commitAnimations()
}
}
/// visual updating of value && separator that depends on type of the row
open func checkValue() {
// all string changing of value
if let row = row as? BxInputString{
cell?.valueTextField.text = row.stringValue
} else {
cell?.valueTextField.text = ""
}
}
/// If selector is closed just will open
public func toOpen() {
if row.isOpened == false {
didSelected()
}
}
/// If selector is opened just will close
public func toClose() {
if row.isOpened == true {
didSelected()
}
}
}
|
mit
|
c8f57b422b7233bf390c0f1bc4c7dd08
| 28.710744 | 125 | 0.574965 | 4.620823 | false | false | false | false |
CoderQHao/Live
|
LiveSwift/LiveSwift/Classes/Live/Model/AnchorModel.swift
|
1
|
468
|
//
// AnchorModel.swift
// LiveSwift
//
// Created by 郝庆 on 2017/5/25.
// Copyright © 2017年 Enroute. All rights reserved.
//
import UIKit
class AnchorModel: BaseModel {
var roomid: Int = 0
var name: String = ""
var pic51: String = ""
var pic74: String = ""
var live: Int = 0 // 是否在直播
var push: Int = 0 // 直播显示方式
var focus: Int = 0 // 关注数
var uid: String = ""
var isEvenIndex: Bool = false
}
|
mit
|
5e675aad36285d4a60688ee66c488b31
| 19.619048 | 51 | 0.591224 | 3.137681 | false | false | false | false |
BGDigital/mckuai2.0
|
mckuai/mckuai/login/Avatar.swift
|
1
|
11593
|
//
// avatar.swift
// mckuai
//
// Created by 夕阳 on 15/2/2.
// Copyright (c) 2015年 XingfuQiu. All rights reserved.
//
import Foundation
import UIKit
class Avatar:UIViewController,UICollectionViewDataSource,UICollectionViewDelegate,UIGestureRecognizerDelegate,UzysAssetsPickerControllerDelegate{
var manager = AFHTTPRequestOperationManager()
var imgPrex = "http://cdn.mckuai.com/images/iphone/"
var isNew = false
var isLocationPic = false
var hud:MBProgressHUD?
var chosedAvatar:String?{
didSet{
choseAvatar()
}
}
var avatars = ["0.png","1.png","2.png","3.png","4.png","5.png","6.png","7.png","8.png","9.png","10.png","11.png","12.png","13.png","14.png"]
@IBOutlet weak var avatar: UIImageView!
@IBOutlet weak var avatarList: UICollectionView!
var addPic:UIButton!
override func viewDidLoad() {
initNavigation()
if chosedAvatar == nil {
chosedAvatar = avatars[0]
}else{
choseAvatar()
}
avatarList.dataSource = self
avatarList.delegate = self
avatarList.scrollEnabled = false
//initAddPicButtton()
}
func initAddPicButtton(){
var addLable = UILabel(frame: CGRectMake(20, self.avatarList.frame.size.height + 15,150 , 25))
addLable.text = "选择本地图片"
addLable.textColor = UIColor(red: 0.263, green: 0.263, blue: 0.263, alpha: 1.00)
self.view.addSubview(addLable)
addPic = UIButton(frame: CGRectMake(10,self.avatarList.frame.size.height + 55 , 60, 60))
addPic.setImage(UIImage(named: "addImage"), forState: UIControlState.Normal)
addPic.addTarget(self, action: "addPicAction", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(addPic)
}
@IBAction func addPicAction() {
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"all"])
var appearanceConfig = UzysAppearanceConfig()
appearanceConfig.finishSelectionButtonColor = UIColor.greenColor()
UzysAssetsPickerController.setUpAppearanceConfig(appearanceConfig)
var picker = UzysAssetsPickerController()
picker.delegate = self
picker.maximumNumberOfSelectionVideo = 0;
picker.maximumNumberOfSelectionPhoto = 1;
self.presentViewController(picker, animated: true, completion: nil)
}
func uzysAssetsPickerController(picker: UzysAssetsPickerController!, didFinishPickingAssets assets: [AnyObject]!) {
if(assets.count == 1){
var assets_array = assets as NSArray
assets_array.enumerateObjectsUsingBlock({ obj, index, stop in
// println(index)
var representation:ALAsset = obj as! ALAsset
var returnImg = UIImage(CGImage: representation.thumbnail().takeUnretainedValue())
self.avatar.image = returnImg
self.isLocationPic = true
self.isNew = true
})
}
// if(assets[0].valueForProperty(ALAssetPropertyType).isEqualToString(ALAssetTypePhoto)){
// [assets enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
// ALAsset *representation = obj;
//
// UIImage *img = [UIImage imageWithCGImage:representation.defaultRepresentation.fullResolutionImage
// scale:representation.defaultRepresentation.scale
// orientation:(UIImageOrientation)representation.defaultRepresentation.orientation];
//
// }];
// }
}
func uzysAssetsPickerControllerDidExceedMaximumNumberOfSelection(picker: UzysAssetsPickerController!) {
MCUtils.showCustomHUD("亲,你传的图片已达到上限", aType: .Warning)
}
func initNavigation() {
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
let navigationTitleAttribute : NSDictionary = NSDictionary(objectsAndKeys: UIColor.whiteColor(),NSForegroundColorAttributeName)
self.navigationController?.navigationBar.titleTextAttributes = navigationTitleAttribute as [NSObject : AnyObject]
self.navigationController?.navigationBar.lt_setBackgroundColor(UIColor(red: 0.247, green: 0.812, blue: 0.333, alpha: 1.00))
var back = UIBarButtonItem(image: UIImage(named: "nav_back"), style: UIBarButtonItemStyle.Bordered, target: self, action: "backToPage")
back.tintColor = UIColor.whiteColor()
self.navigationItem.leftBarButtonItem = back
self.navigationController?.interactivePopGestureRecognizer.delegate = self // 启用 swipe back
var sendButton = UIBarButtonItem()
sendButton.title = "保存"
sendButton.target = self
sendButton.action = Selector("save")
self.navigationItem.rightBarButtonItem = sendButton
}
func backToPage() {
self.navigationController?.popViewControllerAnimated(true)
}
func postHeadInfoToServer() {
if(chosedAvatar != nil){
let dic = [
"flag" : NSString(string: "headImg"),
"userId": appUserIdSave,
"headImg" : chosedAvatar!
]
manager.POST(saveUser_url,
parameters: dic,
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"success"])
if(self.hud != nil){
self.hud?.hide(true)
}
MCUtils.showCustomHUD("保存信息成功", aType: .Success)
isLoginout = true
self.navigationController?.popViewControllerAnimated(true)
}else{
if(self.hud != nil){
self.hud?.hide(true)
}
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"error"])
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
if(self.hud != nil){
self.hud?.hide(true)
}
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"error"])
MCUtils.showCustomHUD("保存信息失败", aType: .Error)
})
}
}
func save(){
MobClick.event("headImgPage", attributes: ["type":"savePic","result":"all"])
if !isNew {
self.navigationController?.popViewControllerAnimated(true)
return
}
if(self.isLocationPic == true){
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud?.labelText = "保存中..."
manager.POST(upload_url,
parameters:nil,
constructingBodyWithBlock: { (formData:AFMultipartFormData!) in
var key = "fileHeadImg"
var value = "fileNameHeadImg.jpg"
var imageData = UIImageJPEGRepresentation(self.avatar.image, 1.0)
formData.appendPartWithFileData(imageData, name: key, fileName: value, mimeType: "image/jpeg")
},
success: { (operation: AFHTTPRequestOperation!,
responseObject: AnyObject!) in
var json = JSON(responseObject)
if "ok" == json["state"].stringValue {
println(json["msg"])
self.chosedAvatar = json["msg"].stringValue
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"success"])
self.postHeadInfoToServer()
}else{
self.hud?.hide(true)
MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error)
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"error"])
}
},
failure: { (operation: AFHTTPRequestOperation!,
error: NSError!) in
// println("Error: " + error.localizedDescription)
self.hud?.hide(true)
MCUtils.showCustomHUD("图片上传失败,请稍候再试", aType: .Error)
MobClick.event("headImgPage", attributes: ["type":"addPic","result":"error"])
})
}else{
hud = MBProgressHUD.showHUDAddedTo(view, animated: true)
hud?.labelText = "保存中"
self.postHeadInfoToServer()
}
}
func choseAvatar(){
if chosedAvatar == nil || self.avatar == nil {
return
}
var a_url = chosedAvatar!.hasPrefix("http://") ? chosedAvatar! : imgPrex + chosedAvatar!
self.avatar.sd_setImageWithURL(NSURL(string: a_url))
// GTUtil.loadImage( a_url, callback: {
// (img:UIImage?)->Void in
// self.avatar.image = img
// })
}
func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
chosedAvatar = avatars[indexPath.row]
isNew = true
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
collectionView.frame.size.height = CGFloat(50 * avatars.count)
return avatars.count
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
var chosing = collectionView.dequeueReusableCellWithReuseIdentifier("avt", forIndexPath: indexPath) as! AvatarHolder
chosing.url = imgPrex + avatars[indexPath.row]
return chosing
}
class func changeAvatar(ctl:UINavigationController,url:String?){
var avatar_view = UIStoryboard(name: "profile_layout", bundle: nil).instantiateViewControllerWithIdentifier("avatar_chose") as! Avatar
avatar_view.chosedAvatar = url
ctl.pushViewController(avatar_view, animated: true)
}
override func viewWillAppear(animated: Bool) {
self.tabBarController?.tabBar.hidden = true
MobClick.beginLogPageView("userInfoSetHeadImg")
}
override func viewWillDisappear(animated: Bool) {
self.tabBarController?.tabBar.hidden = false
MobClick.endLogPageView("userInfoSetHeadImg")
}
}
class AvatarHolder:UICollectionViewCell{
@IBOutlet weak var holder: UIImageView!
var url:String?{
didSet{
self.holder.sd_setImageWithURL(NSURL(string: url!))
}
}
}
|
mit
|
c222c38b86e877bd70fae7b671c225b2
| 36.677632 | 145 | 0.572776 | 5.063218 | false | false | false | false |
RemyDCF/tpg-offline
|
tpg offline Siri/SiriExtensions.swift
|
1
|
8305
|
//
// SiriExtensions.swift
// tpg offline - Siri
//
// Created by Rémy on 14/06/2018.
// Copyright © 2018 Remy. All rights reserved.
//
import UIKit
extension String {
var time: String {
if Int(self) ?? 0 > 60 {
let hour = (Int(self) ?? 0) / 60
let minutes = (Int(self) ?? 0) % 60
return "\(hour)h\(minutes < 10 ? "0\(minutes)" : "\(minutes)")"
} else {
return self
}
}
var accessibleTime: String {
if Int(self) ?? 0 > 60 {
let hour = (Int(self) ?? 0) / 60
let minutes = (Int(self) ?? 0) % 60
return String(format: "%@ hours %@".localized, "\(hour)",
minutes < 10 ? "0\(minutes)" : "\(minutes)")
} else {
return self
}
}
static func random(_ length: Int) -> String {
let letters: NSString =
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789-_"
let len = UInt32(letters.length)
var randomString = ""
for _ in 0 ..< length {
let rand = arc4random_uniform(len)
var nextChar = letters.character(at: Int(rand))
randomString += NSString(characters: &nextChar, length: 1) as String
}
return randomString
}
var escaped: String {
let listOfOccurencies = [
"berner": "bernex",
"on est": "onex",
"nancy": "lancy",
"cinq": "st",
"saint": "st",
"argent": "archamps",
"veuillat": "feuillat",
"plus air": "r",
"plus r": "r"
]
var p = self
.folding(options: NSString.CompareOptions.diacriticInsensitive,
locale: Locale.current)
.replacingOccurrences(of: " ", with: "")
.replacingOccurrences(of: "+", with: "")
.replacingOccurrences(of: "-", with: "")
.lowercased()
for (k, v) in listOfOccurencies {
p = p.replacingOccurrences(of: k, with: v)
}
return p
}
var localized: String {
return NSLocalizedString(self,
tableName: nil,
bundle: Bundle.main,
value: "",
comment: "")
}
func score(word: String, fuzziness: Double? = nil) -> Double {
// If the string is equal to the word, perfect match.
if self == word {
return 1
}
//if it's not a perfect match and is empty return 0
if word.isEmpty || self.isEmpty {
return 0
}
var
runningScore = 0.0,
charScore = 0.0,
finalScore = 0.0,
string = self,
lString = string.lowercased(),
strLength = string.count,
lWord = word.lowercased(),
wordLength = word.count,
idxOf: String.Index!,
startAt = lString.startIndex,
fuzzies = 1.0,
fuzzyFactor = 0.0,
fuzzinessIsNil = true
// Cache fuzzyFactor for speed increase
if let fuzziness = fuzziness {
fuzzyFactor = 1 - fuzziness
fuzzinessIsNil = false
}
for i in 0 ..< wordLength {
// Find next first case-insensitive match of word's i-th character.
// The search in "string" begins at "startAt".
if let range = lString.range(of:
String(lWord[lWord.index(lWord.startIndex, offsetBy: i)] as Character),
options: NSString.CompareOptions.caseInsensitive,
range: (startAt..<lString.endIndex),
locale: nil
) {
// start index of word's i-th character in string.
idxOf = range.lowerBound
if startAt == idxOf {
// Consecutive letter & start-of-string Bonus
charScore = 0.7
} else {
charScore = 0.1
// Acronym Bonus
// Weighing Logic: Typing the first character of an acronym is as if you
// preceded it with two perfect character matches.
if string[string.index(idxOf, offsetBy: -1)] == " " {
charScore += 0.8
}
}
} else {
// Character not found.
if fuzzinessIsNil {
// Fuzziness is nil. Return 0.
return 0
} else {
fuzzies += fuzzyFactor
continue
}
}
// Same case bonus.
if string[idxOf] == word[word.index(word.startIndex, offsetBy: i)] {
charScore += 0.1
}
// Update scores and startAt position for next round of indexOf
runningScore += charScore
startAt = string.index(idxOf, offsetBy: 1)
}
// Reduce penalty for longer strings.
finalScore = 0.5
* (runningScore / Double(strLength) + runningScore / Double(wordLength))
/ fuzzies
if (lWord[lWord.startIndex] == lString[lString.startIndex]),
(finalScore < 0.85) {
finalScore += 0.15
}
return finalScore
}
}
extension Collection {
subscript (safe index: Index) -> Element? {
return indices.contains(index) ? self[index] : nil
}
}
extension Array {
mutating func rearrange(from: Int, to: Int) {
insert(remove(at: from), at: to)
}
}
public extension Sequence where Iterator.Element: Hashable {
var uniqueElements: [Iterator.Element] {
return Array( Set(self) )
}
}
public extension Sequence where Iterator.Element: Equatable {
var uniqueElements: [Iterator.Element] {
return self.reduce([]) { uniqueElements, element in
uniqueElements.contains(element)
? uniqueElements
: uniqueElements + [element]
}
}
}
extension UIColor {
func lighten(by percentage: CGFloat=0.3) -> UIColor {
return self.adjust(by: abs(percentage) )
}
func darken(by percentage: CGFloat=0.3) -> UIColor {
return self.adjust(by: -1 * abs(percentage) )
}
func adjust(by percentage: CGFloat=0.3) -> UIColor {
var r: CGFloat=0, g: CGFloat=0, b: CGFloat=0, a: CGFloat=0
if self.getRed(&r, green: &g, blue: &b, alpha: &a) {
return UIColor(red: min(r + percentage, 1.0),
green: min(g + percentage, 1.0),
blue: min(b + percentage, 1.0),
alpha: a)
} else {
print("Color adjustement failed")
return self
}
}
public var contrast: UIColor {
var color = self
if cgColor.pattern != nil {
let size = CGSize(width: 1, height: 1)
UIGraphicsBeginImageContext(size)
let context = UIGraphicsGetCurrentContext()
context?.interpolationQuality = .medium
let image = UIImage()
image.draw(in: CGRect(origin: CGPoint(x: 0, y: 0), size: size),
blendMode: .copy,
alpha: 1)
let dataPointer = context?.data?.assumingMemoryBound(to: UInt8.self)
let data = UnsafePointer<UInt8>(dataPointer)
color = UIColor(red: CGFloat(data![2] / 255),
green: CGFloat(data![1] / 255),
blue: CGFloat(data![0] / 255),
alpha: 1)
UIGraphicsEndImageContext()
}
var luminance: CGFloat = 0
var red: CGFloat = 0
var green: CGFloat = 0
var blue: CGFloat = 0
var alpha1: CGFloat = 0
color.getRed(&red, green: &green, blue: &blue, alpha: &alpha1)
red *= 0.2126
green *= 0.7152
blue *= 0.0722
luminance = red + green + blue
return luminance > 0.6 ? .black : .white
}
convenience init?(hexString: String) {
var cString: String = hexString
.trimmingCharacters(in: .whitespacesAndNewlines)
.uppercased()
if cString.hasPrefix("#") {
cString.remove(at: cString.startIndex)
}
if (cString.count) != 6 {
return nil
}
var rgbValue: UInt32 = 0
Scanner(string: cString).scanHexInt32(&rgbValue)
self.init(red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0,
green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0,
blue: CGFloat(rgbValue & 0x0000FF) / 255.0,
alpha: CGFloat(1.0))
}
var hexValue: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(
format: "#%02X%02X%02X",
Int(r * 0xff),
Int(g * 0xff),
Int(b * 0xff)
)
}
}
struct App {
static var apnsToken = ""
static var automaticDeparturesDownload = true
static var stops: [Stop] = []
static var darkMode = false
static var intentsVersionNumber: NSNumber = 1.0
}
|
mit
|
3d265b7021ae051f79a9d61fa9c4cc58
| 25.442675 | 84 | 0.567987 | 3.931345 | false | false | false | false |
supermarin/Swifternalization
|
SwifternalizationTests/InequalityExtendedExpressionMatcherTests.swift
|
1
|
1716
|
//
// InequalityExtendedExpressionMatcherTests.swift
// Swifternalization
//
// Created by Tomasz Szulc on 27/06/15.
// Copyright (c) 2015 Tomasz Szulc. All rights reserved.
//
import UIKit
import XCTest
import Swifternalization
class InequalityExtendedExpressionMatcherTests: XCTestCase {
func testValidation1() {
let matcher = InequalityExtendedExpressionParser("iex:4<%d<6").parse() as! InequalityExtendedExpressionMatcher
XCTAssertTrue(matcher.validate("5"), "should be true")
XCTAssertFalse(matcher.validate("4"), "should be false")
XCTAssertFalse(matcher.validate("6"), "should be false")
}
func testValidation2() {
let matcher = InequalityExtendedExpressionParser("iex:4<=%d<10").parse() as! InequalityExtendedExpressionMatcher
XCTAssertTrue(matcher.validate("4"), "should be true")
XCTAssertFalse(matcher.validate("10"), "should be false")
XCTAssertFalse(matcher.validate("11"), "should be false")
}
func testValidation3() {
let matcher = InequalityExtendedExpressionParser("iex:4>%d<10").parse() as! InequalityExtendedExpressionMatcher
XCTAssertTrue(matcher.validate("3"), "should be true")
XCTAssertFalse(matcher.validate("5"), "should be false")
XCTAssertFalse(matcher.validate("11"), "should be false")
}
func testValidation4() {
let matcher = InequalityExtendedExpressionParser("iex:4=%d=10").parse() as! InequalityExtendedExpressionMatcher
XCTAssertFalse(matcher.validate("4"), "should be false")
XCTAssertFalse(matcher.validate("10"), "should be false")
XCTAssertFalse(matcher.validate("8"), "should be false")
}
}
|
mit
|
50ce6ddf41a393f4c0e37c9af2053b62
| 39.857143 | 120 | 0.695804 | 4.588235 | false | true | false | false |
igormatyushkin014/Sensitive
|
Source/Classes/Recognizers/ScreenEdgePan/ScreenEdgePanGestureRecognizer.swift
|
1
|
1483
|
//
// ScreenEdgePanGestureRecognizer.swift
// Sensitive
//
// Created by Igor Matyushkin on 04.01.16.
// Copyright © 2016 Igor Matyushkin. All rights reserved.
//
import UIKit
public class ScreenEdgePanGestureRecognizer: UIScreenEdgePanGestureRecognizer, UIGestureRecognizerDelegate {
// MARK: Class variables & properties
// MARK: Class methods
// MARK: Initializers
public init(handler: @escaping GestureRecognizerHandler<UIScreenEdgePanGestureRecognizer>) {
super.init(target: nil, action: nil)
self.handler = handler
self.recognizeSimultaneouslyWithOtherGestures = true
self.addTarget(self, action: #selector(runHandler))
}
// MARK: Deinitializer
deinit {
}
// MARK: Variables & properties
fileprivate var handler: GestureRecognizerHandler<UIScreenEdgePanGestureRecognizer>?
public var recognizeSimultaneouslyWithOtherGestures: Bool {
get {
return self.delegate === self
}
set {
self.delegate = self
}
}
// MARK: Public methods
// MARK: Private methods
@objc
internal func runHandler() {
self.handler?(self)
}
// MARK: Protocol methods
public func gestureRecognizer(_ gestureRecognizer: UIGestureRecognizer, shouldRecognizeSimultaneouslyWith otherGestureRecognizer: UIGestureRecognizer) -> Bool {
return true
}
}
|
mit
|
46839ddd59bd2cc98ae768abdb49fe72
| 24.118644 | 164 | 0.655196 | 5.592453 | false | false | false | false |
VBVMI/VerseByVerse-iOS
|
VBVMI/TitleParser.swift
|
1
|
1086
|
//
// TitleParser.swift
// VBVMI
//
// Created by Thomas Carey on 27/02/16.
// Copyright © 2016 Tom Carey. All rights reserved.
//
import Foundation
import Regex
//let greeting = Regex("hello (world|universe|swift)")
//
//if let subject = greeting.match("hello swift")?.captures[0] {
// logger.info("🍕ohai \(subject)")
//}
struct TitleParser {
//Typical Title = "Galatians - Lesson 16B"
fileprivate static let title = Regex("^([^-]+)(\\s*-\\s*(\\w*)\\s*(\\w*[-\\/\\s]*\\w*))?$")
static func match(_ string: String) -> [String?]? {
return title.firstMatch(in: string)?.captures
}
static func components(_ string: String) -> (String?, String?) {
guard let matches = match(string) else {
return (nil, nil)
}
//logger.warning("Matches: \(matches)")
if matches.count == 4 {
return (matches[0]?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines), matches[3]?.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines))
}
return (nil, nil)
}
}
|
mit
|
32d5fe729d404341fb0f21b1344d6f83
| 26.74359 | 165 | 0.593346 | 3.823322 | false | false | false | false |
mercadopago/px-ios
|
ExampleSwift/ExampleSwift/Controllers/CustomCheckoutViewController.swift
|
1
|
4981
|
//
// CustomCheckoutViewController.swift
// ExampleSwift
//
// Created by Eric Ertl on 28/05/2020.
// Copyright © 2020 Juan Sebastian Sanzone. All rights reserved.
//
import UIKit
import MercadoPagoSDKV4
class CustomCheckoutViewController: UIViewController {
@IBOutlet private var localeTextField: UITextField!
@IBOutlet private var publicKeyTextField: UITextField!
@IBOutlet private var preferenceIdTextField: UITextField!
@IBOutlet private var accessTokenTextField: UITextField!
@IBOutlet private var productIdTextField: UITextField!
@IBOutlet private var oneTapSwitch: UISwitch!
@IBAction private func iniciarCheckout(_ sender: Any) {
guard localeTextField.text?.count ?? 0 > 0,
publicKeyTextField.text?.count ?? 0 > 0,
preferenceIdTextField.text?.count ?? 0 > 0 else {
let alert = UIAlertController(
title: "Error",
message: "Complete los campos requeridos para continuar",
preferredStyle: .alert
)
alert.addAction(UIAlertAction(title: "Ok", style: .default, handler: nil))
present(alert, animated: true)
return
}
runMercadoPagoCheckoutWithLifecycle()
}
@IBAction private func restablecerDatos(_ sender: Any) {
localeTextField.text = ""
publicKeyTextField.text = ""
preferenceIdTextField.text = ""
accessTokenTextField.text = ""
productIdTextField.text = ""
oneTapSwitch.setOn(true, animated: true)
}
override func viewDidLoad() {
super.viewDidLoad()
setupGrandient()
setupKeys()
oneTapSwitch.addTarget(self, action: #selector(onChangeSwitchValue), for: .valueChanged)
}
private func runMercadoPagoCheckoutWithLifecycle() {
guard let publicKey = publicKeyTextField.text,
let preferenceId = preferenceIdTextField.text,
let language = localeTextField.text else {
return
}
let builder = MercadoPagoCheckoutBuilder(
publicKey: publicKey,
preferenceId: preferenceId
).setLanguage(language)
if let privateKey = accessTokenTextField.text {
builder.setPrivateKey(key: privateKey)
}
if oneTapSwitch.isOn {
let advancedConfiguration = PXAdvancedConfiguration()
if let productId = productIdTextField.text {
advancedConfiguration.setProductId(id: productId)
}
builder.setAdvancedConfiguration(config: advancedConfiguration)
}
let checkout = MercadoPagoCheckout(builder: builder)
if let myNavigationController = navigationController {
checkout.start(navigationController: myNavigationController, lifeCycleProtocol: self)
}
}
private func setupGrandient() {
let gradient = CAGradientLayer()
gradient.frame = view.bounds
let col1 = UIColor(red: 34.0 / 255.0, green: 211 / 255.0, blue: 198 / 255.0, alpha: 1)
let col2 = UIColor(red: 145 / 255.0, green: 72.0 / 255.0, blue: 203 / 255.0, alpha: 1)
gradient.colors = [col1.cgColor, col2.cgColor]
view.layer.insertSublayer(gradient, at: 0)
}
private func setupKeys() {
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let infoPlist = NSDictionary(contentsOfFile: path) {
// Initialize values from config
publicKeyTextField.text = infoPlist["PX_COLLECTOR_PUBLIC_KEY"] as? String
accessTokenTextField.text = infoPlist["PX_PAYER_PRIVATE_KEY"] as? String
}
localeTextField.text = "es-AR"
preferenceIdTextField.text = "737302974-34e65c90-62ad-4b06-9f81-0aa08528ec53"
productIdTextField.text = "BJEO9NVBF6RG01IIIOTG"
}
@objc
private func onChangeSwitchValue() {
productIdTextField.isEnabled = oneTapSwitch.isOn
productIdTextField.layer.opacity = oneTapSwitch.isOn ? 1 : 0.6
}
}
// MARK: Optional Lifecycle protocol implementation example.
extension CustomCheckoutViewController: PXLifeCycleProtocol {
func finishCheckout() -> ((PXResult?) -> Void)? {
nil
}
func cancelCheckout() -> (() -> Void)? {
nil
}
func changePaymentMethodTapped() -> (() -> Void)? {
{ () in
print("px - changePaymentMethodTapped")
}
}
}
extension CustomCheckoutViewController: UITextFieldDelegate {
func textFieldDidBeginEditing(_ textField: UITextField) {
textField.text = ""
}
func textField(
_ textField: UITextField,
shouldChangeCharactersIn range: NSRange,
replacementString string: String
) -> Bool {
string == " " ? false : true
}
func textFieldDidEndEditing(_ textField: UITextField) {
textField.text = textField.text?.trimmingCharacters(in: .whitespacesAndNewlines)
}
}
|
mit
|
4ba2f33737f7890c00b20e06fadb2f91
| 32.648649 | 97 | 0.644177 | 4.844358 | false | false | false | false |
mercadopago/px-ios
|
MercadoPagoSDK/MercadoPagoSDK/UI/Base/MPTextView.swift
|
1
|
1306
|
import UIKit
class MPTextView: UITextView {
override public init(frame: CGRect, textContainer: NSTextContainer?) {
super.init(frame: frame, textContainer: textContainer)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
func addCharactersSpacing(_ spacing: CGFloat) {
let attributedString = NSMutableAttributedString()
if self.attributedText != nil {
attributedString.append(self.attributedText!)
}
attributedString.addAttribute(NSAttributedString.Key.kern, value: spacing, range: NSRange(location: 0, length: self.attributedText!.length))
self.attributedText = attributedString
}
func addLineSpacing(_ lineSpacing: Float) {
let attributedString = NSMutableAttributedString()
if self.attributedText != nil {
attributedString.append(self.attributedText!)
}
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = CGFloat(lineSpacing)
paragraphStyle.alignment = .center
attributedString.addAttribute(NSAttributedString.Key.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attributedString.length))
self.attributedText = attributedString
}
}
|
mit
|
f3bdc6eb650d7768a004f7d95ae4c4de
| 37.411765 | 161 | 0.69755 | 5.60515 | false | false | false | false |
Faifly/FFUtils
|
FFUtils/FFUtils/String+Custom.swift
|
1
|
1457
|
//
// String+Custom.swift
// FFUtils
//
// Created by Artem Kalmykov on 9/26/16.
// Copyright © 2016 Faifly. All rights reserved.
//
import Foundation
extension String
{
/// String length
public var length: Int
{
return self.characters.count
}
/// Search
public func corresponds(toSearchString searchString: String) -> Bool
{
return self.range(of: searchString, options: [.caseInsensitive, .diacriticInsensitive]) != nil
}
/// Empty
public static func isEmpty(_ string: String?) -> Bool
{
if string == nil
{
return true
}
else if string!.length == 0
{
return true
}
else
{
return false
}
}
public var isValidEmail: Bool
{
let emailRegEx = "[a-zA-Z0-9\\'\\+\\-\\_\\%\\.]{2,256}" +
"\\@" + "[a-zA-Z0-9][a-zA-Z0-9\\-]{0,64}" + "(" +
"\\." +
"[a-zA-Z0-9][a-zA-Z0-9\\-]{1,25}" +
")+"
let emailTest = NSPredicate(format:"SELF MATCHES %@", emailRegEx)
return emailTest.evaluate(with: self)
}
public var removingHTMLTags: String
{
return self.replacingOccurrences(of: "<[^>]+>", with: "", options: .regularExpression, range: nil)
}
}
/// Localization
public func LocalizedString(_ string: String) -> String
{
return NSLocalizedString(string, comment: "")
}
|
mit
|
0976c5f26009770ee2933e867b5dc128
| 22.111111 | 106 | 0.528846 | 3.989041 | false | false | false | false |
fanyu/EDCCharla
|
EDCChat/EDCChat/EDCChatStatusView.swift
|
1
|
2158
|
//
// EDCChatStatusView.swift
// EDCChat
//
// Created by FanYu on 10/12/2015.
// Copyright © 2015 FanYu. All rights reserved.
//
import UIKit
enum EDCChatStatus {
case None
case Waiting
case Failed
}
class EDCChatStatusView: UIControl {
private var showView: UIView?
override func intrinsicContentSize() -> CGSize {
return CGSizeMake(20, 20)
}
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var status = EDCChatStatus.None {
willSet {
if newValue != status {
var nv: UIView?
switch newValue {
case .Waiting:
let indicator = showView as? UIActivityIndicatorView ?? UIActivityIndicatorView(activityIndicatorStyle: .Gray)
indicator.hidesWhenStopped = true
nv = indicator
case .Failed:
let btn = showView as? UIButton ?? UIButton()
btn.setImage(EDCChatImageManager.messageFail, forState: .Normal)
btn.addTarget(self, action: "resendButtonTapped:", forControlEvents: .TouchUpInside)
nv = btn
default:
break
}
if nv != showView {
showView?.removeFromSuperview()
if let nv = nv {
nv.frame = bounds
nv.autoresizingMask = [.FlexibleWidth, .FlexibleHeight]
addSubview(nv)
}
showView = nv
}
}
if let av = showView as? UIActivityIndicatorView where !av.isAnimating() {
av.startAnimating()
}
}
}
}
extension EDCChatStatusView {
private dynamic func resendButtonTapped(sender: AnyObject) {
self.sendActionsForControlEvents(.TouchUpInside)
}
}
|
mit
|
191cf9308d2660011c85eb4f4128f1d3
| 25.304878 | 130 | 0.508577 | 5.617188 | false | false | false | false |
Khmelevsky/QuickForms
|
Sources/Validators/Regex.swift
|
1
|
1620
|
//
// Regex.swift
// QuickForms
//
// Created by Alexander Khmelevsky on 20.12.16.
// Copyright © 2016 Alexander Khmelevsky. All rights reserved.
//
import Foundation
extension Validators {
public static func RegEx(pattern: String, message: String, configuration:((_ options:inout NSRegularExpression.Options, _ matchingOptions:inout NSRegularExpression.MatchingOptions)->())? = nil) -> Validator<String> {
return RegexValidator(pattern: pattern, message: message, configuration: configuration)
}
}
class RegexValidator: Validator<String> {
var pattern:String
var message:String
var options:NSRegularExpression.Options = []
var matchingOptions: NSRegularExpression.MatchingOptions = []
init(pattern: String, message: String, configuration:((_ options:inout NSRegularExpression.Options, _ matchingOptions:inout NSRegularExpression.MatchingOptions)->())? = nil) {
self.pattern = pattern
self.message = message
configuration?(&options,&matchingOptions)
}
override open func validate(value: String?) -> [Swift.Error] {
guard let value = value else {
assertionFailure("Add requared validator")
return []
}
if let regex = try? NSRegularExpression(pattern: pattern, options: options) {
return regex.firstMatch(in: value, options: matchingOptions, range: NSRange(location: 0, length: (value as NSString).length)) != nil ? [] : [Form.makeError(message: message)]
} else {
assertionFailure("Pattern error")
return []
}
}
}
|
mit
|
cb44de6fc0d3d0aaa7e60b8e90fcb313
| 34.977778 | 220 | 0.668314 | 4.891239 | false | true | false | false |
katalisha/ga-mobile
|
ToDo - completed/ToDo/LoginViewController.swift
|
2
|
2852
|
//
// LoginViewController.swift
// ToDo
//
// Created by Ryan Blunden on 28/04/2015.
// Copyright (c) 2015 RabbitBird Pty Ltd. All rights reserved.
//
import Foundation
import UIKit
let EMAIL_MIN_LENGTH = 8
let PASSWORD_MIN_LENGTH = 8
class LoginViewController: UIViewController, UITextFieldDelegate {
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var loginButton: UIButton!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
let authDataManager:AuthDataManager
required init(coder aDecoder: NSCoder) {
authDataManager = AuthDataManager()
super.init(coder: aDecoder)
}
override func viewDidLoad() {
title = "ToDo App"
activityIndicator.stopAnimating()
styleLoginButton()
}
func styleLoginButton() {
loginButton.layer.cornerRadius = 5.0
loginButton.layer.masksToBounds = true
}
// Login form API
func textFieldShouldReturn(textField: UITextField) -> Bool {
switch(textField) {
case emailTextField:
emailTextField.resignFirstResponder()
passwordTextField.becomeFirstResponder()
case passwordTextField:
passwordTextField.resignFirstResponder()
doLogin()
default:
break
}
return true
}
@IBAction func onLoginButtonTapped(sender: AnyObject) {
doLogin()
}
// MARK: Form validation and processing
func isLoginFormValid() -> Bool {
return count(emailTextField.text) > EMAIL_MIN_LENGTH && count(passwordTextField.text) >= PASSWORD_MIN_LENGTH
}
// MARK: Login processing
func doLogin() {
if(!isLoginFormValid()) {
displayMessage("Email or password is invalid")
}
else {
setLoginFormState(false)
authDataManager.processLogin(emailTextField.text, password:passwordTextField.text) { (result) -> Void in
if(result) {
self.displayMessage("Successfully logged in!")
}
else {
self.displayMessage("Sorry, a matching email and/or password was not found in our system.")
}
self.setLoginFormState(true)
}
}
}
func setLoginFormState(enabled: Bool) {
emailTextField.enabled = enabled
passwordTextField.enabled = enabled
loginButton.enabled = enabled
if(enabled) {
activityIndicator.stopAnimating()
}
else {
activityIndicator.startAnimating()
}
}
// MARK: Present feedback to user
func displayMessage(message:String) {
let alertViewController = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
alertViewController.addAction(UIAlertAction(title: "OK!", style: UIAlertActionStyle.Default, handler: nil))
presentViewController(alertViewController, animated: true, completion: nil)
}
}
|
gpl-3.0
|
7e6dca81182d52258ee7a1848a961602
| 24.247788 | 112 | 0.684783 | 4.891938 | false | false | false | false |
mlilback/rc2SwiftClient
|
MacClient/prefs/TemplatesPrefsController.swift
|
1
|
24504
|
//
// TemplatesPrefsController.swift
//
// Copyright ©2017 Mark Lilback. This file is licensed under the ISC license.
//
import Cocoa
import Rc2Common
import ClientCore
import ReactiveSwift
import ReactiveCocoa
import SwiftyUserDefaults
import MJLLogger
// MARK: - UserDefaults support for saving TemplateType values
private extension DefaultsKeys {
static let lastTemplateType = DefaultsKey<TemplateType>("prefsTemplateType", defaultValue: .markdown)
}
//extension UserDefaults {
// subscript(key: DefaultsKey<TemplateType>) -> TemplateType {
// get { return unarchive(key) ?? .markdown }
// set { archive(key, newValue) }
// }
//}
// MARK: - outline cell identifiers
extension NSUserInterfaceItemIdentifier {
static let templateName = NSUserInterfaceItemIdentifier(rawValue: "name")
}
// MARK: - main controller
class TemplatesPrefsController: NSViewController {
let templatePasteboardType = NSPasteboard.PasteboardType(rawValue: "io.rc2.client.codeTemplate")
// MARK: properties
@IBOutlet private var splitterView: NSSplitView!
@IBOutlet private var markdownButton: NSButton!
@IBOutlet private var rCodeButton: NSButton!
@IBOutlet private var equationButton: NSButton!
@IBOutlet private var codeOutlineView: NSOutlineView!
@IBOutlet private var addButton: NSButton!
@IBOutlet private var addCategoryButton: NSButton!
@IBOutlet private var removeButton: NSButton!
@IBOutlet private var nameEditField: NSTextField!
@IBOutlet private var codeEditView: NSTextView!
var templateManager: CodeTemplateManager!
private var currentCategories: [CodeTemplateCategory] = []
private var editingDisposables = CompositeDisposable()
private var currentType: TemplateType = .markdown
private var currentTemplate: CodeTemplate?
private let _undoManager = UndoManager()
// swiftlint:disable:next force_try
private let selectionMarkerRegex = try! NSRegularExpression(pattern: CodeTemplate.selectionTemplateKey, options: [.caseInsensitive, .ignoreMetacharacters])
private let selectionMarkerColor = NSColor(calibratedRed: 0.884, green: 0.974, blue: 0.323, alpha: 1.0)
private var lastSelectionMarkerRange: NSRange?
private var manuallyExpanding: Bool = false
override var undoManager: UndoManager? { return _undoManager }
override var acceptsFirstResponder: Bool { return true }
// MARK: - methods
override func viewDidLoad() {
super.viewDidLoad()
codeOutlineView.dataSource = self
codeOutlineView.delegate = self
splitterView.delegate = self
nameEditField.delegate = self
codeEditView.delegate = self
switchTo(type: UserDefaults.standard[.lastTemplateType])
// setup add template icon
let folderImage = NSImage(named: NSImage.folderName)!
let addImage = NSImage(named: NSImage.actionTemplateName)!
folderImage.overlay(image: addImage)
addCategoryButton.image = folderImage
codeOutlineView.registerForDraggedTypes([templatePasteboardType])
codeOutlineView.setDraggingSourceOperationMask([.move, .copy], forLocal: true)
}
override func viewDidDisappear() {
super.viewDidDisappear()
_ = try? templateManager.saveAll()
}
@objc func validateMenuItem(_ menuItem: NSMenuItem) -> Bool {
guard let action = menuItem.action else { return false }
switch action {
case #selector(addTemplate(_:)),
#selector(duplicateSelection(_:)),
#selector(deleteBackward(_:)): // something must be selected
return codeOutlineView.selectedRow != -1
case #selector(addCategory(_:)):
return true
default:
return false
}
}
func switchTo(type: TemplateType) {
switch type {
case .markdown:
markdownButton.state = .on
rCodeButton.state = .off
equationButton.state = .off
currentCategories = templateManager.categories(for: .markdown)
case .rCode:
rCodeButton.state = .on
markdownButton.state = .off
equationButton.state = .off
currentCategories = templateManager.categories(for: .rCode)
case .equation:
equationButton.state = .on
markdownButton.state = .off
rCodeButton.state = .off
currentCategories = templateManager.categories(for: .equation)
}
print("curCats = \(type) \(currentCategories.count)")
UserDefaults.standard[.lastTemplateType] = type
currentType = type
codeOutlineView.reloadData()
}
// MARK: - actions
@IBAction func switchType(_ sender: Any?) {
guard let button = sender as? NSButton else { return }
switch button {
case markdownButton:
switchTo(type: .markdown)
case rCodeButton:
switchTo(type: .rCode)
case equationButton:
switchTo(type: .equation)
default:
fatalError("invalid action sender")
}
}
@IBAction func duplicateSelection(_ sender: Any?) {
}
@IBAction override func deleteBackward(_ sender: Any?) {
guard let selItem = selectedItem else { fatalError("how was delete called with no selection?") }
guard let cat = selItem as? CodeTemplateCategory else {
// swiftlint:disable:next force_cast
delete(template: selItem as! CodeTemplate)
return
}
delete(category: cat)
}
/// adds a CodeTemplate
@IBAction func addTemplate(_ sender: Any?) {
guard let selection = selectedItem else { fatalError("adding template w/o selection") }
var parent: CodeTemplateCategory
var newIndex: Int
if selection is CodeTemplate {
// add after this one
// swiftlint:disable:next force_cast
parent = codeOutlineView.parent(forItem: selection) as! CodeTemplateCategory
newIndex = codeOutlineView.childIndex(forItem: selection) + 1
} else { // is a category
// swiftlint:disable:next force_cast
parent = selection as! CodeTemplateCategory
newIndex = 0
}
// have to be expanded to insert an item
if !codeOutlineView.isItemExpanded(parent) {
codeOutlineView.expandItem(parent)
}
let template = CodeTemplate(name: "Untitled", contents: "", type: currentType)
undoManager?.registerUndo(withTarget: self) { [theTemplate = template] (me) -> Void in
me.remove(template: theTemplate)
}
insert(template: template, in: parent, at: newIndex)
view.window?.makeFirstResponder(nameEditField)
}
/// adds a CodeTemplateCategory
@IBAction func addCategory(_ sender: Any?) {
var newIndex: Int = currentCategories.count
var newGroup: CodeTemplateCategory
defer {
insert(category: newGroup, at: newIndex)
codeOutlineView.expandItem(newGroup)
view.window?.makeFirstResponder(nameEditField)
}
guard let selection = selectedItem else {
newIndex = currentCategories.count
newGroup = templateManager.createCategory(of: currentType, at: newIndex)
return
}
if selection is CodeTemplate {
let parent = codeOutlineView.parent(forItem: selection)!
let destIndex = codeOutlineView.childIndex(forItem: parent)
newGroup = templateManager.createCategory(of: currentType, at: destIndex)
newIndex = destIndex
} else { // selection is category
newIndex = codeOutlineView.childIndex(forItem: selection)
newGroup = templateManager.createCategory(of: currentType, at: newIndex)
}
}
}
// MARK: - NSOutlineViewDataSource
extension TemplatesPrefsController: NSOutlineViewDataSource {
func outlineView(_ outlineView: NSOutlineView, numberOfChildrenOfItem item: Any?) -> Int {
if item == nil { return currentCategories.count }
guard let category = item as? CodeTemplateCategory else { return 0 }
return category.templates.value.count
}
func outlineView(_ outlineView: NSOutlineView, child index: Int, ofItem item: Any?) -> Any {
if item == nil { return currentCategories[index] }
guard let category = item as? CodeTemplateCategory else { fatalError() }
return category.templates.value[index]
}
func outlineView(_ outlineView: NSOutlineView, isItemExpandable item: Any) -> Bool {
return item is CodeTemplateCategory
}
func outlineView(_ outlineView: NSOutlineView, objectValueFor tableColumn: NSTableColumn?, byItem item: Any?) -> Any? {
return item
}
// implement so autosave expanded items works, or manually implement
// func outlineView(_ outlineView: NSOutlineView, persistentObjectForItem item: Any?) -> Any? {
//
// }
func outlineView(_ outlineView: NSOutlineView, writeItems items: [Any], to pasteboard: NSPasteboard) -> Bool
{
guard items.count == 1, let item = items[0] as? CodeTemplateObject else { return false }
let wrapper = DragData(item, path: indexPath(for: item))
pasteboard.setData(wrapper.encode(), forType: templatePasteboardType)
return true
}
// swiftlint:disable:next cyclomatic_complexity
func outlineView(_ outlineView: NSOutlineView, validateDrop info: NSDraggingInfo, proposedItem parentItem: Any?, proposedChildIndex index: Int) -> NSDragOperation
{
guard let wrapperData = info.draggingPasteboard.data(forType: templatePasteboardType),
let wrapper = try? JSONDecoder().decode(DragData.self, from: wrapperData)
else { print("asked to validate invalid drag data"); return [] }
// { Log.warn("asked to validate invalid drag data", .app); } // return [] }
let targetObj = parentItem as? CodeTemplateObject
let fromPath = wrapper.indexPath
let dropOperation = (info.draggingSourceOperationMask == .copy) ? NSDragOperation.copy : NSDragOperation.move
// print("validate drop of \(wrapper.indexPath) to \(destObj?.description ?? "root") @ \(index)")
// If we're dragging a Category:
if wrapper.isCategory {
switch targetObj {
case nil where index >= 0: // proposed is root, which is fine
return dropOperation
case is CodeTemplateCategory:
let targetIndex = outlineView.childIndex(forItem: targetObj!) + 1
// print("Category, new idx: \(targetIndex)")
outlineView.setDropItem(nil, dropChildIndex: targetIndex)
case is CodeTemplate:
let targetIndex = outlineView.childIndex(forItem: outlineView.parent(forItem: targetObj!)!) + 1
// print("Template, new idx: \(targetIndex)")
outlineView.setDropItem(nil, dropChildIndex: targetIndex)
default:
return []
}
return dropOperation
}
// If we're dragging a Template:
else if fromPath.count == 2 {
switch targetObj {
case nil: // don't allow a template at the root level
return []
case is CodeTemplateCategory:
return dropOperation
case is CodeTemplate:
let targetIndex = outlineView.childIndex(forItem: targetObj!) + 1
let parent = outlineView.parent(forItem: targetObj!)!
// print("\(parent) \(targetIndex)")
outlineView.setDropItem(parent, dropChildIndex: targetIndex)
default:
return []
}
}
return dropOperation
}
func outlineView(_ outlineView: NSOutlineView, acceptDrop info: NSDraggingInfo, item parentItem: Any?, childIndex index: Int) -> Bool
{
// wrapper is not identical object
guard let wrapperData = info.draggingPasteboard.data(forType: templatePasteboardType),
let wrapper = try? JSONDecoder().decode(DragData.self, from: wrapperData)
else { print("asked to acceptDrop invalid drag data"); return false }
// let srcIndex = outlineView.childIndex(forItem: wrapper.item)
// let targetObj = parentItem as? CodeTemplateCategory
let fromPath = wrapper.indexPath
let isCopy = info.draggingSourceOperationMask == .copy
let op = isCopy ? "copy" : "move"
let out = op + " from \(fromPath), to \(index), parent: " + String(describing: parentItem)
Log.debug(out, .app)
// If we're dragging a Category:
if wrapper.isCategory {
let fromIndex = fromPath[0]
// print("dropping on \(targetObj?.description ?? "nil") idx \(index) from \(wrapper.indexPath)")
var toIndex = (index == -1) ? 0 : index // currentCategories.count - 1
if toIndex > fromIndex { toIndex -= 1 }
if toIndex >= currentCategories.count { toIndex -= 1 }
// print("from \(fromIndex), to \(toIndex)")
if isCopy {
//>>>TEST:
let newCat = CodeTemplateCategory(wrapper.category!)
currentCategories.insert(newCat, at: toIndex)
codeOutlineView.insertItems(at: IndexSet(integer: toIndex), inParent: nil, withAnimation: .effectGap)
} else {
//currentCategories.moveElement(from: fromIndex, to: toIndex)
let item = currentCategories.remove(at: fromIndex)
currentCategories.insert(item, at: toIndex)
if toIndex >= currentCategories.count { toIndex -= 1 }
codeOutlineView.moveItem(at: fromIndex, inParent: nil, to: toIndex, inParent: nil)
}
return true
}
// If we're dragging a Template:
if let toCat = parentItem as? CodeTemplateCategory, fromPath.count == 2,
let item = wrapper.item as? CodeTemplate {
// let fromCat = outlineView.parent(forItem: item) as! CodeTemplateCategory
// let fromCat = codeOutlineView.parent(forItem: item) as! CodeTemplateCategory
let fromCat = currentCategories[fromPath[0]]
let fromIndex = fromPath[1]
var toIndex = (index == -1) ? 0 : index // toCat.templates.value.count-1
if toCat == fromCat {
if toIndex > fromIndex { toIndex -= 1 }
}
// let toCatIndex = outlineView.childIndex(forItem: toCat)
// print("item \(item) to \(toIndex) in \(toCat)")
if !isCopy {
fromCat.templates.value.remove(at: fromIndex)
codeOutlineView.removeItems(at: IndexSet(integer: fromIndex), inParent: fromCat)
}
self.insert(template: item, in: toCat, at: toIndex)
return true
}
return false
}
}
// MARK: - NSOutlineViewDelegate
extension TemplatesPrefsController: NSOutlineViewDelegate {
func outlineView(_ outlineView: NSOutlineView, viewFor tableColumn: NSTableColumn?, item: Any) -> NSView? {
guard let templateItem = item as? CodeTemplateObject else { fatalError("invalid item") }
// swiftlint:disable:next force_cast
let view = outlineView.makeView(withIdentifier: .templateName, owner: nil) as! TemplateCellView
view.templateItem = templateItem
return view
}
func outlineView(_ outlineView: NSOutlineView, shouldExpandItem item: Any) -> Bool {
let result = item is CodeTemplateCategory
if !manuallyExpanding, NSApp.currentEvent?.modifierFlags.contains(.option) ?? false {
// expand them all
manuallyExpanding = true
DispatchQueue.main.async {
self.codeOutlineView.expandItem(nil, expandChildren: true)
self.manuallyExpanding = false
}
}
return result
}
func outlineView(_ outlineView: NSOutlineView, shouldCollapseItem item: Any) -> Bool {
let result = item is CodeTemplateCategory
if !manuallyExpanding, NSApp.currentEvent?.modifierFlags.contains(.option) ?? false {
// collapse them all
manuallyExpanding = true
DispatchQueue.main.async {
self.codeOutlineView.collapseItem(nil, collapseChildren: true)
self.manuallyExpanding = false
}
}
return result
}
func outlineViewSelectionDidChange(_ notification: Notification) {
editingDisposables.dispose()
editingDisposables = CompositeDisposable()
currentTemplate = nil
let indexes = codeOutlineView.selectedRowIndexes
defer {
nameEditField.isEnabled = indexes.count > 0
removeButton.isEnabled = indexes.count > 0
addButton.isEnabled = indexes.count > 0
}
guard indexes.count > 0 else {
nameEditField.stringValue = ""
codeEditView.textStorage!.setAttributedString(NSAttributedString(string: ""))
return
}
guard let item = codeOutlineView.item(atRow: indexes.first!) else { fatalError("slection not valid object") }
if let cat = item as? CodeTemplateCategory {
editingDisposables += nameEditField.reactive.stringValue <~ cat.name
editingDisposables += cat.name <~ nameEditField.reactive.continuousStringValues
codeEditView.textStorage?.setAttributedString(NSAttributedString(string: ""))
codeEditView.isEditable = false
} else if let template = item as? CodeTemplate {
editingDisposables += nameEditField.reactive.stringValue <~ template.name
editingDisposables += template.name <~ nameEditField.reactive.continuousStringValues
codeEditView.textStorage?.replaceCharacters(in: codeEditView.string.fullNSRange, with: template.contents.value)
// editingDisposables += codeEditView.reactive.textValue <~ template.contents
// editingDisposables += template.contents <~ codeEditView.reactive.continuousStringValues
codeEditView.isEditable = true
currentTemplate = template
colorizeSelectionMarker()
}
}
}
// MARK: - NSSplitViewDelegate
extension TemplatesPrefsController: NSSplitViewDelegate {
func splitView(_ splitView: NSSplitView, constrainMinCoordinate proposedMinimumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat
{
return 120
}
func splitView(_ splitView: NSSplitView, constrainMaxCoordinate proposedMaximumPosition: CGFloat, ofSubviewAt dividerIndex: Int) -> CGFloat
{
return splitView.frame.size.height - 120
}
}
// MARK: - NSTextFieldDelegate
extension TemplatesPrefsController: NSTextFieldDelegate {
func controlTextDidEndEditing(_ obj: Notification) {
_ = try? templateManager.save(type: currentType)
}
}
// MARK: - NSTextViewDelegate
extension TemplatesPrefsController: NSTextViewDelegate {
func textDidChange(_ notification: Notification) {
colorizeSelectionMarker()
if codeEditView.isEditable {
currentTemplate?.contents.value = codeEditView.string
}
}
}
// MARK: - private
extension TemplatesPrefsController {
/// the currently selected template/category, or nil if there is no selection
private var selectedItem: Any? {
let index = codeOutlineView.selectedRow
if index == -1 { return nil }
return codeOutlineView.item(atRow: index)
}
private func indexPath(for item: Any) -> IndexPath {
if let cat = item as? CodeTemplateCategory {
return IndexPath(index: codeOutlineView.childIndex(forItem: cat))
}
guard let template = item as? CodeTemplate, let parent = codeOutlineView.parent(forItem: template) as? CodeTemplateCategory else { fatalError("invalid item") }
return IndexPath(indexes: [codeOutlineView.childIndex(forItem: parent), codeOutlineView.childIndex(forItem: template)])
}
private func colorizeSelectionMarker() {
guard let selMatch = selectionMarkerRegex.firstMatch(in: codeEditView.string, options: [], range: codeEditView.string.fullNSRange)
else { removeSelectionMarker(); return }
let last = lastSelectionMarkerRange ?? NSRange(location: 0, length: 0)
guard last != selMatch.range else { return } // no change
removeSelectionMarker()
codeEditView.layoutManager?.addTemporaryAttribute(.backgroundColor, value: selectionMarkerColor, forCharacterRange: selMatch.range)
lastSelectionMarkerRange = selMatch.range
}
private func removeSelectionMarker() {
if lastSelectionMarkerRange != nil {
// the range might have changed, and we won't know unless we switch to using NSTextStorageDelegate instead of NSTextViewDelegate. so we'll just remove the background color from everywhere
codeEditView.layoutManager?.removeTemporaryAttribute(.backgroundColor, forCharacterRange: codeEditView.string.fullNSRange)
lastSelectionMarkerRange = nil
}
}
/// inserts a new category. separate function for undo
private func insert(category: CodeTemplateCategory, at index: Int) {
currentCategories.insert(category, at: index)
codeOutlineView.insertItems(at: IndexSet(integer: index), inParent: nil, withAnimation: [])
let iset = IndexSet(integer: codeOutlineView.row(forItem: category))
codeOutlineView.selectRowIndexes(iset, byExtendingSelection: false)
}
/// actually removes the category from storage
private func remove(category: CodeTemplateCategory) {
let index = codeOutlineView.childIndex(forItem: category)
currentCategories.remove(at: index)
templateManager.set(categories: currentCategories, for: currentType)
codeOutlineView.removeItems(at: IndexSet(integer: index), inParent: nil, withAnimation: .slideUp)
}
/// deletes category with undo
private func delete(category: CodeTemplateCategory) {
let index = codeOutlineView.childIndex(forItem: category)
let undoAction = { (me: TemplatesPrefsController) -> Void in
me.insert(category: category, at: index)
}
if category.templates.value.count == 0 {
// if no templates, don't require conformation
self.undoManager?.registerUndo(withTarget: self, handler: undoAction)
self.remove(category: category)
return
}
confirmAction(message: NSLocalizedString("DeleteCodeTemplateWarning", comment: ""),
infoText: NSLocalizedString("DeleteCodeTemplateWarningInfo", comment: ""), buttonTitle: NSLocalizedString("Delete", comment: ""))
{ confirmed in
guard confirmed else { return }
self.undoManager?.registerUndo(withTarget: self, handler: undoAction)
self.remove(category: category)
}
}
/// insert a new template. separate function for undo purposes
private func insert(template: CodeTemplate, in parent: CodeTemplateCategory, at index: Int) {
parent.templates.value.insert(template, at: index)
codeOutlineView.insertItems(at: IndexSet(integer: index), inParent: parent, withAnimation: [])
codeOutlineView.selectRowIndexes(IndexSet(integer: codeOutlineView.row(forItem: template)), byExtendingSelection: false)
}
/// actually removes the template visually and from storage
private func remove(template: CodeTemplate) {
guard let parent = codeOutlineView.parent(forItem: template) as? CodeTemplateCategory,
let index = Optional.some(codeOutlineView.childIndex(forItem: template)), index != -1
else { Log.error("", .app); return }
// let index = parent.childIndex(forItem: template)
parent.templates.value.remove(at: index)
codeOutlineView.removeItems(at: IndexSet(integer: index), inParent: parent, withAnimation: .slideUp)
}
/// deletes template with undo, cofirming with user if necessary
private func delete(template: CodeTemplate) {
let defaults = UserDefaults.standard
// create local variables to enforce capture of current values
// swiftlint:disable:next force_cast
let parent = codeOutlineView.parent(forItem: template) as! CodeTemplateCategory
let index = codeOutlineView.childIndex(forItem: template)
// create closure that will do the reverse
let undoAction = { (me: TemplatesPrefsController) -> Void in
me.insert(template: template, in: parent, at: index)
}
let actuallyRemove = {
self.undoManager?.registerUndo(withTarget: self, handler: undoAction)
self.remove(template: template)
}
guard !defaults[.suppressDeleteTemplate] else {
actuallyRemove()
return
}
// need to confirm deletion with user
confirmAction(message: NSLocalizedString("DeleteCodeTemplateWarning", comment: ""),
infoText: NSLocalizedString("DeleteCodeTemplateWarningInfo", comment: ""), buttonTitle: NSLocalizedString("Delete", comment: ""), suppressionKey: .suppressDeleteTemplate)
{ confirmed in
guard confirmed else { return }
actuallyRemove()
}
}
}
// MARK: - NSTextView
// adds a binding target of textValue to NSTextView
extension Reactive where Base: NSTextView {
public var textValue: BindingTarget<String> {
return makeBindingTarget { (view, string) in
let selection = view.selectedRanges
view.replaceCharacters(in: view.string.fullNSRange, with: string)
view.selectedRanges = selection
}
}
}
// MARK: - helper types
private struct DragData: Codable, CustomStringConvertible {
let category: CodeTemplateCategory?
let template: CodeTemplate?
var isCategory: Bool { return category != nil }
var description: String { return isCategory ? category!.description : template!.description }
var item: CodeTemplateObject { return isCategory ? category! : template! }
var indexPath: IndexPath
init(category: CodeTemplateCategory, path: IndexPath) {
self.category = category
self.template = nil
self.indexPath = path
}
init(template: CodeTemplate, path: IndexPath) {
self.template = template
self.category = nil
self.indexPath = path
}
init(_ item: Any, path: IndexPath) {
if let titem = item as? CodeTemplate {
self.template = titem
self.category = nil
} else if let tcat = item as? CodeTemplateCategory {
self.category = tcat
self.template = nil
} else {
fatalError("invalid drag object")
}
self.indexPath = path
}
func encode() -> Data {
// swiftlint:disable:next force_try
return try! JSONEncoder().encode(self)
}
}
class TemplateCellView: NSTableCellView {
var templateItem: CodeTemplateObject? { didSet { templateItemWasSet() } }
private var disposable: Disposable?
private func templateItemWasSet() {
disposable?.dispose()
assert(textField != nil)
textField!.reactive.stringValue <~ templateItem!.name
}
}
class TemplatesOutlineView: NSOutlineView {
override func validateProposedFirstResponder(_ responder: NSResponder, for event: NSEvent?) -> Bool {
if responder is DoubleClickEditableTextField {
return true
}
return super.validateProposedFirstResponder(responder, for: event)
}
}
|
isc
|
29acad5a03915654e588cc3348ae3273
| 37.166667 | 190 | 0.7475 | 3.999837 | false | false | false | false |
cxd/recognisetextobject
|
recogniseobject/AppDelegate.swift
|
1
|
4507
|
//
// AppDelegate.swift
// recogniseobject
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "recogniseobject")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
|
apache-2.0
|
b5b62bb04d83fb1dfb366ed08715dc6b
| 49.077778 | 285 | 0.68671 | 5.96164 | false | false | false | false |
AaronMT/firefox-ios
|
Storage/ExtensionUtils.swift
|
9
|
4547
|
/* 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 UIKit
import MobileCoreServices
extension NSItemProvider {
var isText: Bool { return hasItemConformingToTypeIdentifier(String(kUTTypeText)) }
var isUrl: Bool { return hasItemConformingToTypeIdentifier(String(kUTTypeURL)) }
func processText(completion: CompletionHandler?) {
loadItem(forTypeIdentifier: String(kUTTypeText), options: nil, completionHandler: completion)
}
func processUrl(completion: CompletionHandler?) {
loadItem(forTypeIdentifier: String(kUTTypeURL), options: nil, completionHandler: completion)
}
}
public struct ExtensionUtils {
public enum ExtractedShareItem {
case shareItem(ShareItem)
case rawText(String)
public func isUrlType() -> Bool {
if case .shareItem(_) = self {
return true
} else {
return false
}
}
}
/// Look through the extensionContext for a url and title. Walks over all inputItems and then over all the attachments.
/// Has a completionHandler because ultimately an XPC call to the sharing application is done.
/// We can always extract a URL and sometimes a title. The favicon is currently just a placeholder, but
/// future code can possibly interact with a web page to find a proper icon.
/// If no URL is found, but a text provider *is*, then use the raw text as a fallback.
public static func extractSharedItem(fromExtensionContext extensionContext: NSExtensionContext?, completionHandler: @escaping (ExtractedShareItem?, Error?) -> Void) {
guard let extensionContext = extensionContext,
let inputItems = extensionContext.inputItems as? [NSExtensionItem] else {
completionHandler(nil, nil)
return
}
var textProviderFallback: NSItemProvider?
for inputItem in inputItems {
guard let attachments = inputItem.attachments else { continue }
for attachment in attachments {
if attachment.isUrl {
attachment.processUrl { obj, err in
guard err == nil else {
completionHandler(nil, err)
return
}
guard let url = obj as? URL else {
completionHandler(nil, NSError(domain: "org.mozilla.fennec", code: 999, userInfo: ["Problem": "Non-URL result."]))
return
}
let title = inputItem.attributedContentText?.string
let extracted = ExtractedShareItem.shareItem(ShareItem(url: url.absoluteString, title: title, favicon: nil))
completionHandler(extracted, nil)
}
return
}
if attachment.isText {
if textProviderFallback != nil {
NSLog("\(#function) More than one text attachment, only one expected.")
}
textProviderFallback = attachment
}
}
}
// See if the text is URL-like enough to be an url, in particular, check if it has a valid TLD.
func textToUrl(_ text: String) -> URL? {
guard text.contains(".") else { return nil }
var text = text
if !text.hasPrefix("http") {
text = "http://" + text
}
let url = URL(string: text)
return url?.publicSuffix != nil ? url : nil
}
if let textProvider = textProviderFallback {
textProvider.processText { obj, err in
guard err == nil, let text = obj as? String else {
completionHandler(nil, err)
return
}
if let url = textToUrl(text) {
let extracted = ExtractedShareItem.shareItem(ShareItem(url: url.absoluteString, title: nil, favicon: nil))
completionHandler(extracted, nil)
return
}
let extracted = ExtractedShareItem.rawText(text)
completionHandler(extracted, nil)
}
} else {
completionHandler(nil, nil)
}
}
}
|
mpl-2.0
|
57ea22a87a5c2c798939e1ff200a82d6
| 39.238938 | 170 | 0.570266 | 5.511515 | false | false | false | false |
rasmusth/BluetoothKit
|
Example/Vendor/CryptoSwift/Sources/CryptoSwift/ChaCha20.swift
|
3
|
7842
|
//
// ChaCha20.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 25/08/14.
// Copyright (c) 2014 Marcin Krzyzanowski. All rights reserved.
//
final public class ChaCha20: BlockCipher {
public enum Error: Swift.Error {
case invalidKeyOrInitializationVector
}
public static let blockSize = 64 // 512 / 8
fileprivate let context: Context
private struct Context {
var input = Array<UInt32>(repeating: 0, count: 16)
init(key:Array<UInt8>, iv:Array<UInt8>) throws {
precondition(iv.count >= 8)
let kbits = key.count * 8
if (kbits != 128 && kbits != 256) {
throw Error.invalidKeyOrInitializationVector
}
// 4 - 8
for i in 0..<4 {
let start = i * 4
input[i + 4] = wordNumber(key[start..<(start + 4)])
}
var addPos = 0;
switch (kbits) {
case 256:
addPos += 16
// sigma
input[0] = 0x61707865 //apxe
input[1] = 0x3320646e //3 dn
input[2] = 0x79622d32 //yb-2
input[3] = 0x6b206574 //k et
default:
// tau
input[0] = 0x61707865 //apxe
input[1] = 0x3620646e //6 dn
input[2] = 0x79622d31 //yb-1
input[3] = 0x6b206574 //k et
}
// 8 - 11
for i in 0..<4 {
let start = addPos + (i*4)
let bytes = key[start..<(start + 4)]
input[i + 8] = wordNumber(bytes)
}
// iv
input[12] = 0
input[13] = 0
input[14] = wordNumber(iv[0..<4])
input[15] = wordNumber(iv[4..<8])
}
}
public init(key:Array<UInt8>, iv:Array<UInt8>) throws {
self.context = try Context(key: key, iv: iv)
}
fileprivate func wordToByte(_ input:Array<UInt32> /* 64 */) -> Array<UInt8>? /* 16 */ {
precondition(input.count == 16)
var x = input
for _ in 0..<10 {
quarterround(&x[0], &x[4], &x[8], &x[12])
quarterround(&x[1], &x[5], &x[9], &x[13])
quarterround(&x[2], &x[6], &x[10], &x[14])
quarterround(&x[3], &x[7], &x[11], &x[15])
quarterround(&x[0], &x[5], &x[10], &x[15])
quarterround(&x[1], &x[6], &x[11], &x[12])
quarterround(&x[2], &x[7], &x[8], &x[13])
quarterround(&x[3], &x[4], &x[9], &x[14])
}
var output = Array<UInt8>()
output.reserveCapacity(16)
for i in 0..<16 {
x[i] = x[i] &+ input[i]
output.append(contentsOf: x[i].bytes().reversed())
}
return output;
}
private final func quarterround(_ a:inout UInt32, _ b:inout UInt32, _ c:inout UInt32, _ d:inout UInt32) {
a = a &+ b
d = rotateLeft((d ^ a), by: 16) //FIXME: WAT? n:
c = c &+ d
b = rotateLeft((b ^ c), by: 12);
a = a &+ b
d = rotateLeft((d ^ a), by: 8);
c = c &+ d
b = rotateLeft((b ^ c), by: 7);
}
}
// MARK: Cipher
extension ChaCha20: Cipher {
public func encrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
var ctx = context
var c = Array<UInt8>(repeating: 0, count: bytes.count)
var cPos:Int = 0
var mPos:Int = 0
var bytesCount = bytes.count
while (true) {
if let output = wordToByte(ctx.input) {
ctx.input[12] = ctx.input[12] &+ 1
if (ctx.input[12] == 0) {
ctx.input[13] = ctx.input[13] &+ 1
/* stopping at 2^70 bytes per nonce is user's responsibility */
}
if (bytesCount <= ChaCha20.blockSize) {
for i in 0..<bytesCount {
c[i + cPos] = bytes[i + mPos] ^ output[i]
}
return c
}
for i in 0..<ChaCha20.blockSize {
c[i + cPos] = bytes[i + mPos] ^ output[i]
}
bytesCount -= ChaCha20.blockSize
cPos += ChaCha20.blockSize
mPos += ChaCha20.blockSize
}
}
}
public func decrypt<C: Collection>(_ bytes: C) throws -> Array<UInt8> where C.Iterator.Element == UInt8, C.IndexDistance == Int, C.Index == Int {
return try encrypt(bytes)
}
}
// MARK: Encryptor
extension ChaCha20 {
public struct Encryptor: Updatable {
private var accumulated = Array<UInt8>()
private let chacha: ChaCha20
init(chacha: ChaCha20) {
self.chacha = chacha
}
mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = false) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
self.accumulated += bytes
var encrypted = Array<UInt8>()
encrypted.reserveCapacity(self.accumulated.count)
for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) {
if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
encrypted += try chacha.encrypt(chunk)
self.accumulated.removeFirst(chunk.count)
}
}
return encrypted
}
}
}
// MARK: Decryptor
extension ChaCha20 {
public struct Decryptor: Updatable {
private var accumulated = Array<UInt8>()
private var offset: Int = 0
private var offsetToRemove: Int = 0
private let chacha: ChaCha20
init(chacha: ChaCha20) {
self.chacha = chacha
}
mutating public func update<T: Sequence>(withBytes bytes:T, isLast: Bool = true) throws -> Array<UInt8> where T.Iterator.Element == UInt8 {
// prepend "offset" number of bytes at the begining
if self.offset > 0 {
self.accumulated += Array<UInt8>(repeating: 0, count: offset) + bytes
self.offsetToRemove = offset
self.offset = 0
} else {
self.accumulated += bytes
}
var plaintext = Array<UInt8>()
plaintext.reserveCapacity(self.accumulated.count)
for chunk in BytesSequence(chunkSize: ChaCha20.blockSize, data: self.accumulated) {
if (isLast || self.accumulated.count >= ChaCha20.blockSize) {
plaintext += try chacha.decrypt(chunk)
// remove "offset" from the beginning of first chunk
if self.offsetToRemove > 0 {
plaintext.removeFirst(self.offsetToRemove);
self.offsetToRemove = 0
}
self.accumulated.removeFirst(chunk.count)
}
}
return plaintext
}
}
}
// MARK: Cryptors
extension ChaCha20: Cryptors {
public func makeEncryptor() -> ChaCha20.Encryptor {
return Encryptor(chacha: self)
}
public func makeDecryptor() -> ChaCha20.Decryptor {
return Decryptor(chacha: self)
}
}
// MARK: Helpers
/// Change array to number. It's here because arrayOfBytes is too slow
private func wordNumber<T: Collection>(_ bytes: T) -> UInt32 where T.Iterator.Element == UInt8, T.IndexDistance == Int {
var value:UInt32 = 0
for i:UInt32 in 0..<4 {
let j = bytes.index(bytes.startIndex, offsetBy: Int(i))
value = value | UInt32(bytes[j]) << (8 * i)
}
return value
}
|
mit
|
e4bb38643376289bf0a4f10437b9d3a0
| 30.748988 | 149 | 0.501913 | 4.065319 | false | false | false | false |
mrdepth/Neocom
|
Legacy/Neocom/Neocom/NCAccountsFoldersViewController.swift
|
2
|
5654
|
//
// NCAccountsFoldersViewController.swift
// Neocom
//
// Created by Artem Shimanski on 04.08.17.
// Copyright © 2017 Artem Shimanski. All rights reserved.
//
import UIKit
import CoreData
import CloudData
import EVEAPI
import Futures
class NCAccountsFolderRow: NCFetchedResultsObjectNode<NCAccountsFolder> {
required init(object: NCAccountsFolder) {
super.init(object: object)
cellIdentifier = Prototype.NCDefaultTableViewCell.noImage.reuseIdentifier
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = object.name?.isEmpty == false ? object.name : NSLocalizedString("Unnamed", comment: "")
}
}
class NCAccountsNoFolder: TreeRow {
init() {
super.init(prototype: Prototype.NCDefaultTableViewCell.noImage)
}
override func configure(cell: UITableViewCell) {
guard let cell = cell as? NCDefaultTableViewCell else {return}
cell.titleLabel?.text = NSLocalizedString("Default", comment: "")
}
override var hash: Int {
return 0
}
override func isEqual(_ object: Any?) -> Bool {
return (object is NCAccountsNoFolder)
}
}
class NCAccountsFoldersViewController: NCTreeViewController {
override func viewDidLoad() {
super.viewDidLoad()
tableView.register([Prototype.NCDefaultTableViewCell.noImage,
Prototype.NCActionTableViewCell.default,
Prototype.NCHeaderTableViewCell.empty])
navigationItem.rightBarButtonItem = editButtonItem
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: - TreeControllerDelegate
override func treeController(_ treeController: TreeController, didSelectCellWithNode node: TreeNode) {
super.treeController(treeController, didSelectCellWithNode: node)
if node is NCActionRow {
guard let context = NCStorage.sharedStorage?.viewContext else {return}
let controller = UIAlertController(title: NSLocalizedString("Enter Folder Name", comment: ""), message: nil, preferredStyle: .alert)
var textField: UITextField?
controller.addTextField(configurationHandler: {
textField = $0
})
controller.addAction(UIAlertAction(title: NSLocalizedString("Add Folder", comment: ""), style: .default, handler: { (action) in
let folder = NCAccountsFolder(entity: NSEntityDescription.entity(forEntityName: "AccountsFolder", in: context)!, insertInto: context)
folder.name = textField?.text
if context.hasChanges {
try? context.save()
}
}))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
self.present(controller, animated: true, completion: nil)
}
else if node is NCAccountsNoFolder {
guard let picker = navigationController as? NCAccountsFolderPickerViewController else {return}
picker.completionHandler?(picker, nil)
}
else {
guard let row = node as? NCAccountsFolderRow else {return}
if isEditing {
performRename(folder: row.object)
}
else {
guard let picker = navigationController as? NCAccountsFolderPickerViewController else {return}
picker.completionHandler?(picker, row.object)
}
}
}
func treeController(_ treeController: TreeController, editActionsForNode node: TreeNode) -> [UITableViewRowAction]? {
guard let node = node as? NCAccountsFolderRow else {return nil}
let folder = node.object
return [UITableViewRowAction(style: .destructive, title: NSLocalizedString("Delete", comment: ""), handler: { _,_ in
folder.managedObjectContext?.delete(folder)
try? folder.managedObjectContext?.save()
}),
UITableViewRowAction(style: .normal, title: NSLocalizedString("Rename", comment: ""), handler: { [weak self] (_,_) in
self?.performRename(folder: folder)
})]
}
override func content() -> Future<TreeNode?> {
guard let context = NCStorage.sharedStorage?.viewContext else {return .init(nil)}
var sections = [TreeNode]()
sections.append(NCAccountsNoFolder())
let request = NSFetchRequest<NCAccountsFolder>(entityName: "AccountsFolder")
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let result = NSFetchedResultsController(fetchRequest: request, managedObjectContext: context, sectionNameKeyPath: nil, cacheName: nil)
sections.append(FetchedResultsNode(resultsController: result, objectNode: NCAccountsFolderRow.self))
let row = NCActionRow(title: NSLocalizedString("New Folder", comment: "").uppercased())
sections.append(DefaultTreeSection(prototype: Prototype.NCHeaderTableViewCell.empty, isExpandable: false, children: [row]))
return .init(RootNode(sections))
}
private func performRename(folder: NCAccountsFolder) {
let controller = UIAlertController(title: NSLocalizedString("Rename", comment: ""), message: nil, preferredStyle: .alert)
var textField: UITextField?
controller.addTextField(configurationHandler: {
textField = $0
textField?.text = folder.name
textField?.clearButtonMode = .always
})
controller.addAction(UIAlertAction(title: NSLocalizedString("Rename", comment: ""), style: .default, handler: { (action) in
if textField?.text?.isEmpty == false && folder.name != textField?.text {
folder.name = textField?.text
if folder.managedObjectContext?.hasChanges == true {
try? folder.managedObjectContext?.save()
}
}
}))
controller.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .cancel, handler: nil))
self.present(controller, animated: true, completion: nil)
}
}
|
lgpl-2.1
|
c5d49ccacc8d76de9f1409965a05273e
| 33.895062 | 137 | 0.734831 | 4.465245 | false | false | false | false |
HYT2016/app
|
test/test/gameStartVC2.swift
|
1
|
16409
|
//
// gameStartVC2.swift
// test
//
// Created by ios135 on 2017/6/30.
// Copyright © 2017年 Root HSZ HSU. All rights reserved.
//
import UIKit
import SwiftyJSON
class gameStartVC2: UIViewController {
@IBOutlet weak var displayLabel: UILabel!
@IBOutlet var chkBtns: [UIButton]!
@IBOutlet weak var chkBtna: UIButton!
@IBOutlet weak var chkBtnb: UIButton!
@IBOutlet weak var chkBtnc: UIButton!
@IBOutlet weak var chkBtnd: UIButton!
@IBAction func checkBtn(_ sender: UIButton) {
if userAnswer[sender.tag]{
sender.setImage(UIImage(named: "uncheck01"), for: .normal)
userAnswer[sender.tag]=false
}else{
sender.setImage(UIImage(named: "checked01"), for: .normal)
userAnswer[sender.tag]=true
}
}
var indexPath_row=1
var indexPath_max=1
var WrongDoctorSet=Set<String>()
var WrongDentistSet=Set<String>()
var isWrongQuestion:Bool?=false
var q_category:String?
var q_category1:String?
var userAnswer:[Bool]=[false,false,false,false]
var wrongQFileName:[String]=[]
var wrongQIndex:[String]=[]
var doctor:[String]=[]
var dentist:[String]=[]
var wrongTableViewQfileNameIndex:String?
var wrongTableViewIndex:String?
@IBOutlet weak var testTextView2: UITextView!
@IBAction func submitBtn(_ sender: UIButton) {
print( "result: \(self.checkIfCorrect(qID: b))")
if self.checkIfCorrect(qID: b ) == true {
displayLabel.textColor=UIColor.black
// 僅改變字體大小
self.displayLabel.font = self.displayLabel.font.withSize(22)
displayLabel.text="恭喜答對"
// 延遲0.5秒
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 0.5) {
self.displayLabel.text = ""
}
if self.q_category == wrongTableViewQfileNameIndex{
if indexPath_row==indexPath_max{
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
self.displayLabel.text = "恭喜您訂正完畢"
// 字體放大且字體變粗
self.displayLabel.font = UIFont.boldSystemFont(ofSize: 30)
self.displayLabel.textColor=UIColor(red: 128/255, green: 42/255, blue: 42/255, alpha: 1)
}
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 3) {
// 使頁面跳回上一頁
self.navigationController?.popViewController(animated: true)
}
// indexPath_row=0
// q_category1 = wrongQFileName[indexPath_row]
// self.getQin2()
}else{
// wrongQFileName[indexPath_row]代表可以正常跳到下一題不用從頭開始
q_category1 = wrongQFileName[indexPath_row]
self.getQin2()
indexPath_row+=1
}
}else{
b=Int(self.randomNumber(MIN: 0, MAX: (self.questions.count-1)))
loadQuestionToUser(qID: self.b)
print("loadQuestionToUser:\(loadQuestionToUser(qID: self.b))")
}
}else{
if self.q_category == wrongTableViewQfileNameIndex{
self.displayLabel.font = self.displayLabel.font.withSize(22)
displayLabel.text = "再接再厲"
displayLabel.textColor=UIColor.red
}else{
self.displayLabel.font = self.displayLabel.font.withSize(22)
displayLabel.text = "再接再厲"
displayLabel.textColor=UIColor.red
copyit()
copyit2()
// 發送方
let notificationName = Notification.Name("GetUpdateNoti")
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["PASS":WrongDoctorSet])
NotificationCenter.default.post(name: notificationName, object: nil, userInfo: ["PASS":WrongDentistSet])
}
}
let image = UIImage(named: "uncheck01")!
chkBtna.setImage(image, for: UIControlState.normal)
chkBtnb.setImage(image, for: UIControlState.normal)
chkBtnc.setImage(image, for: UIControlState.normal)
chkBtnd.setImage(image, for: UIControlState.normal)
for index in 0...3{
self.userAnswer[index]=false
}
}
func randomNumber(MIN: Int, MAX: Int)-> Int{
return Int(arc4random_uniform(UInt32(MAX)) + UInt32(MIN));
}
var version = [String: Int]()
var questions:[JSON]=[]
var qTions:[JSON]=[]
var indexVC=0
var qID=0
var b=0
// var b=Int(arc4random_uniform(30))
var a=0
var wrongTableViewCellName:String?
var preIndex:Int=0
var ansStr = ""
var wrQName = ""
var bnum = 0
var num = 0
var qFileName:String = ""
var QuesAnum=1
func loadJsonToArys(){
print("loadJsonToArys \(String(describing: self.q_category))")
//read file
let filePath=Bundle.main.path(forResource: self.q_category, ofType:
"json")
var data1:Data
var json_parsed:JSON
do{
try data1 = Data(contentsOf: URL(fileURLWithPath:
filePath!, isDirectory: false))
json_parsed=JSON(data: data1)
questions = json_parsed.arrayValue
// print(questions)
}catch{
print(error.localizedDescription)
}
print("q num is \(questions.count)")
b=self.getQuestionIndex()
self.loadQuestionToUser(qID: b)
}
func getQuestionIndex()->Int{
// if self.isWrongQuestion==false{
// print(b)
return Int(randomNumber(MIN: 0, MAX: (questions.count-1)))
// }else{
//// 要改
// getQin()
// return 1
// }
}
func getWrongQuestionIndex()->Int{
return Int(wrongTableViewIndex!)!
}
func getQin(){
// 讀檔 取得 題目 號碼 與 內容
qFileName = wrongTableViewQfileNameIndex!
q_category=qFileName
print("q:\(q_category!)")
let filePath=Bundle.main.path(forResource: self.q_category, ofType:
"json")
var data1:Data
var json_parsed:JSON
do{
try data1 = Data(contentsOf: URL(fileURLWithPath:
filePath!, isDirectory: false))
json_parsed=JSON(data: data1)
questions = json_parsed.arrayValue
}catch{
print(error.localizedDescription)
}
b=self.getWrongQuestionIndex()
self.loadQuestionToUser(qID: b)
print("b=\(b)")
}
func getQin2(){
// 讀檔 取得 題目 號碼 與 內容
let filePath=Bundle.main.path(forResource: self.q_category1, ofType:
"json")
var data1:Data
var json_parsed:JSON
do{
try data1 = Data(contentsOf: URL(fileURLWithPath:
filePath!, isDirectory: false))
json_parsed=JSON(data: data1)
questions = json_parsed.arrayValue
}catch{
print(error.localizedDescription)
}
b=Int(wrongQIndex[indexPath_row])!
self.loadQuestionToUser(qID: b)
}
func checkIfCorrect(qID:Int)->Bool{
var isCorrect=false
let answer = questions[qID]["答案"].stringValue
var ansStr=""
// 這裡聽老師解釋
for index in 0...3{
if self.userAnswer[index]{
switch index {
case 0:
ansStr+="A"
case 1:
ansStr+="B"
case 2:
ansStr+="C"
case 3:
ansStr+="D"
default:
break
}
}
}
print("answer = \(answer) user input ansStr = \(ansStr)")
if answer == ansStr{
isCorrect=true
}
return isCorrect
}
func loadQuestionToUser(qID:Int){
let q = questions[qID]
let tmpStr=q["題目"].stringValue
self.testTextView2.text=tmpStr
// print("tmpStr = \(tmpStr)")
}
func loadQuestionToUser2(qID:Int){
let q = questions[qID]
let tmpStr=q["題目"].stringValue
self.testTextView2.text=tmpStr
// print("tmpStr = \(tmpStr)")
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor(patternImage: UIImage(named: "背景 04")!)
displayLabel.backgroundColor=UIColor(patternImage: UIImage(named: "背景 04")!)
testTextView2.backgroundColor = UIColor(red: 174/255, green: 228/255, blue: 249/255, alpha: 0.5)
testTextView2.font = UIFont.systemFont(ofSize: 20, weight: 20)
testTextView2.textColor = UIColor(red: 41/255, green: 36/255, blue: 33/255, alpha: 1)
testTextView2.font = UIFont.boldSystemFont(ofSize: 20)
testTextView2.font = UIFont(name: "Verdana", size: 17)
if self.q_category == doctor[1]{
self.loadJsonToArys()
}else if self.q_category == doctor[2]{
self.loadJsonToArys()
}else if self.q_category == doctor[3]{
self.loadJsonToArys()
}else if self.q_category == doctor[4]{
self.loadJsonToArys()
}else if self.q_category == doctor[5]{
self.loadJsonToArys()
}else if self.q_category == doctor[6]{
self.loadJsonToArys()
}else if self.q_category == doctor[7]{
self.loadJsonToArys()
}else if self.q_category == doctor[8]{
self.loadJsonToArys()
}else if self.q_category == doctor[9]{
self.loadJsonToArys()
}else if self.q_category == doctor[10]{
self.loadJsonToArys()
}else if self.q_category == dentist[1]{
self.loadJsonToArys()
}else if self.q_category == dentist[2]{
self.loadJsonToArys()
}else if self.q_category == dentist[3]{
self.loadJsonToArys()
}else if self.q_category == dentist[4]{
self.loadJsonToArys()
}else if self.q_category == dentist[5]{
self.loadJsonToArys()
}else if self.q_category == dentist[6]{
self.loadJsonToArys()
}else if self.q_category == dentist[7]{
self.loadJsonToArys()
}else if self.q_category == dentist[8]{
self.loadJsonToArys()
}else if self.q_category == dentist[9]{
self.loadJsonToArys()
}else if self.q_category == dentist[10]{
self.loadJsonToArys()
}else if self.q_category == dentist[11]{
self.loadJsonToArys()
}else if self.q_category == dentist[12]{
self.loadJsonToArys()
}else if self.q_category == dentist[13]{
self.loadJsonToArys()
}else if self.q_category == dentist[14]{
self.loadJsonToArys()
}else if self.q_category == dentist[15]{
self.loadJsonToArys()
}else if self.q_category == dentist[16]{
self.loadJsonToArys()
}else if self.q_category == dentist[17]{
self.loadJsonToArys()
}else if self.q_category == dentist[18]{
self.loadJsonToArys()
}else{
self.getQin()
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 讓textView上面不留白
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
testTextView2.setContentOffset(CGPoint.zero, animated: false)
}
// 寫檔
func copyit() {
let dir = FileManager.default.urls(for: FileManager.SearchPathDirectory.cachesDirectory, in: FileManager.SearchPathDomainMask.userDomainMask).first!
// for i in 1...7{
//
// if self.q_category == doctor[i]{
// ansStr="doctorAns.txt"
// }else{
// ansStr="dentistAns.txt"
// }
// }
//
if self.q_category == doctor[1]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[2]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[3]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[4]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[5]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[6]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[7]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[8]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[9]{
ansStr = "doctorAns.txt"
}else if self.q_category == doctor[10]{
ansStr = "doctorAns.txt"
}else{
self.ansStr = "dentistAns.txt"
}
let fileurl = dir.appendingPathComponent(ansStr)
print(fileurl)
let string = "\(q_category!):\(b)\n"
let string2 = "\(q_category!):\(b)"
let data = string.data(using: .utf8, allowLossyConversion: false)!
if FileManager.default.fileExists(atPath: fileurl.path) {
if let fileHandle = try? FileHandle(forUpdating: fileurl) {
// 讓資料不會重複存取
if WrongDoctorSet .contains(string2){
print("已經有資料")
}else if WrongDentistSet .contains(string2){
print("已經有資料")
}else{
fileHandle.seekToEndOfFile()
fileHandle.write(data)
fileHandle.closeFile()
}
}
} else {
try! data.write(to: fileurl, options: Data.WritingOptions.atomic)
}
}
func copyit2() {
let string1 = "\(q_category!):\(b)"
if self.q_category == doctor[1]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[2]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[3]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[4]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[5]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[6]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[7]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[8]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[9]{
WrongDoctorSet.insert(string1)
}else if self.q_category == doctor[10]{
WrongDoctorSet.insert(string1)
}else{
WrongDentistSet.insert(string1)
}
print("WrongDoctorSet:\(WrongDoctorSet)")
print("WrongDentistSet:\(WrongDentistSet)")
}
}
|
mit
|
9564a18fe27081e49ef041a45a1c2292
| 28.556777 | 156 | 0.517288 | 4.12631 | false | false | false | false |
Rochester-Ting/XMLY
|
XMLY/XMLY/Classes/Discover(发现)/Controller/DiscoverVC.swift
|
1
|
1935
|
//
// DiscoverVC.swift
// XMLY
//
// Created by Rochester on 17/1/17.
// Copyright © 2017年 Rochester. All rights reserved.
//
import UIKit
let screenW : CGFloat = UIScreen.main.bounds.size.width
let screenH : CGFloat = UIScreen.main.bounds.size.height
let kStatusH : CGFloat = 20
let kNavH : CGFloat = 44
let kViewH : CGFloat = 49
let klineH : CGFloat = 1
class DiscoverVC: UIViewController {
let titles = ["推荐","分类","广播","榜单","主播"]
var childVCs : [UIViewController] = [UIViewController]()
lazy var pageView : PageView = {
self.childVCs.append(RecommendVC())
self.childVCs.append(ClassifyVC())
self.childVCs.append(BroadcastVC())
self.childVCs.append(ListVC())
self.childVCs.append(AnchorVC())
let kContentH = screenH - kViewH - kNavH - kStatusH
let pageView : PageView = PageView(frame: CGRect(x: 0, y: kStatusH + kNavH + kViewH, width: screenW, height: kContentH), childVCs: self.childVCs, parentVC: self)
return pageView
}()
lazy var titleView : TitleView = {
let titleView = TitleView(frame: CGRect(x: 0, y: kStatusH + kNavH, width: screenW, height: kViewH), titles: self.titles)
return titleView
}()
override func viewDidLoad() {
super.viewDidLoad()
setUpUI()
title = "发现"
}
}
extension DiscoverVC{
fileprivate func setUpUI(){
addTitleView()
addPageView()
}
}
extension DiscoverVC{
fileprivate func addTitleView(){
view.addSubview(titleView)
// 按钮的点击
titleView.titleViewBtnClick = { (btnTag) in
self.pageView.scrollCollectionView(index: btnTag)
}
}
fileprivate func addPageView(){
view.addSubview(pageView)
// collectionView滚动
pageView.collectionItem = {(index) in
self.titleView.selectedButton(index: index)
}
}
}
|
mit
|
178f13dfb40b303c62f280970e8e3cd8
| 30.04918 | 169 | 0.63622 | 3.93763 | false | false | false | false |
arpyzo/mini_bits
|
Mini Bits/GameViewController.swift
|
1
|
1649
|
// Copyright (c) 2015 Robert Pyzalski
//
// 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 SpriteKit
class GameViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let scene = GameScene(size: self.view.frame.size)
scene.scaleMode = .AspectFill
let skView = self.view as! SKView
skView.showsFPS = true
skView.showsNodeCount = true
skView.ignoresSiblingOrder = true
skView.presentScene(scene)
}
override func shouldAutorotate() -> Bool {
return true
}
override func supportedInterfaceOrientations() -> Int {
if UIDevice.currentDevice().userInterfaceIdiom == .Phone {
return Int(UIInterfaceOrientationMask.AllButUpsideDown.rawValue)
} else {
return Int(UIInterfaceOrientationMask.All.rawValue)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Release any cached data, images, etc that aren't in use.
}
override func prefersStatusBarHidden() -> Bool {
return true
}
}
|
apache-2.0
|
ce110c10e6888f38827cebfb0cdd8258
| 30.711538 | 76 | 0.682232 | 4.981873 | false | false | false | false |
tkremenek/swift
|
test/IRGen/sil_generic_witness_methods_objc.swift
|
22
|
1688
|
// RUN: %target-swift-frontend -primary-file %s -emit-ir -enable-objc-interop -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// FIXME: These should be SIL tests, but we can't parse generic types in SIL
// yet.
@objc protocol ObjC {
func method()
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_method<T: ObjC>(_ x: T) {
x.method()
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_f1_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T) {{.*}} {
// CHECK: call swiftcc void @"$s32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T)
func call_call_objc_method<T: ObjC>(_ x: T) {
call_objc_method(x)
}
// CHECK-LABEL: define hidden swiftcc void @"$s32sil_generic_witness_methods_objc05call_E19_existential_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_existential_method(_ x: ObjC) {
x.method()
}
|
apache-2.0
|
c2b5401c28683b09c5208104d5bf4de3
| 51.75 | 163 | 0.609005 | 3.030521 | false | false | false | false |
tkremenek/swift
|
test/Generics/associated_type_where_clause_hints.swift
|
13
|
2570
|
// RUN: %target-typecheck-verify-swift
protocol P0 { }
protocol P0b { }
struct X0 : P0 { }
struct X1 { }
protocol P1 {
associatedtype A // expected-note 2{{'A' declared here}}
associatedtype A2 // expected-note {{'A2' declared here}}
associatedtype A3 // expected-note {{'A3' declared here}}
associatedtype A4 // expected-note {{'A4' declared here}}
}
// A typealias in a subprotocol should be written as a same-type
// requirement.
protocol P2 : P1 {
typealias A = X1 // expected-warning{{typealias overriding associated type 'A' from protocol 'P1' is better expressed as same-type constraint on the protocol}}{{17-17= where A == X1}}{{3-20=}}
}
// A redeclaration of an associated type that adds type/layout requirements
// should be written via a where clause.
protocol P3a : P1 {
associatedtype A: P0, P0b // expected-warning{{redeclaration of associated type 'A' from protocol 'P1' is better expressed as a 'where' clause on the protocol}}{{18-18= where A: P0, A: P0b}}{{3-29=}}
associatedtype A2: P0, P0b where A2.A == Never, A2: P1 // expected-warning{{redeclaration of associated type 'A2' from protocol 'P1' is better expressed as a 'where' clause on the protocol}}{{18-18= where A2: P0, A2: P0b, A2.A == Never, A2 : P1}}{{3-58=}}
associatedtype A3 where A3: P0 // expected-warning{{redeclaration of associated type 'A3' from protocol 'P1' is better expressed as a 'where' clause on the protocol}}{{18-18= where A3 : P0}}{{3-34=}}
// expected-warning@+1 {{redeclaration of associated type 'A4' from protocol 'P1' is better expressed as a 'where' clause on the protocol}}{{18-18= where A4: P0, A4 : Collection, A4.Element == A4.Index, A4.SubSequence == A4}}{{3-52=}}
associatedtype A4: P0 where A4: Collection,
A4.Element == A4.Index,
A4.SubSequence == A4 // {{3-52=}} is this line, so it is correct.
}
// ... unless it has adds a default type witness
protocol P3b : P1 {
associatedtype A: P0 = X0 // note: no warning
}
protocol P4: P1 {
associatedtype B // expected-note{{'B' declared here}}
associatedtype B2 // expected-note{{'B2' declared here}}
}
protocol P5: P4 where A: P0 {
typealias B = X1 // expected-warning{{typealias overriding associated type 'B' from protocol 'P4' is better expressed as same-type constraint on the protocol}}{{28-28=, B == X1}}{{3-20=}}
associatedtype B2: P5 // expected-warning{{redeclaration of associated type 'B2' from protocol 'P4' is better expressed as a 'where' clause on the protocol}}{{28-28=, B2: P5}} {{3-25=}}
}
|
apache-2.0
|
53f585550d0a8ae78c2cc238fe36208f
| 49.392157 | 257 | 0.677821 | 3.39498 | false | false | false | false |
md0u80c9/ResearchKit
|
samples/ORKCatalog/ORKCatalog/Tasks/TaskListRow.swift
|
1
|
70209
|
/*
Copyright (c) 2015, Apple Inc. All rights reserved.
Copyright (c) 2015-2016, Ricardo Sánchez-Sáez.
Redistribution and use in source and binary forms, with or without modification,
are permitted provided that the following conditions are met:
1. Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation and/or
other materials provided with the distribution.
3. Neither the name of the copyright holder(s) nor the names of any contributors
may be used to endorse or promote products derived from this software without
specific prior written permission. No license is granted to the trademarks of
the copyright holders even if such marks are included in this software.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import ResearchKit
import AudioToolbox
/**
Wraps a SystemSoundID.
A class is used in order to provide appropriate cleanup when the sound is
no longer needed.
*/
class SystemSound {
var soundID: SystemSoundID = 0
init?(soundURL: URL) {
if AudioServicesCreateSystemSoundID(soundURL as CFURL, &soundID) != noErr {
return nil
}
}
deinit {
AudioServicesDisposeSystemSoundID(soundID)
}
}
/**
An enum that corresponds to a row displayed in a `TaskListViewController`.
Each of the tasks is composed of one or more steps giving examples of the
types of functionality supported by the ResearchKit framework.
*/
enum TaskListRow: Int, CustomStringConvertible {
case form = 0
case survey
case booleanQuestion
case dateQuestion
case dateTimeQuestion
case imageChoiceQuestion
case locationQuestion
case numericQuestion
case scaleQuestion
case textQuestion
case textChoiceQuestion
case timeIntervalQuestion
case timeOfDayQuestion
case valuePickerChoiceQuestion
case validatedTextQuestion
case imageCapture
case videoCapture
case wait
case eligibilityTask
case consent
case accountCreation
case login
case passcode
case audio
case fitness
case holePegTest
case psat
case reactionTime
case shortWalk
case spatialSpanMemory
case timedWalk
case timedWalkWithTurnAround
case toneAudiometry
case towerOfHanoi
case tremorTest
case twoFingerTappingInterval
case walkBackAndForth
case heightQuestion
case kneeRangeOfMotion
case shoulderRangeOfMotion
case videoInstruction
class TaskListRowSection {
var title: String
var rows: [TaskListRow]
init(title: String, rows: [TaskListRow]) {
self.title = title
self.rows = rows
}
}
/// Returns an array of all the task list row enum cases.
static var sections: [ TaskListRowSection ] {
return [
TaskListRowSection(title: "Surveys", rows:
[
.form,
.survey,
]),
TaskListRowSection(title: "Survey Questions", rows:
[
.booleanQuestion,
.dateQuestion,
.dateTimeQuestion,
.heightQuestion,
.imageChoiceQuestion,
.locationQuestion,
.numericQuestion,
.scaleQuestion,
.textQuestion,
.textChoiceQuestion,
.timeIntervalQuestion,
.timeOfDayQuestion,
.valuePickerChoiceQuestion,
.validatedTextQuestion,
.imageCapture,
.videoCapture,
.wait,
]),
TaskListRowSection(title: "Onboarding", rows:
[
.eligibilityTask,
.consent,
.accountCreation,
.login,
.passcode,
]),
TaskListRowSection(title: "Active Tasks", rows:
[
.audio,
.fitness,
.holePegTest,
.psat,
.reactionTime,
.shortWalk,
.spatialSpanMemory,
.timedWalk,
.timedWalkWithTurnAround,
.toneAudiometry,
.towerOfHanoi,
.tremorTest,
.twoFingerTappingInterval,
.walkBackAndForth,
.kneeRangeOfMotion,
.shoulderRangeOfMotion,
]),
TaskListRowSection(title: "Miscellaneous", rows:
[
.videoInstruction,
]),
]}
// MARK: CustomStringConvertible
var description: String {
switch self {
case .form:
return NSLocalizedString("Form Survey Example", comment: "")
case .survey:
return NSLocalizedString("Simple Survey Example", comment: "")
case .booleanQuestion:
return NSLocalizedString("Boolean Question", comment: "")
case .dateQuestion:
return NSLocalizedString("Date Question", comment: "")
case .dateTimeQuestion:
return NSLocalizedString("Date and Time Question", comment: "")
case .heightQuestion:
return NSLocalizedString("Height Question", comment: "")
case .imageChoiceQuestion:
return NSLocalizedString("Image Choice Question", comment: "")
case .locationQuestion:
return NSLocalizedString("Location Question", comment: "")
case .numericQuestion:
return NSLocalizedString("Numeric Question", comment: "")
case .scaleQuestion:
return NSLocalizedString("Scale Question", comment: "")
case .textQuestion:
return NSLocalizedString("Text Question", comment: "")
case .textChoiceQuestion:
return NSLocalizedString("Text Choice Question", comment: "")
case .timeIntervalQuestion:
return NSLocalizedString("Time Interval Question", comment: "")
case .timeOfDayQuestion:
return NSLocalizedString("Time of Day Question", comment: "")
case .valuePickerChoiceQuestion:
return NSLocalizedString("Value Picker Choice Question", comment: "")
case .validatedTextQuestion:
return NSLocalizedString("Validated Text Question", comment: "")
case .imageCapture:
return NSLocalizedString("Image Capture Step", comment: "")
case .videoCapture:
return NSLocalizedString("Video Capture Step", comment: "")
case .wait:
return NSLocalizedString("Wait Step", comment: "")
case .eligibilityTask:
return NSLocalizedString("Eligibility Task Example", comment: "")
case .consent:
return NSLocalizedString("Consent-Obtaining Example", comment: "")
case .accountCreation:
return NSLocalizedString("Account Creation", comment: "")
case .login:
return NSLocalizedString("Login", comment: "")
case .passcode:
return NSLocalizedString("Passcode Creation", comment: "")
case .audio:
return NSLocalizedString("Audio", comment: "")
case .fitness:
return NSLocalizedString("Fitness Check", comment: "")
case .holePegTest:
return NSLocalizedString("Hole Peg Test", comment: "")
case .psat:
return NSLocalizedString("PSAT", comment: "")
case .reactionTime:
return NSLocalizedString("Reaction Time", comment: "")
case .shortWalk:
return NSLocalizedString("Short Walk", comment: "")
case .spatialSpanMemory:
return NSLocalizedString("Spatial Span Memory", comment: "")
case .timedWalk:
return NSLocalizedString("Timed Walk", comment: "")
case .timedWalkWithTurnAround:
return NSLocalizedString("Timed Walk with Turn Around", comment: "")
case .toneAudiometry:
return NSLocalizedString("Tone Audiometry", comment: "")
case .towerOfHanoi:
return NSLocalizedString("Tower of Hanoi", comment: "")
case .twoFingerTappingInterval:
return NSLocalizedString("Two Finger Tapping Interval", comment: "")
case .walkBackAndForth:
return NSLocalizedString("Walk Back and Forth", comment: "")
case .tremorTest:
return NSLocalizedString("Tremor Test", comment: "")
case .videoInstruction:
return NSLocalizedString("Video Instruction Task", comment: "")
case .kneeRangeOfMotion:
return NSLocalizedString("Knee Range of Motion", comment: "")
case .shoulderRangeOfMotion:
return NSLocalizedString("Shoulder Range of Motion", comment: "")
}
}
// MARK: Types
/**
Every step and task in the ResearchKit framework has to have an identifier.
Within a task, the step identifiers should be unique.
Here we use an enum to ensure that the identifiers are kept unique. Since
the enum has a raw underlying type of a `String`, the compiler can determine
the uniqueness of the case values at compile time.
In a real application, the identifiers for your tasks and steps might
come from a database, or in a smaller application, might have some
human-readable meaning.
*/
private enum Identifier {
// Task with a form, where multiple items appear on one page.
case formTask
case formStep
case formItem01
case formItem02
case formItem03
// Survey task specific identifiers.
case surveyTask
case introStep
case questionStep
case summaryStep
// Task with a Boolean question.
case booleanQuestionTask
case booleanQuestionStep
// Task with an example of date entry.
case dateQuestionTask
case dateQuestionStep
// Task with an example of date and time entry.
case dateTimeQuestionTask
case dateTimeQuestionStep
// Task with an example of height entry.
case heightQuestionTask
case heightQuestionStep1
case heightQuestionStep2
case heightQuestionStep3
// Task with an image choice question.
case imageChoiceQuestionTask
case imageChoiceQuestionStep
// Task with a location entry.
case locationQuestionTask
case locationQuestionStep
// Task with examples of numeric questions.
case numericQuestionTask
case numericQuestionStep
case numericNoUnitQuestionStep
// Task with examples of questions with sliding scales.
case scaleQuestionTask
case discreteScaleQuestionStep
case continuousScaleQuestionStep
case discreteVerticalScaleQuestionStep
case continuousVerticalScaleQuestionStep
case textScaleQuestionStep
case textVerticalScaleQuestionStep
// Task with an example of free text entry.
case textQuestionTask
case textQuestionStep
// Task with an example of a multiple choice question.
case textChoiceQuestionTask
case textChoiceQuestionStep
// Task with an example of time of day entry.
case timeOfDayQuestionTask
case timeOfDayQuestionStep
// Task with an example of time interval entry.
case timeIntervalQuestionTask
case timeIntervalQuestionStep
// Task with a value picker.
case valuePickerChoiceQuestionTask
case valuePickerChoiceQuestionStep
// Task with an example of validated text entry.
case validatedTextQuestionTask
case validatedTextQuestionStepEmail
case validatedTextQuestionStepDomain
// Image capture task specific identifiers.
case imageCaptureTask
case imageCaptureStep
// Video capture task specific identifiers.
case VideoCaptureTask
case VideoCaptureStep
// Task with an example of waiting.
case waitTask
case waitStepDeterminate
case waitStepIndeterminate
// Eligibility task specific indentifiers.
case eligibilityTask
case eligibilityIntroStep
case eligibilityFormStep
case eligibilityFormItem01
case eligibilityFormItem02
case eligibilityFormItem03
case eligibilityIneligibleStep
case eligibilityEligibleStep
// Consent task specific identifiers.
case consentTask
case visualConsentStep
case consentSharingStep
case consentReviewStep
case consentDocumentParticipantSignature
case consentDocumentInvestigatorSignature
// Account creation task specific identifiers.
case accountCreationTask
case registrationStep
case waitStep
case verificationStep
// Login task specific identifiers.
case loginTask
case loginStep
case loginWaitStep
// Passcode task specific identifiers.
case passcodeTask
case passcodeStep
// Active tasks.
case audioTask
case fitnessTask
case holePegTestTask
case psatTask
case reactionTime
case shortWalkTask
case spatialSpanMemoryTask
case timedWalkTask
case timedWalkWithTurnAroundTask
case toneAudiometryTask
case towerOfHanoi
case tremorTestTask
case twoFingerTappingIntervalTask
case walkBackAndForthTask
case kneeRangeOfMotion
case shoulderRangeOfMotion
// Video instruction tasks.
case videoInstructionTask
case videoInstructionStep
}
// MARK: Properties
/// Returns a new `ORKTask` that the `TaskListRow` enumeration represents.
var representedTask: ORKTask {
switch self {
case .form:
return formTask
case .survey:
return surveyTask
case .booleanQuestion:
return booleanQuestionTask
case .dateQuestion:
return dateQuestionTask
case .dateTimeQuestion:
return dateTimeQuestionTask
case .heightQuestion:
return heightQuestionTask
case .imageChoiceQuestion:
return imageChoiceQuestionTask
case .locationQuestion:
return locationQuestionTask
case .numericQuestion:
return numericQuestionTask
case .scaleQuestion:
return scaleQuestionTask
case .textQuestion:
return textQuestionTask
case .textChoiceQuestion:
return textChoiceQuestionTask
case .timeIntervalQuestion:
return timeIntervalQuestionTask
case .timeOfDayQuestion:
return timeOfDayQuestionTask
case .valuePickerChoiceQuestion:
return valuePickerChoiceQuestionTask
case .validatedTextQuestion:
return validatedTextQuestionTask
case .imageCapture:
return imageCaptureTask
case .videoCapture:
return videoCaptureTask
case .wait:
return waitTask
case .eligibilityTask:
return eligibilityTask
case .consent:
return consentTask
case .accountCreation:
return accountCreationTask
case .login:
return loginTask
case .passcode:
return passcodeTask
case .audio:
return audioTask
case .fitness:
return fitnessTask
case .holePegTest:
return holePegTestTask
case .psat:
return PSATTask
case .reactionTime:
return reactionTimeTask
case .shortWalk:
return shortWalkTask
case .spatialSpanMemory:
return spatialSpanMemoryTask
case .timedWalk:
return timedWalkTask
case .timedWalkWithTurnAround:
return timedWalkWithTurnAroundTask
case .toneAudiometry:
return toneAudiometryTask
case .towerOfHanoi:
return towerOfHanoiTask
case .twoFingerTappingInterval:
return twoFingerTappingIntervalTask
case .walkBackAndForth:
return walkBackAndForthTask
case .tremorTest:
return tremorTestTask
case .kneeRangeOfMotion:
return kneeRangeOfMotion
case .shoulderRangeOfMotion:
return shoulderRangeOfMotion
case .videoInstruction:
return videoInstruction
}
}
// MARK: Task Creation Convenience
/**
This task demonstrates a form step, in which multiple items are presented
in a single scrollable form. This might be used for entering multi-value
data, like taking a blood pressure reading with separate systolic and
diastolic values.
*/
private var formTask: ORKTask {
let step = ORKFormStep(identifier: String(describing:Identifier.formStep), title: exampleQuestionText, text: exampleDetailText)
// A first field, for entering an integer.
let formItem01Text = NSLocalizedString("Field01", comment: "")
let formItem01 = ORKFormItem(identifier: String(describing:Identifier.formItem01), text: formItem01Text, answerFormat: ORKAnswerFormat.integerAnswerFormat(withUnit: nil))
formItem01.placeholder = NSLocalizedString("Your placeholder here", comment: "")
// A second field, for entering a time interval.
let formItem02Text = NSLocalizedString("Field02", comment: "")
let formItem02 = ORKFormItem(identifier: String(describing:Identifier.formItem02), text: formItem02Text, answerFormat: ORKTimeIntervalAnswerFormat())
formItem02.placeholder = NSLocalizedString("Your placeholder here", comment: "")
step.formItems = [
formItem01,
formItem02
]
return ORKOrderedTask(identifier: String(describing:Identifier.formTask), steps: [step])
}
/**
A task demonstrating how the ResearchKit framework can be used to present a simple
survey with an introduction, a question, and a conclusion.
*/
private var surveyTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
// Add a question step.
let questionStepAnswerFormat = ORKBooleanAnswerFormat()
let questionStepTitle = NSLocalizedString("Would you like to subscribe to our newsletter?", comment: "")
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.questionStep), title: questionStepTitle, answer: questionStepAnswerFormat)
// Add a summary step.
let summaryStep = ORKInstructionStep(identifier: String(describing:Identifier.summaryStep))
summaryStep.title = NSLocalizedString("Thanks", comment: "")
summaryStep.text = NSLocalizedString("Thank you for participating in this sample survey.", comment: "")
return ORKOrderedTask(identifier: String(describing:Identifier.surveyTask), steps: [
instructionStep,
questionStep,
summaryStep
])
}
/// This task presents just a single "Yes" / "No" question.
private var booleanQuestionTask: ORKTask {
let answerFormat = ORKBooleanAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.booleanQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.booleanQuestionTask), steps: [questionStep])
}
/// This task demonstrates a question which asks for a date.
private var dateQuestionTask: ORKTask {
/*
The date answer format can also support minimum and maximum limits,
a specific default value, and overriding the calendar to use.
*/
let answerFormat = ORKAnswerFormat.dateAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.dateQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.dateQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a date and time of an event.
private var dateTimeQuestionTask: ORKTask {
/*
This uses the default calendar. Use a more detailed constructor to
set minimum / maximum limits.
*/
let answerFormat = ORKAnswerFormat.dateTime()
let step = ORKQuestionStep(identifier: String(describing:Identifier.dateTimeQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.dateTimeQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for the user height.
private var heightQuestionTask: ORKTask {
let answerFormat1 = ORKAnswerFormat.heightAnswerFormat()
let step1 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep1), title: "Height (local system)", answer: answerFormat1)
step1.text = exampleDetailText
let answerFormat2 = ORKAnswerFormat.heightAnswerFormat(with: ORKMeasurementSystem.metric)
let step2 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep2), title: "Height (metric system)", answer: answerFormat2)
step2.text = exampleDetailText
let answerFormat3 = ORKAnswerFormat.heightAnswerFormat(with: ORKMeasurementSystem.USC)
let step3 = ORKQuestionStep(identifier: String(describing:Identifier.heightQuestionStep3), title: "Height (USC system)", answer: answerFormat3)
step2.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.heightQuestionTask), steps: [step1, step2, step3])
}
/**
This task demonstrates a survey question involving picking from a series of
image choices. A more realistic applciation of this type of question might be to
use a range of icons for faces ranging from happy to sad.
*/
private var imageChoiceQuestionTask: ORKTask {
let roundShapeImage = UIImage(named: "round_shape")!
let roundShapeText = NSLocalizedString("Round Shape", comment: "")
let squareShapeImage = UIImage(named: "square_shape")!
let squareShapeText = NSLocalizedString("Square Shape", comment: "")
let imageChoces = [
ORKImageChoice(normalImage: roundShapeImage, selectedImage: nil, text: roundShapeText, value: roundShapeText as NSCoding & NSCopying & NSObjectProtocol),
ORKImageChoice(normalImage: squareShapeImage, selectedImage: nil, text: squareShapeText, value: squareShapeText as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormat(with: imageChoces)
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.imageChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.imageChoiceQuestionTask), steps: [questionStep])
}
/// This task presents just a single location question.
private var locationQuestionTask: ORKTask {
let answerFormat = ORKLocationAnswerFormat()
// We attach an answer format to a question step to specify what controls the user sees.
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.locationQuestionStep), title: exampleQuestionText, answer: answerFormat)
// The detail text is shown in a small font below the title.
questionStep.text = exampleDetailText
questionStep.placeholder = NSLocalizedString("Address", comment: "");
return ORKOrderedTask(identifier: String(describing:Identifier.locationQuestionTask), steps: [questionStep])
}
/**
This task demonstrates use of numeric questions with and without units.
Note that the unit is just a string, prompting the user to enter the value
in the expected unit. The unit string propagates into the result object.
*/
private var numericQuestionTask: ORKTask {
// This answer format will display a unit in-line with the numeric entry field.
let localizedQuestionStep1AnswerFormatUnit = NSLocalizedString("Your unit", comment: "")
let questionStep1AnswerFormat = ORKAnswerFormat.decimalAnswerFormat(withUnit: localizedQuestionStep1AnswerFormatUnit)
let questionStep1 = ORKQuestionStep(identifier: String(describing:Identifier.numericQuestionStep), title: exampleQuestionText, answer: questionStep1AnswerFormat)
questionStep1.text = exampleDetailText
questionStep1.placeholder = NSLocalizedString("Your placeholder.", comment: "")
// This answer format is similar to the previous one, but this time without displaying a unit.
let questionStep2 = ORKQuestionStep(identifier: String(describing:Identifier.numericNoUnitQuestionStep), title: exampleQuestionText, answer: ORKAnswerFormat.decimalAnswerFormat(withUnit: nil))
questionStep2.text = exampleDetailText
questionStep2.placeholder = NSLocalizedString("Placeholder without unit.", comment: "")
return ORKOrderedTask(identifier: String(describing:Identifier.numericQuestionTask), steps: [
questionStep1,
questionStep2
])
}
/// This task presents two options for questions displaying a scale control.
private var scaleQuestionTask: ORKTask {
// The first step is a scale control with 10 discrete ticks.
let step1AnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: false, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep1 = ORKQuestionStep(identifier: String(describing:Identifier.discreteScaleQuestionStep), title: exampleQuestionText, answer: step1AnswerFormat)
questionStep1.text = exampleDetailText
// The second step is a scale control that allows continuous movement with a percent formatter.
let step2AnswerFormat = ORKAnswerFormat.continuousScale(withMaximumValue: 1.0, minimumValue: 0.0, defaultValue: 99.0, maximumFractionDigits: 0, vertical: false, maximumValueDescription: nil, minimumValueDescription: nil)
step2AnswerFormat.numberStyle = .percent
let questionStep2 = ORKQuestionStep(identifier: String(describing:Identifier.continuousScaleQuestionStep), title: exampleQuestionText, answer: step2AnswerFormat)
questionStep2.text = exampleDetailText
// The third step is a vertical scale control with 10 discrete ticks.
let step3AnswerFormat = ORKAnswerFormat.scale(withMaximumValue: 10, minimumValue: 1, defaultValue: NSIntegerMax, step: 1, vertical: true, maximumValueDescription: nil, minimumValueDescription: nil)
let questionStep3 = ORKQuestionStep(identifier: String(describing:Identifier.discreteVerticalScaleQuestionStep), title: exampleQuestionText, answer: step3AnswerFormat)
questionStep3.text = exampleDetailText
// The fourth step is a vertical scale control that allows continuous movement.
let step4AnswerFormat = ORKAnswerFormat.continuousScale(withMaximumValue: 5.0, minimumValue: 1.0, defaultValue: 99.0, maximumFractionDigits: 2, vertical: true, maximumValueDescription: exampleHighValueText, minimumValueDescription: exampleLowValueText)
let questionStep4 = ORKQuestionStep(identifier: String(describing:Identifier.continuousVerticalScaleQuestionStep), title: exampleQuestionText, answer: step4AnswerFormat)
questionStep4.text = exampleDetailText
// The fifth step is a scale control that allows text choices.
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Poor", value: 1 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Fair", value: 2 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Good", value: 3 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Above Average", value: 10 as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "Excellent", value: 5 as NSCoding & NSCopying & NSObjectProtocol)]
let step5AnswerFormat = ORKAnswerFormat.textScale(with: textChoices, defaultIndex: NSIntegerMax, vertical: false)
let questionStep5 = ORKQuestionStep(identifier: String(describing:Identifier.textScaleQuestionStep), title: exampleQuestionText, answer: step5AnswerFormat)
questionStep5.text = exampleDetailText
// The sixth step is a vertical scale control that allows text choices.
let step6AnswerFormat = ORKAnswerFormat.textScale(with: textChoices, defaultIndex: NSIntegerMax, vertical: true)
let questionStep6 = ORKQuestionStep(identifier: String(describing:Identifier.textVerticalScaleQuestionStep), title: exampleQuestionText, answer: step6AnswerFormat)
questionStep6.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.scaleQuestionTask), steps: [
questionStep1,
questionStep2,
questionStep3,
questionStep4,
questionStep5,
questionStep6
])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var textQuestionTask: ORKTask {
let answerFormat = ORKAnswerFormat.textAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.textQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.textQuestionTask), steps: [step])
}
/**
This task demonstrates a survey question for picking from a list of text
choices. In this case, the text choices are presented in a table view
(compare with the `valuePickerQuestionTask`).
*/
private var textChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3" as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat = ORKAnswerFormat.choiceAnswerFormat(with: .singleChoice, textChoices: textChoices)
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.textChoiceQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.textChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates requesting a time interval. For example, this might
be a suitable answer format for a question like "How long is your morning
commute?"
*/
private var timeIntervalQuestionTask: ORKTask {
/*
The time interval answer format is constrained to entering a time
less than 24 hours and in steps of minutes. For times that don't fit
these restrictions, use another mode of data entry.
*/
let answerFormat = ORKAnswerFormat.timeIntervalAnswerFormat()
let step = ORKQuestionStep(identifier: String(describing:Identifier.timeIntervalQuestionStep), title: exampleQuestionText, answer: answerFormat)
step.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.timeIntervalQuestionTask), steps: [step])
}
/// This task demonstrates a question asking for a time of day.
private var timeOfDayQuestionTask: ORKTask {
/*
Because we don't specify a default, the picker will default to the
time the step is presented. For questions like "What time do you have
breakfast?", it would make sense to set the default on the answer
format.
*/
let answerFormat = ORKAnswerFormat.timeOfDayAnswerFormat()
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.timeOfDayQuestionStep), title: exampleQuestionText, answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.timeOfDayQuestionTask), steps: [questionStep])
}
/**
This task demonstrates a survey question using a value picker wheel.
Compare with the `textChoiceQuestionTask` and `imageChoiceQuestionTask`
which can serve a similar purpose.
*/
private var valuePickerChoiceQuestionTask: ORKTask {
let textChoiceOneText = NSLocalizedString("Choice 1", comment: "")
let textChoiceTwoText = NSLocalizedString("Choice 2", comment: "")
let textChoiceThreeText = NSLocalizedString("Choice 3", comment: "")
// The text to display can be separate from the value coded for each choice:
let textChoices = [
ORKTextChoice(text: textChoiceOneText, value: "choice_1" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceTwoText, value: "choice_2" as NSCoding & NSCopying & NSObjectProtocol),
ORKTextChoice(text: textChoiceThreeText, value: "choice_3" as NSCoding & NSCopying & NSObjectProtocol)
]
let answerFormat = ORKAnswerFormat.valuePickerAnswerFormat(with: textChoices)
let questionStep = ORKQuestionStep(identifier: String(describing:Identifier.valuePickerChoiceQuestionStep), title: exampleQuestionText,
answer: answerFormat)
questionStep.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.valuePickerChoiceQuestionTask), steps: [questionStep])
}
/**
This task demonstrates asking for text entry. Both single and multi-line
text entry are supported, with appropriate parameters to the text answer
format.
*/
private var validatedTextQuestionTask: ORKTask {
let answerFormatEmail = ORKAnswerFormat.emailAnswerFormat()
let stepEmail = ORKQuestionStep(identifier: String(describing:Identifier.validatedTextQuestionStepEmail), title: NSLocalizedString("Email", comment: ""), answer: answerFormatEmail)
stepEmail.text = exampleDetailText
let domainRegex = "^(https?:\\/\\/)?([\\da-z\\.-]+)\\.([a-z\\.]{2,6})([\\/\\w \\.-]*)*\\/?$"
let answerFormatDomain = ORKAnswerFormat.textAnswerFormat(withValidationRegex: domainRegex, invalidMessage:"Invalid URL: %@")
answerFormatDomain.multipleLines = false
answerFormatDomain.keyboardType = .URL
answerFormatDomain.autocapitalizationType = UITextAutocapitalizationType.none
answerFormatDomain.autocorrectionType = UITextAutocorrectionType.no
answerFormatDomain.spellCheckingType = UITextSpellCheckingType.no
let stepDomain = ORKQuestionStep(identifier: String(describing:Identifier.validatedTextQuestionStepDomain), title: NSLocalizedString("URL", comment: ""), answer: answerFormatDomain)
stepDomain.text = exampleDetailText
return ORKOrderedTask(identifier: String(describing:Identifier.validatedTextQuestionTask), steps: [stepEmail, stepDomain])
}
/// This task presents the image capture step in an ordered task.
private var imageCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.withRenderingMode(.alwaysTemplate)
let imageCaptureStep = ORKImageCaptureStep(identifier: String(describing:Identifier.imageCaptureStep))
imageCaptureStep.isOptional = false
imageCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the image", comment: "")
imageCaptureStep.accessibilityHint = NSLocalizedString("Captures the image visible in the preview", comment: "")
imageCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
imageCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
return ORKOrderedTask(identifier: String(describing:Identifier.imageCaptureTask), steps: [
instructionStep,
imageCaptureStep
])
}
/// This task presents the video capture step in an ordered task.
private var videoCaptureTask: ORKTask {
// Create the intro step.
let instructionStep = ORKInstructionStep(identifier: String(describing:Identifier.introStep))
instructionStep.title = NSLocalizedString("Sample Survey", comment: "")
instructionStep.text = exampleDescription
let handSolidImage = UIImage(named: "hand_solid")!
instructionStep.image = handSolidImage.withRenderingMode(.alwaysTemplate)
let videoCaptureStep = ORKVideoCaptureStep(identifier: String(describing:Identifier.VideoCaptureStep))
videoCaptureStep.accessibilityInstructions = NSLocalizedString("Your instructions for capturing the video", comment: "")
videoCaptureStep.accessibilityHint = NSLocalizedString("Captures the video visible in the preview", comment: "")
videoCaptureStep.templateImage = UIImage(named: "hand_outline_big")!
videoCaptureStep.templateImageInsets = UIEdgeInsets(top: 0.05, left: 0.05, bottom: 0.05, right: 0.05)
videoCaptureStep.duration = 30.0; // 30 seconds
return ORKOrderedTask(identifier: String(describing:Identifier.VideoCaptureTask), steps: [
instructionStep,
videoCaptureStep
])
}
/// This task presents a wait task.
private var waitTask: ORKTask {
let waitStepIndeterminate = ORKWaitStep(identifier: String(describing:Identifier.waitStepIndeterminate))
waitStepIndeterminate.title = exampleQuestionText
waitStepIndeterminate.text = exampleDescription
waitStepIndeterminate.indicatorType = ORKProgressIndicatorType.indeterminate
let waitStepDeterminate = ORKWaitStep(identifier: String(describing:Identifier.waitStepDeterminate))
waitStepDeterminate.title = exampleQuestionText
waitStepDeterminate.text = exampleDescription
waitStepDeterminate.indicatorType = ORKProgressIndicatorType.progressBar
return ORKOrderedTask(identifier: String(describing:Identifier.waitTask), steps: [waitStepIndeterminate, waitStepDeterminate])
}
/**
A task demonstrating how the ResearchKit framework can be used to determine
eligibility using a navigable ordered task.
*/
private var eligibilityTask: ORKTask {
// Intro step
let introStep = ORKInstructionStep(identifier: String(describing:Identifier.eligibilityIntroStep))
introStep.title = NSLocalizedString("Eligibility Task Example", comment: "")
// Form step
let formStep = ORKFormStep(identifier: String(describing:Identifier.eligibilityFormStep))
formStep.title = NSLocalizedString("Eligibility", comment: "")
formStep.text = exampleQuestionText
formStep.isOptional = false
// Form items
let textChoices : [ORKTextChoice] = [ORKTextChoice(text: "Yes", value: "Yes" as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "No", value: "No" as NSCoding & NSCopying & NSObjectProtocol), ORKTextChoice(text: "N/A", value: "N/A" as NSCoding & NSCopying & NSObjectProtocol)]
let answerFormat = ORKTextChoiceAnswerFormat(style: ORKChoiceAnswerStyle.singleChoice, textChoices: textChoices)
let formItem01 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem01), text: exampleQuestionText, answerFormat: answerFormat)
formItem01.isOptional = false
let formItem02 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem02), text: exampleQuestionText, answerFormat: answerFormat)
formItem02.isOptional = false
let formItem03 = ORKFormItem(identifier: String(describing:Identifier.eligibilityFormItem03), text: exampleQuestionText, answerFormat: answerFormat)
formItem03.isOptional = false
formStep.formItems = [
formItem01,
formItem02,
formItem03
]
// Ineligible step
let ineligibleStep = ORKInstructionStep(identifier: String(describing:Identifier.eligibilityIneligibleStep))
ineligibleStep.title = NSLocalizedString("You are ineligible to join the study", comment: "")
// Eligible step
let eligibleStep = ORKCompletionStep(identifier: String(describing:Identifier.eligibilityEligibleStep))
eligibleStep.title = NSLocalizedString("You are eligible to join the study", comment: "")
// Create the task
let eligibilityTask = ORKNavigableOrderedTask(identifier: String(describing:Identifier.eligibilityTask), steps: [
introStep,
formStep,
ineligibleStep,
eligibleStep
])
// Build navigation rules.
var resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem01))
let predicateFormItem01 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "Yes" as NSCoding & NSCopying & NSObjectProtocol)
resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem02))
let predicateFormItem02 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "Yes" as NSCoding & NSCopying & NSObjectProtocol)
resultSelector = ORKResultSelector(stepIdentifier: String(describing:Identifier.eligibilityFormStep), resultIdentifier: String(describing:Identifier.eligibilityFormItem03))
let predicateFormItem03 = ORKResultPredicate.predicateForChoiceQuestionResult(with: resultSelector, expectedAnswerValue: "No" as NSCoding & NSCopying & NSObjectProtocol)
let predicateEligible = NSCompoundPredicate(andPredicateWithSubpredicates: [predicateFormItem01, predicateFormItem02, predicateFormItem03])
let predicateRule = ORKPredicateStepNavigationRule(resultPredicatesAndDestinationStepIdentifiers: [ (predicateEligible, String(describing:Identifier.eligibilityEligibleStep)) ])
eligibilityTask.setNavigationRule(predicateRule, forTriggerStepIdentifier:String(describing:Identifier.eligibilityFormStep))
// Add end direct rules to skip unneeded steps
let directRule = ORKDirectStepNavigationRule(destinationStepIdentifier: ORKNullStepIdentifier)
eligibilityTask.setNavigationRule(directRule, forTriggerStepIdentifier:String(describing:Identifier.eligibilityIneligibleStep))
return eligibilityTask
}
/// A task demonstrating how the ResearchKit framework can be used to obtain informed consent.
private var consentTask: ORKTask {
/*
Informed consent starts by presenting an animated sequence conveying
the main points of your consent document.
*/
let visualConsentStep = ORKVisualConsentStep(identifier: String(describing:Identifier.visualConsentStep), document: consentDocument)
let investigatorShortDescription = NSLocalizedString("Institution", comment: "")
let investigatorLongDescription = NSLocalizedString("Institution and its partners", comment: "")
let localizedLearnMoreHTMLContent = NSLocalizedString("Your sharing learn more content here.", comment: "")
/*
If you want to share the data you collect with other researchers for
use in other studies beyond this one, it is best practice to get
explicit permission from the participant. Use the consent sharing step
for this.
*/
let sharingConsentStep = ORKConsentSharingStep(identifier: String(describing:Identifier.consentSharingStep), investigatorShortDescription: investigatorShortDescription, investigatorLongDescription: investigatorLongDescription, localizedLearnMoreHTMLContent: localizedLearnMoreHTMLContent)
/*
After the visual presentation, the consent review step displays
your consent document and can obtain a signature from the participant.
The first signature in the document is the participant's signature.
This effectively tells the consent review step which signatory is
reviewing the document.
*/
let signature = consentDocument.signatures!.first
let reviewConsentStep = ORKConsentReviewStep(identifier: String(describing:Identifier.consentReviewStep), signature: signature, in: consentDocument)
// In a real application, you would supply your own localized text.
reviewConsentStep.text = loremIpsumText
reviewConsentStep.reasonForConsent = loremIpsumText
return ORKOrderedTask(identifier: String(describing:Identifier.consentTask), steps: [
visualConsentStep,
sharingConsentStep,
reviewConsentStep
])
}
/// This task presents the Account Creation process.
private var accountCreationTask: ORKTask {
/*
A registration step provides a form step that is populated with email and password fields.
If you wish to include any of the additional fields, then you can specify it through the `options` parameter.
*/
let registrationTitle = NSLocalizedString("Registration", comment: "")
let passcodeValidationRegex = "^(?=.*\\d).{4,8}$"
let passcodeInvalidMessage = NSLocalizedString("A valid password must be 4 and 8 digits long and include at least one numeric character.", comment: "")
let registrationOptions: ORKRegistrationStepOption = [.includeGivenName, .includeFamilyName, .includeGender, .includeDOB]
let registrationStep = ORKRegistrationStep(identifier: String(describing:Identifier.registrationStep), title: registrationTitle, text: exampleDetailText, passcodeValidationRegex: passcodeValidationRegex, passcodeInvalidMessage: passcodeInvalidMessage, options: registrationOptions)
/*
A wait step allows you to upload the data from the user registration onto your server before presenting the verification step.
*/
let waitTitle = NSLocalizedString("Creating account", comment: "")
let waitText = NSLocalizedString("Please wait while we upload your data", comment: "")
let waitStep = ORKWaitStep(identifier: String(describing:Identifier.waitStep))
waitStep.title = waitTitle
waitStep.text = waitText
/*
A verification step view controller subclass is required in order to use the verification step.
The subclass provides the view controller button and UI behavior by overriding the following methods.
*/
class VerificationViewController : ORKVerificationStepViewController {
override func resendEmailButtonTapped() {
let alertTitle = NSLocalizedString("Resend Verification Email", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
let verificationStep = ORKVerificationStep(identifier: String(describing:Identifier.verificationStep), text: exampleDetailText, verificationViewControllerClass: VerificationViewController.self)
return ORKOrderedTask(identifier: String(describing:Identifier.accountCreationTask), steps: [
registrationStep,
waitStep,
verificationStep
])
}
/// This tasks presents the login step.
private var loginTask: ORKTask {
/*
A login step view controller subclass is required in order to use the login step.
The subclass provides the behavior for the login step forgot password button.
*/
class LoginViewController : ORKLoginStepViewController {
override func forgotPasswordButtonTapped() {
let alertTitle = NSLocalizedString("Forgot password?", comment: "")
let alertMessage = NSLocalizedString("Button tapped", comment: "")
let alert = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
alert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
/*
A login step provides a form step that is populated with email and password fields,
and a button for `Forgot password?`.
*/
let loginTitle = NSLocalizedString("Login", comment: "")
let loginStep = ORKLoginStep(identifier: String(describing:Identifier.loginStep), title: loginTitle, text: exampleDetailText, loginViewControllerClass: LoginViewController.self)
/*
A wait step allows you to validate the data from the user login against your server before proceeding.
*/
let waitTitle = NSLocalizedString("Logging in", comment: "")
let waitText = NSLocalizedString("Please wait while we validate your credentials", comment: "")
let waitStep = ORKWaitStep(identifier: String(describing:Identifier.loginWaitStep))
waitStep.title = waitTitle
waitStep.text = waitText
return ORKOrderedTask(identifier: String(describing:Identifier.loginTask), steps: [loginStep, waitStep])
}
/// This task demonstrates the Passcode creation process.
private var passcodeTask: ORKTask {
/*
If you want to protect the app using a passcode. It is reccomended to
ask user to create passcode as part of the consent process and use the
authentication and editing view controllers to interact with the passcode.
The passcode is stored in the keychain.
*/
let passcodeConsentStep = ORKPasscodeStep(identifier: String(describing:Identifier.passcodeStep))
return ORKOrderedTask(identifier: String(describing:Identifier.passcodeStep), steps: [passcodeConsentStep])
}
/// This task presents the Audio pre-defined active task.
private var audioTask: ORKTask {
return ORKOrderedTask.audioTask(withIdentifier: String(describing:Identifier.audioTask), intendedUseDescription: exampleDescription, speechInstruction: exampleSpeechInstruction, shortSpeechInstruction: exampleSpeechInstruction, duration: 20, recordingSettings: nil, checkAudioLevel: true, options: [])
}
/**
This task presents the Fitness pre-defined active task. For this example,
short walking and rest durations of 20 seconds each are used, whereas more
realistic durations might be several minutes each.
*/
private var fitnessTask: ORKTask {
return ORKOrderedTask.fitnessCheck(withIdentifier: String(describing:Identifier.fitnessTask), intendedUseDescription: exampleDescription, walkDuration: 20, restDuration: 20, options: [])
}
/// This task presents the Hole Peg Test pre-defined active task.
private var holePegTestTask: ORKTask {
return ORKNavigableOrderedTask.holePegTest(withIdentifier: String(describing:Identifier.holePegTestTask), intendedUseDescription: exampleDescription, dominantHand: .right, numberOfPegs: 9, threshold: 0.2, rotated: false, timeLimit: 300, options: [])
}
/// This task presents the PSAT pre-defined active task.
private var PSATTask: ORKTask {
return ORKOrderedTask.psatTask(withIdentifier: String(describing:Identifier.psatTask), intendedUseDescription: exampleDescription, presentationMode: ORKPSATPresentationMode.auditory.union(.visual), interStimulusInterval: 3.0, stimulusDuration: 1.0, seriesLength: 60, options: [])
}
/// This task presents the Reaction Time pre-defined active task.
private var reactionTimeTask: ORKTask {
/// An example of a custom sound.
let successSoundURL = Bundle.main.url(forResource:"tap", withExtension: "aif")!
let successSound = SystemSound(soundURL: successSoundURL)!
return ORKOrderedTask.reactionTime(withIdentifier: String(describing:Identifier.reactionTime), intendedUseDescription: exampleDescription, maximumStimulusInterval: 10, minimumStimulusInterval: 4, thresholdAcceleration: 0.5, numberOfAttempts: 3, timeout: 3, successSound: successSound.soundID, timeoutSound: 0, failureSound: UInt32(kSystemSoundID_Vibrate), options: [])
}
/// This task presents the Gait and Balance pre-defined active task.
private var shortWalkTask: ORKTask {
return ORKOrderedTask.shortWalk(withIdentifier: String(describing:Identifier.shortWalkTask), intendedUseDescription: exampleDescription, numberOfStepsPerLeg: 20, restDuration: 20, options: [])
}
/// This task presents the Spatial Span Memory pre-defined active task.
private var spatialSpanMemoryTask: ORKTask {
return ORKOrderedTask.spatialSpanMemoryTask(withIdentifier: String(describing:Identifier.spatialSpanMemoryTask), intendedUseDescription: exampleDescription, initialSpan: 3, minimumSpan: 2, maximumSpan: 15, playSpeed: 1.0, maximumTests: 5, maximumConsecutiveFailures: 3, customTargetImage: nil, customTargetPluralName: nil, requireReversal: false, options: [])
}
/// This task presents the Timed Walk pre-defined active task.
private var timedWalkTask: ORKTask {
return ORKOrderedTask.timedWalk(withIdentifier: String(describing:Identifier.timedWalkTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, includeAssistiveDeviceForm: true, options: [])
}
/// This task presents the Timed Walk with turn around pre-defined active task.
private var timedWalkWithTurnAroundTask: ORKTask {
return ORKOrderedTask.timedWalk(withIdentifier: String(describing:Identifier.timedWalkWithTurnAroundTask), intendedUseDescription: exampleDescription, distanceInMeters: 100.0, timeLimit: 180.0, turnAroundTimeLimit: 60.0, includeAssistiveDeviceForm: true, options: [])
}
/// This task presents the Tone Audiometry pre-defined active task.
private var toneAudiometryTask: ORKTask {
return ORKOrderedTask.toneAudiometryTask(withIdentifier: String(describing:Identifier.toneAudiometryTask), intendedUseDescription: exampleDescription, speechInstruction: nil, shortSpeechInstruction: nil, toneDuration: 20, options: [])
}
private var towerOfHanoiTask: ORKTask {
return ORKOrderedTask.towerOfHanoiTask(withIdentifier: String(describing:Identifier.towerOfHanoi), intendedUseDescription: exampleDescription, numberOfDisks: 5, options: [])
}
/// This task presents the Two Finger Tapping pre-defined active task.
private var twoFingerTappingIntervalTask: ORKTask {
return ORKOrderedTask.twoFingerTappingIntervalTask(withIdentifier: String(describing:Identifier.twoFingerTappingIntervalTask), intendedUseDescription: exampleDescription, duration: 10,
handOptions: [.both], options: [])
}
/// This task presents a walk back-and-forth task
private var walkBackAndForthTask: ORKTask {
return ORKOrderedTask.walkBackAndForthTask(withIdentifier: String(describing:Identifier.walkBackAndForthTask), intendedUseDescription: exampleDescription, walkDuration: 30, restDuration: 30, options: [])
}
/// This task presents the Tremor Test pre-defined active task.
private var tremorTestTask: ORKTask {
return ORKOrderedTask.tremorTest(withIdentifier: String(describing:Identifier.tremorTestTask),
intendedUseDescription: exampleDescription,
activeStepDuration: 10,
activeTaskOptions: [],
handOptions: [.both],
options: [])
}
/// This task presents a knee range of motion task
private var kneeRangeOfMotion: ORKTask {
return ORKOrderedTask.kneeRangeOfMotionTask(withIdentifier: String(describing: Identifier.kneeRangeOfMotion), limbOption: .right, intendedUseDescription: exampleDescription, options: [])
}
/// This task presents a shoulder range of motion task
private var shoulderRangeOfMotion: ORKTask {
return ORKOrderedTask.shoulderRangeOfMotionTask(withIdentifier: String(describing: Identifier.shoulderRangeOfMotion), limbOption: .left, intendedUseDescription: exampleDescription, options: [])
}
/// This task presents a video instruction step
private var videoInstruction: ORKTask {
let videoInstructionStep = ORKVideoInstructionStep(identifier: String(describing: Identifier.videoInstructionStep))
videoInstructionStep.title = NSLocalizedString("Video Instruction Step", comment: "")
videoInstructionStep.videoURL = URL(string: "https://www.apple.com/media/us/researchkit/2016/a63aa7d4_e6fd_483f_a59d_d962016c8093/films/carekit/researchkit-carekit-cc-us-20160321_r848-9dwc.mov")
videoInstructionStep.thumbnailTime = 2 // Customizable thumbnail timestamp
return ORKOrderedTask(identifier: String(describing: Identifier.videoInstructionTask), steps: [videoInstructionStep])
}
// MARK: Consent Document Creation Convenience
/**
A consent document provides the content for the visual consent and consent
review steps. This helper sets up a consent document with some dummy
content. You should populate your consent document to suit your study.
*/
private var consentDocument: ORKConsentDocument {
let consentDocument = ORKConsentDocument()
/*
This is the title of the document, displayed both for review and in
the generated PDF.
*/
consentDocument.title = NSLocalizedString("Example Consent", comment: "")
// This is the title of the signature page in the generated document.
consentDocument.signaturePageTitle = NSLocalizedString("Consent", comment: "")
/*
This is the line shown on the signature page of the generated document,
just above the signatures.
*/
consentDocument.signaturePageContent = NSLocalizedString("I agree to participate in this research study.", comment: "")
/*
Add the participant signature, which will be filled in during the
consent review process. This signature initially does not have a
signature image or a participant name; these are collected during
the consent review step.
*/
let participantSignatureTitle = NSLocalizedString("Participant", comment: "")
let participantSignature = ORKConsentSignature(forPersonWithTitle: participantSignatureTitle, dateFormatString: nil, identifier: String(describing:Identifier.consentDocumentParticipantSignature))
consentDocument.addSignature(participantSignature)
/*
Add the investigator signature. This is pre-populated with the
investigator's signature image and name, and the date of their
signature. If you need to specify the date as now, you could generate
a date string with code here.
This signature is only used for the generated PDF.
*/
let signatureImage = UIImage(named: "signature")!
let investigatorSignatureTitle = NSLocalizedString("Investigator", comment: "")
let investigatorSignatureGivenName = NSLocalizedString("Jonny", comment: "")
let investigatorSignatureFamilyName = NSLocalizedString("Appleseed", comment: "")
let investigatorSignatureDateString = "3/10/15"
let investigatorSignature = ORKConsentSignature(forPersonWithTitle: investigatorSignatureTitle, dateFormatString: nil, identifier: String(describing:Identifier.consentDocumentInvestigatorSignature), givenName: investigatorSignatureGivenName, familyName: investigatorSignatureFamilyName, signatureImage: signatureImage, dateString: investigatorSignatureDateString)
consentDocument.addSignature(investigatorSignature)
/*
This is the HTML content for the "Learn More" page for each consent
section. In a real consent, this would be your content, and you would
have different content for each section.
If your content is just text, you can use the `content` property
instead of the `htmlContent` property of `ORKConsentSection`.
*/
let htmlContentString = "<ul><li>Lorem</li><li>ipsum</li><li>dolor</li></ul><p>\(loremIpsumLongText)</p><p>\(loremIpsumMediumText)</p>"
/*
These are all the consent section types that have pre-defined animations
and images. We use them in this specific order, so we see the available
animated transitions.
*/
let consentSectionTypes: [ORKConsentSectionType] = [
.overview,
.dataGathering,
.privacy,
.dataUse,
.timeCommitment,
.studySurvey,
.studyTasks,
.withdrawing
]
/*
For each consent section type in `consentSectionTypes`, create an
`ORKConsentSection` that represents it.
In a real app, you would set specific content for each section.
*/
var consentSections: [ORKConsentSection] = consentSectionTypes.map { contentSectionType in
let consentSection = ORKConsentSection(type: contentSectionType)
consentSection.summary = loremIpsumShortText
if contentSectionType == .overview {
consentSection.htmlContent = htmlContentString
}
else {
consentSection.content = loremIpsumLongText
}
return consentSection
}
/*
This is an example of a section that is only in the review document
or only in the generated PDF, and is not displayed in `ORKVisualConsentStep`.
*/
let consentSection = ORKConsentSection(type: .onlyInDocument)
consentSection.summary = NSLocalizedString(".OnlyInDocument Scene Summary", comment: "")
consentSection.title = NSLocalizedString(".OnlyInDocument Scene", comment: "")
consentSection.content = loremIpsumLongText
consentSections += [consentSection]
// Set the sections on the document after they've been created.
consentDocument.sections = consentSections
return consentDocument
}
// MARK: `ORKTask` Reused Text Convenience
private var exampleDescription: String {
return NSLocalizedString("Your description goes here.", comment: "")
}
private var exampleSpeechInstruction: String {
return NSLocalizedString("Your more specific voice instruction goes here. For example, say 'Aaaah'.", comment: "")
}
private var exampleQuestionText: String {
return NSLocalizedString("Your question goes here.", comment: "")
}
private var exampleHighValueText: String {
return NSLocalizedString("High Value", comment: "")
}
private var exampleLowValueText: String {
return NSLocalizedString("Low Value", comment: "")
}
private var exampleDetailText: String {
return NSLocalizedString("Additional text can go here.", comment: "")
}
private var exampleEmailText: String {
return NSLocalizedString("[email protected]", comment: "")
}
private var loremIpsumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."
}
private var loremIpsumShortText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit."
}
private var loremIpsumMediumText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo?"
}
private var loremIpsumLongText: String {
return "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam adhuc, meo fortasse vitio, quid ego quaeram non perspicis. Plane idem, inquit, et maxima quidem, qua fieri nulla maior potest. Quonam, inquit, modo? An potest, inquit ille, quicquam esse suavius quam nihil dolere? Cave putes quicquam esse verius. Quonam, inquit, modo?"
}
}
|
bsd-3-clause
|
90fcfaf8d986ee0fe1508bc885aa0424
| 45.494702 | 469 | 0.675118 | 5.521154 | false | false | false | false |
xwu/swift
|
test/Concurrency/concurrent_value_checking.swift
|
1
|
11115
|
// RUN: %target-typecheck-verify-swift -disable-availability-checking -warn-concurrency
// REQUIRES: concurrency
class NotConcurrent { } // expected-note 18{{class 'NotConcurrent' does not conform to the 'Sendable' protocol}}
// ----------------------------------------------------------------------
// Sendable restriction on actor operations
// ----------------------------------------------------------------------
actor A1 {
let localLet: NotConcurrent = NotConcurrent()
func synchronous() -> NotConcurrent? { nil }
func asynchronous(_: NotConcurrent?) async { }
}
actor A2 {
var localVar: NotConcurrent
init(value: NotConcurrent) {
self.localVar = value
}
}
func testActorCreation(value: NotConcurrent) {
_ = A2(value: value) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent' across actors}}
}
extension A1 {
func testIsolation(other: A1) async {
// All within the same actor domain, so the Sendable restriction
// does not apply.
_ = localLet
_ = synchronous()
_ = await asynchronous(nil)
_ = self.localLet
_ = self.synchronous()
_ = await self.asynchronous(nil)
// Across to a different actor, so Sendable restriction is enforced.
_ = other.localLet // expected-warning{{cannot use property 'localLet' with a non-sendable type 'NotConcurrent' across actors}}
_ = await other.synchronous() // expected-warning{{cannot call function returning non-sendable type 'NotConcurrent?' across actors}}
_ = await other.asynchronous(nil) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent?' across actors}}
}
}
// ----------------------------------------------------------------------
// Sendable restriction on global actor operations
// ----------------------------------------------------------------------
actor TestActor {}
@globalActor
struct SomeGlobalActor {
static var shared: TestActor { TestActor() }
}
@SomeGlobalActor
let globalValue: NotConcurrent? = nil
@SomeGlobalActor
func globalSync(_: NotConcurrent?) {
}
@SomeGlobalActor
func globalAsync(_: NotConcurrent?) async {
await globalAsync(globalValue) // both okay because we're in the actor
globalSync(nil)
}
func globalTest() async {
let a = globalValue // expected-warning{{cannot use let 'globalValue' with a non-sendable type 'NotConcurrent?' across actors}}
await globalAsync(a) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent?' across actors}}
await globalSync(a) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent?' across actors}}
}
struct HasSubscript {
@SomeGlobalActor
subscript (i: Int) -> NotConcurrent? { nil }
}
class ClassWithGlobalActorInits { // expected-note 2{{class 'ClassWithGlobalActorInits' does not conform to the 'Sendable' protocol}}
@SomeGlobalActor
init(_: NotConcurrent) { }
@SomeGlobalActor
init() { }
}
@MainActor
func globalTestMain(nc: NotConcurrent) async {
let a = globalValue // expected-warning{{cannot use let 'globalValue' with a non-sendable type 'NotConcurrent?' across actors}}
await globalAsync(a) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent?' across actors}}
await globalSync(a) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent?' across actors}}
_ = await ClassWithGlobalActorInits(nc) // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent' across actors}}
// expected-warning@-1{{cannot call function returning non-sendable type 'ClassWithGlobalActorInits' across actors}}
_ = await ClassWithGlobalActorInits() // expected-warning{{cannot call function returning non-sendable type 'ClassWithGlobalActorInits' across actors}}
}
@SomeGlobalActor
func someGlobalTest(nc: NotConcurrent) {
let hs = HasSubscript()
let _ = hs[0] // okay
_ = ClassWithGlobalActorInits(nc)
}
// ----------------------------------------------------------------------
// Sendable restriction on captures.
// ----------------------------------------------------------------------
func acceptNonConcurrent(_: () -> Void) { }
func acceptConcurrent(_: @Sendable () -> Void) { }
func testConcurrency() {
let x = NotConcurrent()
var y = NotConcurrent()
y = NotConcurrent()
acceptNonConcurrent {
print(x) // okay
print(y) // okay
}
acceptConcurrent {
print(x) // expected-warning{{cannot use let 'x' with a non-sendable type 'NotConcurrent' from concurrently-executed code}}
print(y) // expected-error{{reference to captured var 'y' in concurrently-executing code}}
}
}
func acceptUnsafeSendable(@_unsafeSendable _ fn: () -> Void) { }
func testUnsafeSendableNothing() {
var x = 5
acceptUnsafeSendable {
x = 17
}
print(x)
}
func testUnsafeSendableInAsync() async {
var x = 5
acceptUnsafeSendable {
x = 17 // expected-error{{mutation of captured var 'x' in concurrently-executing code}}
}
print(x)
}
// ----------------------------------------------------------------------
// Sendable restriction on key paths.
// ----------------------------------------------------------------------
class NC: Hashable { // expected-note 3{{class 'NC' does not conform to the 'Sendable' protocol}}
func hash(into: inout Hasher) { }
static func==(_: NC, _: NC) -> Bool { true }
}
class HasNC {
var dict: [NC: Int] = [:]
}
func testKeyPaths(dict: [NC: Int], nc: NC) {
_ = \HasNC.dict[nc] // expected-warning{{cannot form key path that captures non-sendable type 'NC'}}
}
// ----------------------------------------------------------------------
// Sendable restriction on nonisolated declarations.
// ----------------------------------------------------------------------
actor ANI {
// FIXME: improve diagnostics to talk about nonisolated
nonisolated let nc = NC() // expected-warning{{cannot use property 'nc' with a non-sendable type 'NC' across actors}}
nonisolated func f() -> NC? { nil } // expected-warning{{cannot call function returning non-sendable type 'NC?' across actors}}
}
// ----------------------------------------------------------------------
// Sendable restriction on conformances.
// ----------------------------------------------------------------------
protocol AsyncProto {
func asyncMethod(_: NotConcurrent) async
}
extension A1: AsyncProto {
// FIXME: Poor diagnostic.
func asyncMethod(_: NotConcurrent) async { } // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent' across actors}}
}
protocol MainActorProto {
func asyncMainMethod(_: NotConcurrent) async
}
class SomeClass: MainActorProto {
@SomeGlobalActor
func asyncMainMethod(_: NotConcurrent) async { } // expected-warning{{cannot pass argument of non-sendable type 'NotConcurrent' across actors}}
}
// ----------------------------------------------------------------------
// Sendable restriction on concurrent functions.
// ----------------------------------------------------------------------
@Sendable func concurrentFunc() -> NotConcurrent? { nil }
// ----------------------------------------------------------------------
// No Sendable restriction on @Sendable function types.
// ----------------------------------------------------------------------
typealias CF = @Sendable () -> NotConcurrent?
typealias BadGenericCF<T> = @Sendable () -> T?
typealias GoodGenericCF<T: Sendable> = @Sendable () -> T? // okay
var concurrentFuncVar: (@Sendable (NotConcurrent) -> Void)? = nil
// ----------------------------------------------------------------------
// Sendable restriction on @Sendable closures.
// ----------------------------------------------------------------------
func acceptConcurrentUnary<T>(_: @Sendable (T) -> T) { }
func concurrentClosures<T>(_: T) {
acceptConcurrentUnary { (x: T) in
_ = x // ok
acceptConcurrentUnary { _ in x } // expected-warning{{cannot use parameter 'x' with a non-sendable type 'T' from concurrently-executed code}}
}
}
// ----------------------------------------------------------------------
// Sendable checking
// ----------------------------------------------------------------------
struct S1: Sendable {
var nc: NotConcurrent // expected-error{{stored property 'nc' of 'Sendable'-conforming struct 'S1' has non-sendable type 'NotConcurrent'}}
}
struct S2<T>: Sendable {
var nc: T // expected-error{{stored property 'nc' of 'Sendable'-conforming generic struct 'S2' has non-sendable type 'T'}}
}
struct S3<T> {
var c: T
var array: [T]
}
extension S3: Sendable where T: Sendable { }
enum E1: Sendable {
case payload(NotConcurrent) // expected-error{{associated value 'payload' of 'Sendable'-conforming enum 'E1' has non-sendable type 'NotConcurrent'}}
}
enum E2<T> {
case payload(T)
}
extension E2: Sendable where T: Sendable { }
final class C1: Sendable {
let nc: NotConcurrent? = nil // expected-error{{stored property 'nc' of 'Sendable'-conforming class 'C1' has non-sendable type 'NotConcurrent?'}}
var x: Int = 0 // expected-error{{stored property 'x' of 'Sendable'-conforming class 'C1' is mutable}}
let i: Int = 0
}
final class C2: Sendable {
let x: Int = 0
}
class C3 { }
class C4: C3, @unchecked Sendable {
var y: Int = 0 // okay
}
class C5: @unchecked Sendable {
var x: Int = 0 // okay
}
class C6: C5 {
var y: Int = 0 // still okay, it's unsafe
}
final class C7<T>: Sendable { }
class C9: Sendable { } // expected-error{{non-final class 'C9' cannot conform to 'Sendable'; use '@unchecked Sendable'}}
// ----------------------------------------------------------------------
// @unchecked Sendable disabling checking
// ----------------------------------------------------------------------
struct S11: @unchecked Sendable {
var nc: NotConcurrent // okay
}
struct S12<T>: @unchecked Sendable {
var nc: T // okay
}
enum E11<T>: @unchecked Sendable {
case payload(NotConcurrent) // okay
case other(T) // okay
}
class C11 { }
class C12: @unchecked C11 { } // expected-error{{'unchecked' attribute cannot apply to non-protocol type 'C11'}}
protocol P { }
protocol Q: @unchecked Sendable { } // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
typealias TypeAlias1 = @unchecked P // expected-error{{'unchecked' attribute only applies in inheritance clauses}}
// ----------------------------------------------------------------------
// UnsafeSendable historical name
// ----------------------------------------------------------------------
enum E12<T>: UnsafeSendable { // expected-warning{{'UnsafeSendable' is deprecated: Use @unchecked Sendable instead}}
case payload(NotConcurrent) // okay
case other(T) // okay
}
// ----------------------------------------------------------------------
// @Sendable inference through optionals
// ----------------------------------------------------------------------
func testSendableOptionalInference(nc: NotConcurrent) {
var fn: (@Sendable () -> Void)? = nil
fn = {
print(nc) // expected-warning{{cannot use parameter 'nc' with a non-sendable type 'NotConcurrent' from concurrently-executed code}}
}
_ = fn
}
|
apache-2.0
|
981d4a1c8566240ff3cdabd247828f47
| 34.063091 | 153 | 0.589384 | 4.5 | false | false | false | false |
skyylex/HaffmanSwift
|
Source/FoundationExtension.swift
|
1
|
1319
|
//
// FoundationExtension.swift
// HaffmanCoding
//
// Created by Yury Lapitsky on 12/15/15.
// Copyright © 2015 skyylex. All rights reserved.
//
import Foundation
public extension String {
public func bitsSequence() -> [Bit] {
return self.characters.map { element -> Bit in
return (element == "0") ? .zero : .one
}
}
public static func bitString(_ bits: [Bit]) -> String {
let characters = bits.map { element -> Character in
return (element == .one) ? "1" : "0"
}
return String (characters)
}
fileprivate func generateZeroString(_ zerosAmount: Int) -> String {
let range = (0...(zerosAmount - 1))
return range.reduce("") { current, _ -> String in current + "0" }
}
public func fillWithZeros(_ fullSize: Int) -> String {
let diff = fullSize - self.characters.count
return (diff == 0) ? self : generateZeroString(diff) + self
}
}
public extension Dictionary {
public func join(_ other: Dictionary) -> Dictionary {
var copy = self
copy.update(other)
return copy
}
fileprivate mutating func update(_ other:Dictionary) {
for (key,value) in other {
self.updateValue(value, forKey:key)
}
}
}
|
mit
|
e3b9710c44235d397bfd3f0fd1e78e08
| 25.897959 | 73 | 0.574355 | 4.11875 | false | false | false | false |
iPrysyazhnyuk/SwiftNetworker
|
SwiftNetworker/Classes/SwiftNetworker/NetworkerError.swift
|
1
|
1246
|
//
// NetworkerError.swift
// Pods
//
// Created by Igor on 10/15/17.
//
//
import ObjectMapper
public struct NetworkerError: Error, LocalizedError {
public static let unknownErrorMessage = "Unknown error".localized
/// Additional info in JSON format, can be response from server
public let info: JSON?
/// HTTP status code
public let statusCode: Int?
public var message: String?
public init(info: JSON? = nil,
message: String = NetworkerError.unknownErrorMessage,
statusCode: Int? = nil) {
self.info = info
self.message = message
self.statusCode = statusCode
}
public var errorDescription: String? {
return message
}
}
extension String {
var localized: String {
return NSLocalizedString(self, comment: "")
}
}
extension Error {
public var networkerError: NetworkerError? { return self as? NetworkerError }
/// Parse error if it's NetworkerError
///
/// - Returns: Mappable object
public func parse<T: Mappable>() -> T? {
guard let networkerError = networkerError,
let info = networkerError.info else { return nil }
return T(JSON: info)
}
}
|
mit
|
1d1d605ac98dfb7b1ea681e92b2e84be
| 22.074074 | 81 | 0.62199 | 4.434164 | false | false | false | false |
garygriswold/Bible.js
|
SafeBible2/SafeBible_ios/SafeBible/Models/BibleModel.swift
|
1
|
8104
|
//
// BibleModel.swift
// Settings
//
// Created by Gary Griswold on 7/30/18.
// Copyright © 2018 Short Sands, LLC. All rights reserved.
//
import UIKit
struct Bible : Equatable {
let bibleId: String // FCBH 6 to 8 char code
let abbr: String // Version Abbreviation
let iso3: String // SIL 3 char SIL language code
let name: String // Name in the language, but sometimes in English
let textBucket: String // Name of bucket with text Bible
let textId: String // 2nd part of text s3Key
let s3TextTemplate: String // Template of part of S3 key that identifies object
let audioBucket: String?// Name of bucket with audio Bible
let otDamId: String? // Old Testament DamId
let ntDamId: String? // New Testament DamId
let language: Language
var isDownloaded: Bool?
var tableContents: TableContentsModel?
init(bibleId: String, abbr: String, iso3: String, name: String,
textBucket: String, textId: String, s3TextTemplate: String,
audioBucket: String?, otDamId: String?, ntDamId: String?,
iso: String, script: String) {
self.bibleId = bibleId
self.abbr = abbr
self.iso3 = iso3
self.name = name
self.textBucket = textBucket
self.textId = textId
self.s3TextTemplate = s3TextTemplate
self.audioBucket = audioBucket
self.otDamId = otDamId
self.ntDamId = ntDamId
self.language = Language(iso: iso, script: script)
}
static func == (lhs: Bible, rhs: Bible) -> Bool {
return lhs.bibleId == rhs.bibleId
}
}
class BibleModel : SettingsModel {
let locales: [Language]
var selected: [Bible]
var available: [[Bible]]
var filtered: [Bible] // deprecated, not used
var oneLanguage: Language? // Used only when settingsViewType == .oneLang
private let availableSection: Int
init(availableSection: Int, language: Language?, selectedOnly: Bool) {
let start: Double = CFAbsoluteTimeGetCurrent()
self.availableSection = availableSection
self.oneLanguage = language
let prefLocales = SettingsDB.shared.getLanguageSettings()
self.selected = [Bible]()
var bibles: [String] = SettingsDB.shared.getBibleSettings()
if bibles.count > 0 {
self.selected = VersionsDB.shared.getBiblesSelected(locales: prefLocales, selectedBibles: bibles)
} else {
let initial = BibleInitialSelect()
self.selected = initial.getBiblesSelected(locales: prefLocales)
bibles = selected.map { $0.bibleId }
SettingsDB.shared.updateSettings(bibles: self.selected)
}
let selectedLocales = Set(self.selected.map { $0.language.identifier })
var tempLocales = [Language]()
self.available = [[Bible]]()
if !selectedOnly {
if self.oneLanguage != nil {
let avail = VersionsDB.shared.getBiblesAvailable(locale: oneLanguage!, selectedBibles: bibles)
self.available.append(avail)
} else {
for locale in prefLocales {
let available1 = VersionsDB.shared.getBiblesAvailable(locale: locale,
selectedBibles: bibles)
if available1.count > 0 || selectedLocales.contains(locale.identifier) {
tempLocales.append(locale)
self.available.append(available1)
}
}
}
}
self.locales = tempLocales
self.filtered = [Bible]()
print("*** BibleModel.init duration \((CFAbsoluteTimeGetCurrent() - start) * 1000) ms")
}
deinit {
print("***** deinit BibleModel ******")
}
var selectedCount: Int {
get { return selected.count }
}
var availableCount: Int {
get { return available.count }
}
var filteredCount: Int {
get { return filtered.count }
}
func getSelectedLanguage(row: Int) -> Language? {
return nil
}
func getSelectedBible(row: Int) -> Bible? {
return (row >= 0 && row < selected.count) ? selected[row] : nil
}
func getAvailableLanguage(row: Int) -> Language? {
return nil
}
func getAvailableBibleCount(section: Int) -> Int {
let bibles: [Bible] = self.available[section]
return bibles.count
}
func getAvailableBible(section: Int, row: Int) -> Bible? {
let bibles = self.available[section]
if let bible = (row < bibles.count) ? bibles[row] : nil {
return bible
}
return nil
}
func selectedCell(tableView: UITableView, indexPath: IndexPath) -> UITableViewCell {
let bible = selected[indexPath.row]
return self.generateCell(tableView: tableView, indexPath: indexPath, bible: bible)
}
func availableCell(tableView: UITableView, indexPath: IndexPath, inSearch: Bool) -> UITableViewCell {
let section = indexPath.section - self.availableSection
let bible = self.getAvailableBible(section: section, row: indexPath.row)! // ??????????? safety
return self.generateCell(tableView: tableView, indexPath: indexPath, bible: bible)
}
private func generateCell(tableView: UITableView, indexPath: IndexPath, bible: Bible) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "languageCell", for: indexPath)
cell.backgroundColor = AppFont.backgroundColor
cell.textLabel?.font = AppFont.sansSerif(style: .subheadline)
cell.textLabel?.textColor = AppFont.textColor
cell.detailTextLabel?.font = AppFont.sansSerif(style: .footnote)
cell.textLabel?.text = bible.name
cell.detailTextLabel?.text = bible.abbr
cell.selectionStyle = .default
return cell
}
func moveSelected(source: Int, destination: Int) {
let element = self.selected[source]
self.selected.remove(at: source)
self.selected.insert(element, at: destination)
SettingsDB.shared.updateSettings(bibles: self.selected)
}
func moveAvailableToSelected(source: IndexPath, destination: IndexPath, inSearch: Bool) {
let element: Bible = self.available[source.section - self.availableSection][source.row]
self.available[source.section - self.availableSection].remove(at: source.row)
self.selected.insert(element, at: destination.row)
SettingsDB.shared.updateSettings(bibles: self.selected)
}
func moveSelectedToAvailable(source: IndexPath, destination: IndexPath, inSearch: Bool) {
let element: Bible = self.selected[source.row]
self.selected.remove(at: source.row)
self.available[destination.section - self.availableSection].insert(element, at: destination.row)
SettingsDB.shared.updateSettings(bibles: self.selected)
}
func findAvailableInsertIndex(selectedIndex: IndexPath) -> IndexPath {
let bible = self.selected[selectedIndex.row]
var localeIndex: Int
if self.oneLanguage != nil {
localeIndex = 0
} else {
localeIndex = self.findAvailableLocale(locale: bible.language)
}
let bibleList = self.available[localeIndex]
let searchName = bible.name
for index in 0..<bibleList.count {
let bible = bibleList[index]
if bible.name > searchName {
return IndexPath(item: index, section: (localeIndex + self.availableSection))
}
}
return IndexPath(item: bibleList.count, section: (localeIndex + self.availableSection))
}
private func findAvailableLocale(locale: Language) -> Int {
if let index = self.locales.index(of: locale) {
return index
} else {
return self.locales.count - 1
}
}
func filterForSearch(searchText: String) {
}
}
|
mit
|
c7f78b769f2a63088b797f28e65af992
| 37.770335 | 110 | 0.62372 | 4.337794 | false | false | false | false |
garygriswold/Bible.js
|
Plugins/AudioPlayer/src/ios_oldApp/AudioPlayer/AudioTOCChapter.swift
|
3
|
2605
|
//
// AudioTOCChapter.swift
// AudioPlayer
//
// Created by Gary Griswold on 8/11/17.
// Copyright © 2017 ShortSands. All rights reserved.
//
import CoreMedia
class AudioTOCChapter {
private var versePositions: [Double]
init(json: String) {
let start = json.index(json.startIndex, offsetBy: 1)
let end = json.index(json.endIndex, offsetBy: -1)
let trimmed = json[start..<end]
let parts = trimmed.split(separator: ",")
self.versePositions = [Double](repeating: 0.0, count: parts.count)
for index in 1..<parts.count {
if let dbl = Double(parts[index]) {
self.versePositions[index] = dbl
}
}
//print(self.versePositions)
}
deinit {
print("***** Deinit AudioTOCChapter *****")
}
func hasPositions() -> Bool {
return versePositions.count > 0
}
func findVerseByPosition(priorVerse: Int, time: CMTime) -> Int {
let seconds = Double(CMTimeGetSeconds(time))
return findVerseByPosition(priorVerse: priorVerse, seconds: seconds)
}
func findVerseByPosition(priorVerse: Int, seconds: Double) -> Int {
var index = (priorVerse > 0 && priorVerse < self.versePositions.count) ? priorVerse : 1
let priorPosition = self.versePositions[index]
if (seconds > priorPosition) {
while(index < (self.versePositions.count - 1)) {
index += 1
let versePos = self.versePositions[index]
if (seconds < versePos) {
return index - 1
}
}
return self.versePositions.count - 1
} else if (seconds < priorPosition) {
while(index > 2) {
index -= 1
let versePos = self.versePositions[index]
if (seconds >= versePos) {
return index
}
}
return 1
} else { // seconds == priorPosition
return index
}
}
func findPositionOfVerse(verse: Int) -> CMTime {
let seconds = (verse > 0 && verse < self.versePositions.count) ? self.versePositions[verse] : 0.0
return CMTime(seconds: seconds, preferredTimescale: CMTimeScale(1000))
}
func toString() -> String {
var str = ""
for (index, position) in self.versePositions.enumerated() {
str += "verse_id=" + String(index) + ", position=" + String(position) + "\n"
}
return(str)
}
}
|
mit
|
c13f362af3674cec80731660b4309645
| 30 | 105 | 0.543395 | 4.369128 | false | false | false | false |
devpunk/velvet_room
|
Source/View/SaveData/VSaveData.swift
|
1
|
2422
|
import UIKit
final class VSaveData:ViewMain
{
private(set) weak var viewBar:VSaveDataBar!
private weak var viewList:VSaveDataList!
private weak var viewBack:VSaveDataBarBack!
override var panBack:Bool
{
get
{
return true
}
}
required init(controller:UIViewController)
{
super.init(controller:controller)
guard
let controller:CSaveData = controller as? CSaveData
else
{
return
}
factoryViews(controller:controller)
}
required init?(coder:NSCoder)
{
return nil
}
override func layoutSubviews()
{
super.layoutSubviews()
let barHeight:CGFloat = viewBar.bounds.height
let backRemainHeight:CGFloat = barHeight - viewBack.kHeight
let backMarginBottom:CGFloat = backRemainHeight / -2.0
viewBack.layoutBottom.constant = backMarginBottom
}
//MARK: private
private func factoryViews(controller:CSaveData)
{
let viewList:VSaveDataList = VSaveDataList(
controller:controller)
self.viewList = viewList
let viewBar:VSaveDataBar = VSaveDataBar(
controller:controller)
self.viewBar = viewBar
let viewBack:VSaveDataBarBack = VSaveDataBarBack(
controller:controller)
self.viewBack = viewBack
addSubview(viewBar)
addSubview(viewList)
addSubview(viewBack)
NSLayoutConstraint.topToTop(
view:viewBar,
toView:self)
viewBar.layoutHeight = NSLayoutConstraint.height(
view:viewBar,
constant:viewList.kMinBarHeight)
NSLayoutConstraint.equalsHorizontal(
view:viewBar,
toView:self)
NSLayoutConstraint.equals(
view:viewList,
toView:self)
viewBack.layoutBottom = NSLayoutConstraint.bottomToBottom(
view:viewBack,
toView:viewBar)
NSLayoutConstraint.height(
view:viewBack,
constant:viewBack.kHeight)
NSLayoutConstraint.width(
view:viewBack,
constant:viewBack.kWidth)
NSLayoutConstraint.leftToLeft(
view:viewBack,
toView:self)
}
}
|
mit
|
06e93858e548c2f445eae94f640efb28
| 24.494737 | 67 | 0.580099 | 5.186296 | false | false | false | false |
willowtreeapps/WillowTreeReachability
|
Sources/Monitor.swift
|
1
|
8330
|
//
// Reachability.swift
//
// Copyright © 2015 WillowTree, Inc.
//
import Foundation
import SystemConfiguration
public protocol NetworkStatusSubscriber: class {
func networkStatusChanged(status: ReachabilityStatus)
}
/// Enumeration representing the current network connection status
public enum ReachabilityStatus: Int, CustomStringConvertible {
/// Unknown network state
case unknown
/// Network is not reachable
case notReachable
/// Network is reachable via Wifi
case viaWifi
/// Network is reachable via cellular connection
case viaCellular
/// Returns the ReachabilityStatus based on the passed in reachability flags.
///
/// - parameter flags: the SCNetworkReachablityFlags to check for connectivity
/// - returns: the reachability status
static func statusForReachabilityFlags(_ flags: SCNetworkReachabilityFlags) -> ReachabilityStatus {
let reachable = flags.contains(.reachable)
let requiresConnection = flags.contains(.connectionRequired)
let supportsAutomaticConnection = (flags.contains(.connectionOnDemand) || flags.contains(.connectionOnTraffic))
let requiresUserInteraction = flags.contains(.interventionRequired)
let networkReachable = (reachable &&
(!requiresConnection || (supportsAutomaticConnection && !requiresUserInteraction)))
if !networkReachable {
return .notReachable
} else if flags.contains(.isWWAN) {
return .viaCellular
} else {
return .viaWifi
}
}
/// Printable description of the given status
public var description: String {
get {
switch self {
case .unknown:
return "Unknown"
case .notReachable:
return "Not reachable"
case .viaCellular:
return "Reachable via cellular"
case .viaWifi:
return "Reachable via wifi"
}
}
}
}
/// Subscription token used to keep a subscription to the network montitoring alive.
public class NetworkStatusSubscription {
weak var subscriber: NetworkStatusSubscriber?
weak var monitor: Monitor?
init(subscriber: NetworkStatusSubscriber?, monitor: Monitor?)
{
self.subscriber = subscriber
self.monitor = monitor
}
deinit {
monitor?.removeSubscription(self)
}
}
public class Monitor {
/// Returns the current reachability status
public var status: ReachabilityStatus {
var flags = SCNetworkReachabilityFlags()
if SCNetworkReachabilityGetFlags(self.reachabilityReference, &flags) {
return ReachabilityStatus.statusForReachabilityFlags(flags)
}
return .unknown
}
var subscriptions = [NetworkStatusSubscriber]()
var unsafeSelfPointer = UnsafeMutablePointer<Monitor>.allocate(capacity: 1)
private let callbackQueue = DispatchQueue(label: "com.willowtreeapps.Reachability", attributes: .concurrent)
private var monitoringStarted = false
var reachabilityReference: SCNetworkReachability!
var reachabilityFlags: SCNetworkReachabilityFlags?
/// Initialize monitoring for general internet connection
convenience public init?()
{
var zeroAddress = sockaddr_in()
bzero(&zeroAddress, MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
zeroAddress.sin_family = UInt8(AF_INET)
let address_in = UnsafeMutablePointer<sockaddr_in>.allocate(capacity: 1)
address_in.initialize(to: zeroAddress)
self.init(withAddress: address_in)
}
/// Initialize monitoring for the specified socket address.
///
/// - parameter withAddress: the socket address to use when checking reachability
public init?(withAddress address: UnsafeMutablePointer<sockaddr_in>) {
guard let reachabilityReference = address.withMemoryRebound(to: sockaddr.self, capacity: 1, {
return SCNetworkReachabilityCreateWithAddress(nil, $0)
}) else {
return nil
}
self.reachabilityReference = reachabilityReference
}
/// Initialize reachability checking for connection to the specified host name with URL
/// - parameter withURL: the URL of the server to connect to
public init?(withURL URL: NSURL) {
guard let host = URL.host,
let reachabilityReference = SCNetworkReachabilityCreateWithName(nil, host) else {
return nil
}
self.reachabilityReference = reachabilityReference
}
deinit {
reachabilityReference = nil
unsafeSelfPointer.deallocate(capacity: 1)
}
/// Starts the asynchronous monitoring of network reachability.
///
/// - return: true if the notifications started successfully
public func start() -> Bool {
guard !monitoringStarted else {
return true
}
monitoringStarted = true
var networkReachabilityContext = SCNetworkReachabilityContext()
unsafeSelfPointer.initialize(to: self)
networkReachabilityContext.info = UnsafeMutableRawPointer(unsafeSelfPointer)
if SCNetworkReachabilitySetCallback(reachabilityReference, Monitor.systemReachabilityCallback(), &networkReachabilityContext) {
if SCNetworkReachabilityScheduleWithRunLoop(reachabilityReference, CFRunLoopGetCurrent(), RunLoopMode.defaultRunLoopMode.rawValue as CFString) {
return true
}
}
return false
}
/// Stops the current monitoring of network reachability
public func stop() {
guard monitoringStarted else {
return
}
if reachabilityReference != nil {
SCNetworkReachabilityUnscheduleFromRunLoop(reachabilityReference, CFRunLoopGetCurrent(), RunLoopMode.defaultRunLoopMode.rawValue as CFString)
}
unsafeSelfPointer.deallocate(capacity: 1)
monitoringStarted = false
}
/// Subscribes the specified subscriber for network changes. This function returns a subscription
/// object that must be held strongly by the callee to keep the subscription active. Once the
/// returned subscription falls out of scope, the subscription is automatically removed.
///
/// - parameter subscriber: the subscriber for network status notification changes
/// - returns: a subscription token that must be retained for the subscription to remain active
public func addSubscription(using subscriber: NetworkStatusSubscriber) -> NetworkStatusSubscription {
let subscription = NetworkStatusSubscription(subscriber: subscriber, monitor: self)
subscriptions.append(subscriber)
return subscription
}
/// Removes a subscriptions from the current list of subscriptions.
///
/// - parameter subscription: the subscription to remove from the list of subscribers
public func removeSubscription(_ subscription: NetworkStatusSubscription) {
subscriptions = subscriptions.filter {
$0 !== subscription.subscriber
}
}
/// Internal callback called by the system configuration framework
static func systemReachabilityCallback() -> SCNetworkReachabilityCallBack {
let callback: SCNetworkReachabilityCallBack = {(target: SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutableRawPointer?) in
guard let info = info else {
return
}
let reachabiltyReference = UnsafeMutablePointer<Monitor>(info.assumingMemoryBound(to: Monitor.self))
let reachability = reachabiltyReference.pointee
let reachabilityStatus = ReachabilityStatus.statusForReachabilityFlags(flags)
for subscriber in reachability.subscriptions {
reachability.callbackQueue.async {
subscriber.networkStatusChanged(status: reachabilityStatus)
}
}
}
return callback
}
}
|
mit
|
68cecd8894d96f2b5017a5a3cb3636ba
| 35.213043 | 156 | 0.667307 | 6.031137 | false | false | false | false |
hajunsa/comicpal
|
Sources/WSConnectionUpgradeFactory.swift
|
1
|
4511
|
/*
* Copyright IBM Corporation 2016-2017
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
import Cryptor
import KituraNet
/// The implementation of the ConnectionUpgradeFactory protocol for the WebSocket protocol.
/// Participates in the HTTP protocol upgrade process when upgarding to the WebSocket protocol.
public class WSConnectionUpgradeFactory: ConnectionUpgradeFactory {
private var registry = Dictionary<String, WebSocketService>()
private let wsGUID = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
/// The name of the protocol supported by this `ConnectionUpgradeFactory`.
public let name = "websocket"
init() {
ConnectionUpgrader.register(factory: self)
}
/// "Upgrade" a connection to the WebSocket protocol. Invoked by the KituraNet.ConnectionUpgrader when
/// an upgrade request is being handled.
///
/// - Parameter handler: The `IncomingSocketHandler` that is handling the connection being upgraded.
/// - Parameter request: The `ServerRequest` object of the incoming "upgrade" request.
/// - Parameter response: The `ServerResponse` object that will be used to send the response of the "upgrade" request.
///
/// - Returns: A tuple of the created `WSSocketProcessor` and a message to send as the body of the response to
/// the upgrade request. The `WSSocketProcessor` will be nil if the upgrade request wasn't successful.
/// If the message is nil, the response will not contain a body.
public func upgrade(handler: IncomingSocketHandler, request: ServerRequest, response: ServerResponse) -> (IncomingSocketProcessor?, String?) {
guard let protocolVersion = request.headers["Sec-WebSocket-Version"] else {
return (nil, "Sec-WebSocket-Version header missing in the upgrade request")
}
guard protocolVersion[0] == "13" else {
response.headers["Sec-WebSocket-Version"] = ["13"]
return (nil, "Only WebSocket protocol version 13 is supported")
}
guard let securityKey = request.headers["Sec-WebSocket-Key"] else {
return (nil, "Sec-WebSocket-Key header missing in the upgrade request")
}
guard let service = registry[request.urlURL.path] else {
return (nil, "No service has been registered for the path \(request.urlURL.path)")
}
let sha1 = Digest(using: .sha1)
let sha1Bytes = sha1.update(string: securityKey[0] + wsGUID)!.final()
let sha1Data = Data(bytes: sha1Bytes, count: sha1Bytes.count)
response.headers["Sec-WebSocket-Accept"] =
[sha1Data.base64EncodedString(options: .lineLength64Characters)]
response.headers["Sec-WebSocket-Protocol"] = request.headers["Sec-WebSocket-Protocol"]
let connection = WebSocketConnection(request: request)
let processor = WSSocketProcessor(connection: connection)
connection.processor = processor
connection.service = service
return (processor, nil)
}
func register(service: WebSocketService, onPath: String) {
let path: String
if onPath.hasPrefix("/") {
path = onPath
}
else {
path = "/" + onPath
}
registry[path] = service
}
func unregister(onPath: String) {
let path: String
if onPath.hasPrefix("/") {
path = onPath
}
else {
path = "/" + onPath
}
registry.removeValue(forKey: path)
}
func hasRegistry(onPath: String) -> Bool {
let path: String
if onPath.hasPrefix("/") {
path = onPath
}
else {
path = "/" + onPath
}
return registry[path] != nil
}
/// Clear the `WebSocketService` registry. Used in testing.
func clear() {
registry.removeAll()
}
}
|
apache-2.0
|
4d15cbdcead812ae4c026d3be98541f4
| 37.555556 | 146 | 0.64243 | 4.551968 | false | false | false | false |
franciscocgoncalves/BindViewControllerToView
|
Example/BindViewControllerToView/CollectionViewController.swift
|
1
|
1783
|
//
// CollectionViewController.swift
// CellViewController
//
// Created by Francisco Gonçalves on 19/12/15.
// Copyright © 2015 CocoaPods. All rights reserved.
//
import UIKit
import BindViewControllerToView
private let reuseIdentifier = "Cell"
class CollectionViewController: UICollectionViewController, UICollectionViewDelegateFlowLayout {
var model: [String] = ["Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World", "Hello World"]
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.registerClass(MyCollectionCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
}
// MARK: UICollectionViewDataSource
extension CollectionViewController {
override func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return model.count
}
override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath)
if let cell = cell as? MyCollectionCell {
cell.parentViewController = self
cell.viewController?.model = model[indexPath.item]
}
return cell
}
func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
return CGSize(width: 300, height: 300)
}
}
|
mit
|
dfd3cdc09dee7a8f0fff47e132336f06
| 33.25 | 294 | 0.771477 | 4.86612 | false | false | false | false |
xuanyi0627/jetstream-ios
|
Jetstream/Client.swift
|
1
|
8085
|
//
// Client.swift
// Jetstream
//
// Copyright (c) 2014 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
let clientVersion = "0.2.0"
let defaultErrorDomain = "com.uber.jetstream"
/// Connectivity status of the client.
public enum ClientStatus {
/// Client is offline.
case Offline
/// Client is online.
case Online
}
/// A function that when invoked creates a TransportAdapter for use.
public typealias TransportAdapterFactory = () -> TransportAdapter
/// A Client is used to initiate a connection between the application model and the remote Jetstream
/// server. A client uses a TransportAdapter to establish a connection to the server.
@objc public class Client: NSObject {
// MARK: - Events
/// Signal that fires whenever the status of the client changes. The fired data contains the
/// new status for the client.
public let onStatusChanged = Signal<(ClientStatus)>()
/// Signal that fires whenever the clients gets a new session. The fired data contains the
/// new session.
public let onSession = Signal<(Session)>()
/// Signal that fires whenever a session was denied.
public let onSessionDenied = Signal<()>()
/// Signal that fires whenever a message is sent that is waiting an acknowledgment from the
/// server. This can be observed to tell when server has a lot of messages it has not replied to.
public let onWaitingRepliesCountChanged: Signal<(UInt)>
// MARK: - Properties
/// The status of the client.
public private(set) var status: ClientStatus = .Offline {
didSet {
if oldValue != status {
onStatusChanged.fire(status)
}
}
}
/// The session of the client.
public private(set) var session: Session? {
didSet {
if session != nil {
transport.adapter.sessionEstablished(session!)
onSession.fire(session!)
}
}
}
let logger = Logging.loggerFor("Client")
let transportAdapterFactory: TransportAdapterFactory
let restartSessionOnFatalError: Bool
var transport: Transport
var sessionCreateParams = [String: AnyObject]()
// MARK: - Public interface
/// Constructs a client.
///
/// :param: transportAdapterFactory The factory used to create a transport adapter to connect to a Jetstream server.
/// :param: restartSessionOnFatalError Whether to restart a session on a fatal session or transport error.
public init(transportAdapterFactory: TransportAdapterFactory, restartSessionOnFatalError: Bool = true) {
self.transportAdapterFactory = transportAdapterFactory
self.transport = Transport(adapter: transportAdapterFactory())
self.onWaitingRepliesCountChanged = transport.onWaitingRepliesCountChanged
self.restartSessionOnFatalError = restartSessionOnFatalError
super.init()
bindListeners()
}
/// Starts connecting the client to the server.
public func connect() {
transport.connect()
}
/// Starts connecting the client to the server with params to supply to server when creating a session.
///
/// :param: sessionCreateParams The params that should be sent along with the session create request.
public func connectWithSessionCreateParams(sessionCreateParams: [String: AnyObject]) {
self.sessionCreateParams = sessionCreateParams
connect()
}
/// Closes the connection to the server.
public func close() {
transport.disconnect()
session?.close()
session = nil
}
/// MARK: - Internal interface
func bindListeners() {
onStatusChanged.listen(self) { [weak self] (status) in
if let this = self {
this.statusChanged(status)
}
}
bindTransportListeners()
}
func bindTransportListeners() {
transport.onStatusChanged.listen(self) { [weak self] (status) in
if let this = self {
this.transportStatusChanged(status)
}
}
transport.onMessage.listen(self) { [weak self] (message: NetworkMessage) in
asyncMain {
if let this = self {
this.receivedMessage(message)
}
}
}
}
func unbindTransportListeners() {
transport.onStatusChanged.removeListener(self)
transport.onMessage.removeListener(self)
}
func statusChanged(clientStatus: ClientStatus) {
switch clientStatus {
case .Online:
logger.info("Online")
if session == nil {
transport.sendMessage(SessionCreateMessage(params: sessionCreateParams))
}
case .Offline:
logger.info("Offline")
}
}
func transportStatusChanged(transportStatus: TransportStatus) {
switch transportStatus {
case .Closed:
status = .Offline
case .Connecting:
status = .Offline
case .Connected:
status = .Online
case .Fatal:
status = .Offline
if restartSessionOnFatalError && session != nil {
reinitializeTransportAndRestartSession()
}
}
}
func receivedMessage(message: NetworkMessage) {
switch message {
case let sessionCreateReply as SessionCreateReplyMessage:
if session != nil {
logger.error("Received session create response with existing session")
} else if let token = sessionCreateReply.sessionToken {
logger.info("Starting session with token: \(token)")
session = Session(client: self, token: token)
} else {
logger.info("Denied starting session, error: \(sessionCreateReply.error)")
onSessionDenied.fire()
}
default:
session?.receivedMessage(message)
}
}
func reinitializeTransportAndRestartSession() {
var scopesAndFetchParams = [ScopesWithFetchParams]()
if let scopesByIndex = session?.scopes {
scopesAndFetchParams = scopesByIndex.values.array
}
session?.close()
session = nil
onSession.listenOnce(self) { [weak self] session in
if let this = self {
for (scope, params) in scopesAndFetchParams {
session.fetch(scope, params: params) { error in
if let definiteError = error {
this.logger.error("Received error refetching scope '\(scope.name)': \(error)")
}
}
}
}
}
unbindTransportListeners()
transport = Transport(adapter: transportAdapterFactory())
bindTransportListeners()
connect()
}
}
|
mit
|
290bf351ed2af60f5b7df781d7579d13
| 34.933333 | 120 | 0.630056 | 5.046816 | false | false | false | false |
RobotsAndPencils/SwiftCharts
|
Examples/Examples/MultipleLabelsExample.swift
|
3
|
3546
|
//
// MultipleLabelsExample.swift
// SwiftCharts
//
// Created by ischuetz on 04/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class MultipleLabelsExample: UIViewController {
private var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFont)
let cp1 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 2), y: ChartAxisValueDouble(2))
let cp2 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 4), y: ChartAxisValueDouble(6))
let cp3 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 5), y: ChartAxisValueDouble(12))
let cp4 = ChartPoint(x: MyMultiLabelAxisValue(myVal: 8), y: ChartAxisValueDouble(4))
let chartPoints = [cp1, cp2, cp3, cp4]
let xValues = chartPoints.map{$0.x}
let yValues = ChartAxisValuesGenerator.generateYAxisValuesWithChartPoints(chartPoints, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: labelSettings)}, addPaddingSegmentIfEdge: false)
let xModel = ChartAxisModel(axisValues: xValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings))
let yModel = ChartAxisModel(axisValues: yValues, axisTitleLabel: ChartAxisLabel(text: "Axis title", settings: labelSettings.defaultVertical()))
let chartFrame = ExamplesDefaults.chartFrame(self.view.bounds)
let chartSettings = ExamplesDefaults.chartSettings
chartSettings.trailing = 20
let coordsSpace = ChartCoordsSpaceLeftBottomSingleAxis(chartSettings: chartSettings, chartFrame: chartFrame, xModel: xModel, yModel: yModel)
let (xAxis, yAxis, innerFrame) = (coordsSpace.xAxis, coordsSpace.yAxis, coordsSpace.chartInnerFrame)
let lineModel = ChartLineModel(chartPoints: chartPoints, lineColor: UIColor.redColor(), lineWidth: 1, animDuration: 1, animDelay: 0)
let chartPointsLineLayer = ChartPointsLineLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, lineModels: [lineModel])
let settings = ChartGuideLinesDottedLayerSettings(linesColor: UIColor.blackColor(), linesWidth: ExamplesDefaults.guidelinesWidth)
let guidelinesLayer = ChartGuideLinesDottedLayer(xAxis: xAxis, yAxis: yAxis, innerFrame: innerFrame, settings: settings)
let chart = Chart(
frame: chartFrame,
layers: [
xAxis,
yAxis,
guidelinesLayer,
chartPointsLineLayer
]
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
private class MyMultiLabelAxisValue: ChartAxisValue {
private let myVal: Int
private let derivedVal: Double
init(myVal: Int) {
self.myVal = myVal
self.derivedVal = Double(myVal) / 5.0
super.init(scalar: Double(myVal))
}
override var labels:[ChartAxisLabel] {
return [
ChartAxisLabel(text: "\(self.myVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(18), fontColor: UIColor.blackColor())),
ChartAxisLabel(text: "blabla", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(10), fontColor: UIColor.blueColor())),
ChartAxisLabel(text: "\(self.derivedVal)", settings: ChartLabelSettings(font: UIFont.systemFontOfSize(14), fontColor: UIColor.purpleColor()))
]
}
}
|
apache-2.0
|
e5fbd43f69315a6d00633dc0b508c643
| 43.886076 | 259 | 0.688663 | 5.058488 | false | false | false | false |
victorpimentel/SwiftLint
|
Source/SwiftLintFramework/Rules/ConditionalReturnsOnNewlineRule.swift
|
2
|
2361
|
//
// ConditionalReturnsOnNewlineRule.swift
// SwiftLint
//
// Created by Rohan Dhaimade on 12/8/16.
// Copyright © 2016 Realm. All rights reserved.
//
import Foundation
import SourceKittenFramework
public struct ConditionalReturnsOnNewlineRule: ConfigurationProviderRule, Rule, OptInRule {
public var configuration = SeverityConfiguration(.warning)
public init() {}
public static let description = RuleDescription(
identifier: "conditional_returns_on_newline",
name: "Conditional Returns on Newline",
description: "Conditional statements should always return on the next line",
nonTriggeringExamples: [
"guard true else {\n return true\n}",
"guard true,\n let x = true else {\n return true\n}",
"if true else {\n return true\n}",
"if true,\n let x = true else {\n return true\n}",
"if textField.returnKeyType == .Next {",
"if true { // return }",
"/*if true { */ return }"
],
triggeringExamples: [
"↓guard true else { return }",
"↓if true { return }",
"↓if true { break } else { return }",
"↓if true { break } else { return }",
"↓if true { return \"YES\" } else { return \"NO\" }"
]
)
public func validate(file: File) -> [StyleViolation] {
let pattern = "(guard|if)[^\n]*return"
return file.rangesAndTokens(matching: pattern).filter { _, tokens in
guard let firstToken = tokens.first, let lastToken = tokens.last,
SyntaxKind(rawValue: firstToken.type) == .keyword &&
SyntaxKind(rawValue: lastToken.type) == .keyword else {
return false
}
return ["if", "guard"].contains(content(for: firstToken, file: file)) &&
content(for: lastToken, file: file) == "return"
}.map {
StyleViolation(ruleDescription: type(of: self).description,
severity: configuration.severity,
location: Location(file: file, characterOffset: $0.0.location))
}
}
private func content(for token: SyntaxToken, file: File) -> String {
return file.contents.bridge().substringWithByteRange(start: token.offset, length: token.length) ?? ""
}
}
|
mit
|
ae6bebe4f4e8a7a24d53622c1d20b825
| 38.166667 | 109 | 0.58383 | 4.598826 | false | true | false | false |
firebase/snippets-ios
|
appcheck/AppCheckSnippetsSwift/YourCustomAppCheckProvider.swift
|
1
|
1892
|
//
// Copyright (c) 2021 Google Inc.
//
// 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 FirebaseAppCheck
// [START appcheck_custom_provider]
class YourCustomAppCheckProvider: NSObject, AppCheckProvider {
var app: FirebaseApp
init(withFirebaseApp app: FirebaseApp) {
self.app = app
super.init()
}
func getToken(completion handler: @escaping (AppCheckToken?, Error?) -> Void) {
DispatchQueue.main.async {
// Logic to exchange proof of authenticity for an App Check token.
// [START_EXCLUDE]
let expirationFromServer = 1000.0
let tokenFromServer = "token"
// [END_EXCLUDE]
// Create AppCheckToken object.
let exp = Date(timeIntervalSince1970: expirationFromServer)
let token = AppCheckToken(
token: tokenFromServer,
expirationDate: exp
)
// Pass the token or error to the completion handler.
handler(token, nil)
}
}
}
// [END appcheck_custom_provider]
// [START appcheck_custom_provider_factory]
class YourCustomAppCheckProviderFactory: NSObject, AppCheckProviderFactory {
func createProvider(with app: FirebaseApp) -> AppCheckProvider? {
return YourCustomAppCheckProvider(withFirebaseApp: app)
}
}
// [END appcheck_custom_provider_factory]
|
apache-2.0
|
0ba1c92752d1ab4653d094947deef69e
| 32.785714 | 83 | 0.671247 | 4.349425 | false | false | false | false |
antonio081014/LeeCode-CodeBase
|
Swift/remove-covered-intervals.swift
|
2
|
656
|
/**
* https://leetcode.com/problems/remove-covered-intervals/
*
*
*/
// Date: Sun Oct 4 10:24:29 PDT 2020
class Solution {
func removeCoveredIntervals(_ inter: [[Int]]) -> Int {
let intervals = inter.sorted { (a, b) in
if a[0] == b[0] { return a[1] >= b[1] }
return a[0] < b[0]
}
// print("\(intervals)")
var rightEnd = 0
var result = 1
for index in stride(from: 1, to: intervals.count, by: 1) {
if intervals[index][1] > intervals[rightEnd][1] {
result += 1
rightEnd = index
}
}
return result
}
}
|
mit
|
b701d765526a4657a4811fd20259be8a
| 26.375 | 66 | 0.481707 | 3.584699 | false | false | false | false |
Chaosspeeder/YourGoals
|
YourGoals/Main/AppBadgeCalculator.swift
|
1
|
1133
|
//
// AppBadgeCalculator.swift
// YourGoals
//
// Created by André Claaßen on 24.11.17.
// Copyright © 2017 André Claaßen. All rights reserved.
//
import Foundation
class AppBadgeCalculator {
let todayActionablesDataSource:TodayAllActionablesDataSource
init(manager:GoalsStorageManager) {
self.todayActionablesDataSource = TodayAllActionablesDataSource(manager: manager)
}
/// calculate the number of active actionables for the given date
///
/// - Parameter date: the date
/// - Returns: number of active actionables. unchecked tasks plus unchecked habits
/// - Throws: a core data exception
func numberOfActiveActionables(forDate date: Date, withBackburned backburnedGoals: Bool) throws -> NSNumber {
let actionables = try self.todayActionablesDataSource.fetchItems(forDate: date, withBackburned: backburnedGoals, andSection: nil)
let numberOfActiveActionables = actionables.reduce(0) {
$0 + (($1.actionable.checkedState(forDate: date) == .active) ? 1 : 0)
}
return NSNumber(value: numberOfActiveActionables)
}
}
|
lgpl-3.0
|
01218360fb03561bba79c46f152c99ad
| 35.387097 | 137 | 0.707447 | 4.355212 | false | false | false | false |
openHPI/xikolo-ios
|
iOS/Views/AdditionalLearningMaterialCell.swift
|
1
|
2532
|
//
// Created for xikolo-ios under GPL-3.0 license.
// Copyright © HPI. All rights reserved.
//
import Common
import UIKit
class AdditionalLearningMaterialCell: UICollectionViewCell {
@IBOutlet private weak var cardView: UIView!
@IBOutlet private weak var gradientView: UIView!
@IBOutlet private weak var iconImageView: UIImageView!
@IBOutlet private weak var titleLabel: UILabel!
private lazy var gradientLayer: CAGradientLayer = {
let gradient = CAGradientLayer()
gradient.startPoint = CGPoint(x: -1, y: -1)
gradient.endPoint = CGPoint(x: 1, y: 1)
gradient.colors = [UIColor.clear.cgColor, ColorCompatibility.systemBackground.withAlphaComponent(0.2).cgColor]
gradient.locations = [0.0, 1.0]
gradient.frame = CGRect(x: 0.0, y: 0.0, width: self.gradientView.frame.size.width, height: self.gradientView.frame.size.height)
return gradient
}()
override func awakeFromNib() {
super.awakeFromNib()
self.cardView.layer.roundCorners(for: .default)
self.gradientView.layer.insertSublayer(self.gradientLayer, at: 0)
self.gradientView.layer.roundCorners(for: .default)
self.cardView.addDefaultPointerInteraction()
}
override func layoutSubviews() {
super.layoutSubviews()
self.gradientView.layer.sublayers?.first?.frame = CGRect(x: 0.0, y: 0.0, width: self.bounds.width, height: self.gradientView.frame.size.height)
}
override func traitCollectionDidChange(_ previousTraitCollection: UITraitCollection?) {
super.traitCollectionDidChange(previousTraitCollection)
if #available(iOS 13, *) {
if self.traitCollection.hasDifferentColorAppearance(comparedTo: previousTraitCollection) {
self.gradientLayer.colors = [UIColor.clear.cgColor, ColorCompatibility.systemBackground.withAlphaComponent(0.2).cgColor]
}
}
}
func configure(for learningMaterial: AdditionalLearningMaterial) {
self.cardView.backgroundColor = Brand.default.colors.window
self.iconImageView.tintColor = ColorCompatibility.systemBackground.withAlphaComponent(0.95)
self.iconImageView.image = learningMaterial.imageName.flatMap(UIImage.init(named:))
self.titleLabel.textColor = ColorCompatibility.systemBackground.withAlphaComponent(0.95)
self.titleLabel.text = learningMaterial.title
}
}
extension AdditionalLearningMaterialCell {
static var cardInset: CGFloat {
return 8
}
}
|
gpl-3.0
|
f4c2c9bfde2bd7c6d1ee920155e94fcd
| 37.348485 | 151 | 0.711972 | 4.601818 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit
|
SwiftKit/tool/BQTool.swift
|
1
|
5650
|
//
// BQTool.swift
// swift4.2Demo
//
// Created by baiqiang on 2018/10/8.
// Copyright © 2018年 baiqiang. All rights reserved.
//
import UIKit
class BQTool: NSObject {
static private var sapceName: String?
//MARK:- ***** 计算方法耗时 *****
class func getFuntionUseTime(function:()->()) {
let start = CACurrentMediaTime()
function()
let end = CACurrentMediaTime()
Log("方法耗时为:\(end-start)")
}
//MARK:- ***** 对象转json *****
class func jsonFromObject(obj:Any) -> String {
guard let data = try? JSONSerialization.data(withJSONObject: obj, options: .prettyPrinted) else {
return String(describing: obj)
}
if let result = String(data: data, encoding: .utf8) {
return result
}
return String(describing: obj)
}
class func currentSapceName() -> String {
if sapceName == nil {
var arrSapce = self.classForCoder().description().split(separator: ".")
arrSapce.removeLast()
sapceName = arrSapce.joined()
}
return sapceName!
}
class func loadVc(vcName:String, spaceName: String? = nil) -> UIViewController? {
var clsName = ""
if let space = spaceName{
clsName = space + "." + vcName
} else {
clsName = self.currentSapceName() + "." + vcName
}
let cls = NSClassFromString(clsName) as? UIViewController.Type
let vc = cls?.init()
if let valueVc = vc {
return valueVc
} else {
return nil
}
}
/// 类实例方法交换
///
/// - Parameters:
/// - cls: 类名
/// - targetSel: 目标方法
/// - newSel: 替换方法
@discardableResult
public class func exchangeMethod(cls: AnyClass?, targetSel: Selector, newSel: Selector) -> Bool {
guard let before: Method = class_getInstanceMethod(cls, targetSel),
let after: Method = class_getInstanceMethod(cls, newSel) else {
return false
}
method_exchangeImplementations(before, after)
return true
}
///获取设备型号
class var modelName: String {
var systemInfo = utsname()
uname(&systemInfo)
let machineMirror = Mirror(reflecting: systemInfo.machine)
let identifier = machineMirror.children.reduce("") { identifier, element in
guard let value = element.value as? Int8, value != 0 else { return identifier }
return identifier + String(UnicodeScalar(UInt8(value)))
}
switch identifier {
case "iPod5,1": return "iPod Touch 5"
case "iPod7,1": return "iPod Touch 6"
case "iPhone3,1", "iPhone3,2", "iPhone3,3": return "iPhone 4"
case "iPhone4,1": return "iPhone 4s"
case "iPhone5,1", "iPhone5,2": return "iPhone 5"
case "iPhone5,3", "iPhone5,4": return "iPhone 5c"
case "iPhone6,1", "iPhone6,2": return "iPhone 5s"
case "iPhone7,2": return "iPhone 6"
case "iPhone7,1": return "iPhone 6 Plus"
case "iPhone8,1": return "iPhone 6s"
case "iPhone8,2": return "iPhone 6s Plus"
case "iPhone8,4": return "iPhone SE"
case "iPhone9,1": return "iPhone 7"
case "iPhone9,2": return "iPhone 7 Plus"
case "iPad2,1", "iPad2,2", "iPad2,3", "iPad2,4":return "iPad 2"
case "iPad3,1", "iPad3,2", "iPad3,3": return "iPad 3"
case "iPad3,4", "iPad3,5", "iPad3,6": return "iPad 4"
case "iPad4,1", "iPad4,2", "iPad4,3": return "iPad Air"
case "iPad5,3", "iPad5,4": return "iPad Air 2"
case "iPad2,5", "iPad2,6", "iPad2,7": return "iPad Mini"
case "iPad4,4", "iPad4,5", "iPad4,6": return "iPad Mini 2"
case "iPad4,7", "iPad4,8", "iPad4,9": return "iPad Mini 3"
case "iPad5,1", "iPad5,2": return "iPad Mini 4"
case "iPad6,7", "iPad6,8": return "iPad Pro"
case "AppleTV5,3": return "Apple TV"
case "i386", "x86_64": return "Simulator"
default: return identifier
}
}
class func currentBundleIdentifier() -> String {
return Bundle.main.bundleIdentifier!
}
class func currentVersion() -> String {
return UIDevice.current.systemVersion
}
class func uuidIdentifier() -> String? {
return UIDevice.current.identifierForVendor?.uuidString
}
}
/// 需要在build setting -> other swift flags -> Debug 中设置 -D DEBUG
func Log<T>(_ messsage : T, file : String = #file, funcName : String = #function, lineNum : Int = #line) {
#if DEBUG
let fileName = (file as NSString).lastPathComponent.split(separator: ".").first!
print("\(fileName) -> \(funcName) -> line:\(lineNum) ==> \(messsage)")
#endif
}
func iPhoneXUp() -> Bool {
return UIScreen.main.bounds.size.height >= 812
}
|
apache-2.0
|
a7db5591dc8dd6f01c5c8c0d1c315089
| 35.097403 | 106 | 0.503508 | 4.286045 | false | false | false | false |
apple/swift-experimental-string-processing
|
Sources/_StringProcessing/Algorithms/Matching/MatchResult.swift
|
1
|
865
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2021-2022 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
//
//===----------------------------------------------------------------------===//
struct _MatchResult<S: MatchingCollectionSearcher> {
let match: S.Searched.SubSequence
let result: S.Match
var range: Range<S.Searched.Index> {
match.startIndex..<match.endIndex
}
}
struct _BackwardMatchResult<S: BackwardMatchingCollectionSearcher> {
let match: S.BackwardSearched.SubSequence
let result: S.Match
var range: Range<S.BackwardSearched.Index> {
match.startIndex..<match.endIndex
}
}
|
apache-2.0
|
54d006d64111daddf3e84cf6ba3ede6c
| 29.892857 | 80 | 0.601156 | 4.675676 | false | false | false | false |
Judy-u/Reflect
|
Reflect/Reflect/Model2Dict/Reflect+Convert.swift
|
4
|
2236
|
//
// Reflect+Convert.swift
// Reflect
//
// Created by 成林 on 15/8/23.
// Copyright (c) 2015年 冯成林. All rights reserved.
//
import Foundation
/** 模型转字典 */
extension Reflect{
func toDict() -> [String: Any]{
var dict: [String: Any] = [:]
self.properties { (name, type, value) -> Void in
if type.isOptional{
if type.realType == ReflectType.RealType.Class { //模型
dict[name] = (value as? Reflect)?.toDict()
}else{ //基本属性
dict[name] = "\(value)".replacingOccurrencesOfString("Optional(", withString: "").replacingOccurrencesOfString(")", withString: "").replacingOccurrencesOfString("\"", withString: "")
}
}else{
if type.realType == ReflectType.RealType.Class { //模型
if type.isArray { //数组
var dictM: [[String: Any]] = []
let modelArr = value as! NSArray
for item in modelArr {
let dict = (item as! Reflect).toDict()
dictM.append(dict)
}
dict[name] = dictM
}else{
dict[name] = (value as! Reflect).toDict()
}
}else{ //基本属性
dict[name] = "\(value)".replacingOccurrencesOfString("Optional(", withString: "").replacingOccurrencesOfString(")", withString: "").replacingOccurrencesOfString("\"", withString: "")
}
}
}
return dict
}
}
|
mit
|
9532f84c116d312a2815567414dc196f
| 27.763158 | 202 | 0.351327 | 6.564565 | false | false | false | false |
Aneapiy/Swift-HAR
|
Swift-HAR/Dataset.swift
|
1
|
3293
|
//
// Dataset.swift
// Swift-AI
//
// Created by Collin Hundley on 4/4/17.
//
//
import Foundation
public extension NeuralNet {
/// A complete dataset for training a neural network, including training sets and validation sets.
public struct Dataset {
public enum Error: Swift.Error {
case data(String)
}
// Training
/// The full set of inputs for the training set.
public let trainInputs: [[Float]]
/// The full set of labels for the training set.
public let trainLabels: [[Float]]
// Validation
/// The full set of inputs for the validation set.
public let validationInputs: [[Float]]
/// The full set of labels for the validation set.
public let validationLabels: [[Float]]
public init(trainInputs: [[Float]], trainLabels: [[Float]],
validationInputs: [[Float]], validationLabels: [[Float]],
structure: NeuralNet.Structure) throws {
// Ensure that an equal number of sets were provided for inputs and their corresponding answers
guard trainInputs.count == trainLabels.count && validationInputs.count == validationLabels.count else {
throw Error.data("The number of input sets provided for training/validation must equal the number of answer sets provided.")
}
// Ensure that each training input set contains the correct number of inputs
guard trainInputs.reduce(0, {$0 + $1.count}) == structure.inputs * trainInputs.count else {
throw Error.data("The number of inputs for each training set must equal the network's number of inputs. One or more set contains an incorrect number of inputs.")
}
// Ensure that each training answer set contains the correct number of outputs
guard trainLabels.reduce(0, {$0 + $1.count}) == structure.outputs * trainLabels.count else {
throw Error.data("The number of outputs for each training answer set must equal the network's number of outputs. One or more set contains an incorrect number of outputs.")
}
// Ensure that each validation input set contains the correct number of inputs
guard validationInputs.reduce(0, {$0 + $1.count}) == structure.inputs * validationInputs.count else {
throw Error.data("The number of inputs for each validation set must equal the network's number of inputs. One or more set contains an incorrect number of inputs.")
}
// Ensure that each validation answer set contains the correct number of outputs
guard validationLabels.reduce(0, {$0 + $1.count}) == structure.outputs * validationLabels.count else {
throw Error.data("The number of outputs for each validation answer set must equal the network's number of outputs. One or more set contains an incorrect number of outputs.")
}
// Initialize properties
self.trainInputs = trainInputs
self.trainLabels = trainLabels
self.validationInputs = validationInputs
self.validationLabels = validationLabels
}
}
}
|
apache-2.0
|
d634d46f02ebcf7d0b328254ef9181f3
| 48.893939 | 189 | 0.634983 | 5.137285 | false | false | false | false |
DarrenKong/firefox-ios
|
XCUITests/BaseTestCase.swift
|
2
|
4547
|
/* 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 MappaMundi
import XCTest
class BaseTestCase: XCTestCase {
var navigator: MMNavigator<FxUserState>!
var app: XCUIApplication!
var userState: FxUserState!
override func setUp() {
super.setUp()
continueAfterFailure = false
app = XCUIApplication()
app.terminate()
restart(app, args: [LaunchArguments.ClearProfile, LaunchArguments.SkipIntro, LaunchArguments.SkipWhatsNew])
navigator = createScreenGraph(for: self, with: app).navigator()
userState = navigator.userState
}
override func tearDown() {
XCUIApplication().terminate()
super.tearDown()
}
func restart(_ app: XCUIApplication, args: [String] = []) {
XCUIDevice.shared().press(.home)
var launchArguments = [LaunchArguments.Test]
args.forEach { arg in
launchArguments.append(arg)
}
app.launchArguments = launchArguments
app.activate()
}
//If it is a first run, first run window should be gone
func dismissFirstRunUI() {
let firstRunUI = XCUIApplication().scrollViews["IntroViewController.scrollView"]
if firstRunUI.exists {
firstRunUI.swipeLeft()
XCUIApplication().buttons["Start Browsing"].tap()
}
}
func waitforExistence(_ element: XCUIElement, file: String = #file, line: UInt = #line) {
waitFor(element, with: "exists == true", file: file, line: line)
}
func waitforNoExistence(_ element: XCUIElement, timeoutValue: TimeInterval = 5.0, file: String = #file, line: UInt = #line) {
waitFor(element, with: "exists != true", timeout: timeoutValue, file: file, line: line)
}
func waitForValueContains(_ element: XCUIElement, value: String, file: String = #file, line: UInt = #line) {
waitFor(element, with: "value CONTAINS '\(value)'", file: file, line: line)
}
private func waitFor(_ element: XCUIElement, with predicateString: String, description: String? = nil, timeout: TimeInterval = 5.0, file: String, line: UInt) {
let predicate = NSPredicate(format: predicateString)
let expectation = XCTNSPredicateExpectation(predicate: predicate, object: element)
let result = XCTWaiter().wait(for: [expectation], timeout: timeout)
if result != .completed {
let message = description ?? "Expect predicate \(predicateString) for \(element.description)"
self.recordFailure(withDescription: message, inFile: file, atLine: line, expected: false)
}
}
func loadWebPage(_ url: String, waitForLoadToFinish: Bool = true, file: String = #file, line: UInt = #line) {
let app = XCUIApplication()
UIPasteboard.general.string = url
app.textFields["url"].press(forDuration: 2.0)
app.sheets.element(boundBy: 0).buttons.element(boundBy: 0).tap()
if waitForLoadToFinish {
let finishLoadingTimeout: TimeInterval = 30
let progressIndicator = app.progressIndicators.element(boundBy: 0)
waitFor(progressIndicator,
with: "exists != true",
description: "Problem loading \(url)",
timeout: finishLoadingTimeout,
file: file, line: line)
}
}
func iPad() -> Bool {
if UIDevice.current.userInterfaceIdiom == .pad {
return true
}
return false
}
func waitUntilPageLoad() {
let app = XCUIApplication()
let progressIndicator = app.progressIndicators.element(boundBy: 0)
waitforNoExistence(progressIndicator, timeoutValue: 20.0)
}
}
extension BaseTestCase {
func tabTrayButton(forApp app: XCUIApplication) -> XCUIElement {
return app.buttons["TopTabsViewController.tabsButton"].exists ? app.buttons["TopTabsViewController.tabsButton"] : app.buttons["TabToolbar.tabsButton"]
}
}
extension XCUIElement {
func tap(force: Bool) {
// There appears to be a bug with tapping elements sometimes, despite them being on-screen and tappable, due to hittable being false.
// See: http://stackoverflow.com/a/33534187/1248491
if isHittable {
tap()
} else if force {
coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).tap()
}
}
}
|
mpl-2.0
|
1b4ce0a5616971ec2645c03cf2225058
| 37.533898 | 163 | 0.641742 | 4.668378 | false | true | false | false |
ylankgz/safebook
|
Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/Safebook/AppDelegate.swift
|
100
|
1493
|
//
// AppDelegate.swift
// Keinex
//
// Created by Андрей on 7/15/15.
// Copyright (c) 2016 Keinex. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
let lang = Locale.current.identifier
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UIApplication.shared.statusBarStyle = UIStatusBarStyle.lightContent
if lang == "ru_RU" {
userDefaults.register(defaults: [String(sourceUrl):sourceUrlKeinexRu])
} else {
userDefaults.register(defaults: [String(sourceUrl):sourceUrlKeinexCom])
}
userDefaults.register(defaults: [String(autoDelCache):"none"])
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func deleteCache() {
if userDefaults.string(forKey: autoDelCache as String)! == "onClose" {
SettingsViewController().deleteCache()
}
}
func applicationDidEnterBackground(_ application: UIApplication) {
deleteCache()
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
deleteCache()
}
}
|
mit
|
c3b9da41d10833882e8418976b53ed85
| 26.537037 | 144 | 0.656355 | 5.235915 | false | false | false | false |
wscqs/FMDemo-
|
FMDemo/Classes/Module/Base/View/BaseTableView.swift
|
1
|
2455
|
//
// BaseTableView.swift
// ban
//
// Created by mba on 16/8/30.
// Copyright © 2016年 mbalib. All rights reserved.
//
import UIKit
import DZNEmptyDataSet
class BaseTableView: UITableView {
convenience init(frame: CGRect) {
self.init(frame: frame, style: UITableViewStyle.plain)
}
override init(frame: CGRect, style: UITableViewStyle) {
super.init(frame: frame, style: style)
setDefaultUI()
setUI()
}
required init?(coder aDecoder: NSCoder) {
// fatalError("init(coder:) has not been implemented"
super.init(coder: aDecoder)
setDefaultUI()
setUI()
}
func setDefaultUI() {
// tableHeaderView = UIView()
// tableFooterView = UIView()
emptyDataSetSource = self
emptyDataSetDelegate = self
backgroundColor = UIColor.colorWithHexString(kGlobalBgColor)
estimatedRowHeight = 100
rowHeight = UITableViewAutomaticDimension
}
func setUI() {
}
// func startRequest(isForce: Bool){
//
// }
}
extension BaseTableView: DZNEmptyDataSetSource, DZNEmptyDataSetDelegate{
// func image(forEmptyDataSet scrollView: UIScrollView!) -> UIImage! {
// return #imageLiteral(resourceName: "course_emptyBgimg")
// }
// func title(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
// let attributes = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 15.0), NSForegroundColorAttributeName: UIColor.gray]
// let text = "空数据,重新加载"
// return NSAttributedString(string: text, attributes: attributes)
// }
//
// func description(forEmptyDataSet scrollView: UIScrollView!) -> NSAttributedString! {
// let attributes = [ NSFontAttributeName: UIFont.boldSystemFont(ofSize: 10.0), NSForegroundColorAttributeName: UIColor.gray]
// let text = "空数据,重新加载"
// return NSAttributedString(string: text, attributes: attributes)
// }
// func backgroundColorForEmptyDataSet(scrollView: UIScrollView!) -> UIColor! {
//
// }
func emptyDataSetShouldAllowScroll(_ scrollView: UIScrollView!) -> Bool {
return true
}
func emptyDataSetShouldAllowTouch(_ scrollView: UIScrollView!) -> Bool {
return true
}
func emptyDataSetDidTap(_ scrollView: UIScrollView!) {
}
}
|
apache-2.0
|
6e8eb37a15cf14b01ca11dfbfb90283f
| 26.191011 | 132 | 0.63843 | 4.792079 | false | false | false | false |
ubiregiinc/UbiregiExtensionClient
|
UbiregiExtensionClientTests/UbiregiExtensionServiceTests.swift
|
1
|
8786
|
import XCTest
import Quick
import Nimble
import Swifter
@testable import UbiregiExtensionClient
class UbiregiExtensionServiceTests: QuickSpec {
override func spec() {
var service: UXCUbiregiExtensionService!
var ext: UXCUbiregiExtension!
beforeEach {
service = UXCUbiregiExtensionService()
ext = UXCUbiregiExtension(hostname: "localhost", port: 8080, numericAddress: nil)
}
afterEach {
service = nil
ext = nil
}
describe("addExtension") {
it("adds extension") {
service.addExtension(ext)
expect(service.extensions).to(equal([ext]))
}
it("ignores already added extension") {
service.addExtension(ext)
service.addExtension(ext)
expect(service.extensions).to(equal([ext]))
}
}
describe("removeExtension") {
beforeEach {
service.addExtension(ext)
}
it("removes extension") {
service.removeExtension(ext)
expect(service.extensions).to(beEmpty())
}
it("does nothing if not registered extension is given") {
let e2 = UXCUbiregiExtension(hostname: "localhost", port: 8081, numericAddress: nil)
service.removeExtension(e2)
expect(service.extensions).to(equal([ext]))
}
}
describe("findExtension") {
beforeEach {
service.addExtension(ext)
}
it("finds extension") {
let e = service.findExtensionForHostname("localhost", port: 8080)
expect(e).notTo(beNil())
expect(e).to(equal(ext))
}
it("returns nil if no extension found for hostname and port") {
let e = service.findExtensionForHostname("google.com", port: 80)
expect(e).to(beNil())
}
}
describe("status refresh") {
describe("updateStatus") {
var e1: UXCUbiregiExtension!
var e2: UXCUbiregiExtension!
beforeEach {
// Update connection status every seconds
service.updateStatusInterval = 0.1
// Set non main queue for notification
service.notificationQueue = dispatch_queue_create("com.ubiregi.UbiregiExtensionClient.test", nil)
e1 = UXCUbiregiExtension(hostname: "localhost", port: 8080, numericAddress: nil)
e2 = UXCUbiregiExtension(hostname: "localhost", port: 8081, numericAddress: nil)
}
afterEach {
e1 = nil
e2 = nil
}
it("updates connection status of all extensions") {
expect(service.connectionStatus).to(equal(UXCConnectionStatus.Initialized))
withSwifter(8080) { s1 in
s1["/status"] = returnJSON(["version": "1.2.3"])
withSwifter(8081) { s2 in
s2["/status"] = returnJSON(["version": "2.3.4"])
service.addExtension(e1)
service.addExtension(e2)
waitFor(3) {
service.connectionStatus == .Connected
}
}
}
}
it("posts notification on connection status update") {
service.periodicalUpdateStatusEnabled = false
service.addExtension(e1)
waitFor(2, message: "Wait for connection status got .Error") {
service.connectionStatus == .Error
}
let observer = NotificationTrace()
NSNotificationCenter.defaultCenter().addObserver(observer, selector: "didReceiveNotification:", name: UXCConstants.UbiregiExtensionServiceDidUpdateConnectionStatusNotification, object: service)
withSwifter(8080) { server in
server["/status"] = returnJSON(["version": "1.2.3"])
service.updateStatus()
NSThread.sleepForTimeInterval(1)
let connectionNotifications = observer.notifications.filter {
let newStatus = $0.userInfo!["newConnectionStatus"] as! Int
let oldStatus = $0.userInfo!["oldConnectionStatus"] as! Int
return oldStatus == UXCConnectionStatus.Error.rawValue && newStatus == UXCConnectionStatus.Connected.rawValue
}
expect(connectionNotifications.count).to(equal(1))
}
}
it("makes next retry soon if connection failed") {
service.periodicalUpdateStatusEnabled = false
service.updateStatusInterval = 120
service._connectionStatus = .Connected
// Wait for already running updateStatus to finish
NSThread.sleepForTimeInterval(0.3)
// Use _extensions directly, not addExtension, to skip updateStatus call on extension addition
service._extensions.append(e1)
// Kick connection failure recovery
NSNotificationCenter.defaultCenter().postNotificationName(UbiregiExtensionDidUpdateConnectionStatusNotification, object: e1)
withSwifter(8080) { server in
self.expectationForNotification(UXCConstants.UbiregiExtensionServiceDidUpdateConnectionStatusNotification, object: service) { notification in
service.connectionStatus == UXCConnectionStatus.Connected
}
server["/status"] = returnJSON(["version": "3.4.5"])
self.waitForExpectationsWithTimeout(3.0, handler: nil)
}
}
}
}
describe("barcode scanning") {
var e1: UXCUbiregiExtension!
beforeEach {
// Update connection status every seconds
service.updateStatusInterval = 0.1
// Set non main queue for notification
service.notificationQueue = dispatch_queue_create("com.ubiregi.UbiregiExtensionClient.test", nil)
e1 = UXCUbiregiExtension(hostname: "localhost", port: 8081, numericAddress: nil)
}
afterEach {
e1 = nil
}
let responseWithDevices = { (request: HttpRequest) in
HttpResponse.OK(
.Json(
[
"version": "1.2.3",
"product_version": "October, 2015",
"release": "1-3",
"printers": ["present"],
"barcodes": ["present"]
]
)
)
}
it("posts a notification on barcode scan") {
withSwifter { server in
server["/status"] = responseWithDevices
server["/scan"] = { request in .OK(.Text("123456")) }
self.expectationForNotification(UXCConstants.UbiregiExtensionServiceDidScanBarcodeNotification, object: service, handler: nil)
service.addExtension(e1)
self.waitForExpectationsWithTimeout(1, handler: nil)
}
}
}
}
}
|
mit
|
c0e1f57875cc288d89d37f913bd8c5d0
| 39.680556 | 213 | 0.458684 | 6.320863 | false | true | false | false |
donald-pinckney/Ideal-Gas-Simulator
|
Thermo/RectangularContainer.swift
|
1
|
5073
|
//
// RectangularContainer.swift
// Thermo
//
// Created by Donald Pinckney on 2/13/15.
// Copyright (c) 2015 donald. All rights reserved.
//
import Foundation
let Kb = 1.0
class RectangularContainer: NSObject {
let dimens: [Double]
var N: Int = 200 {
didSet {
setupParticles(oldValue)
}
}
weak var node: RectangularContainerNode? = nil {
didSet {
redraw()
}
}
var particles: [Particle] = []
// MARK: - Output Calculations
var totalKE: Double = 0
// MARK: - Constructors -
init(numDims: Int, squareDimen l: Double) {
dimens = Array(count: numDims, repeatedValue: l)
super.init()
setupParticles(0)
}
convenience override init() {
self.init(numDims: 3, squareDimen: 1)
}
func setupParticles(oldN: Int) {
if N < oldN {
(oldN - N).times {
self.particles.removeLast()
}
} else {
(N - oldN).times {
self.particles.append(Particle(N: self.dimens.count))
}
}
redraw()
}
// Force removes and updates all particle nodes. Expensive!
func redraw() {
node?.updateParticleList()
}
// MARK: - Simulation Update Logic -
func update(dt: Double) {
for p in particles {
// Update positions
moveParticle(p, dt: dt)
// Reflect collisions until fully within container
collideParticleAndWall(p, dt: dt)
}
for p in particles {
// Collide particle with other particles
if !p.didAlreadyCollide {
collideParticleAndOtherParticles(p, dt: dt)
}
}
totalKE = 0
for p in particles {
p.didAlreadyCollide = false
p.redraw()
// Do output calculations
totalKE += p.m * magSquare(p.v) / 2
}
}
func moveParticle(p: Particle, dt: Double) {
p.pos += dt * p.v
}
func collideParticleAndWall(p: Particle, dt: Double) {
while true {
var inside = true
for i in 0..<dimens.count {
let d = dimens[i]
let pos = p.pos.x[i]
if pos >= d/2 || pos <= -d/2 {
p.v.x[i] *= -1
p.pos.x[i] = pos > 0 ? d - pos : -d - pos
inside = false
}
}
if inside {
return
}
}
}
func collideParticleAndOtherParticles(p: Particle, dt: Double) {
// Octrees would be cool, but for now linear search
for op in particles {
if p === op {
continue
}
let D = distSquare(&p.pos, &op.pos)
if D <= pow(p.r + op.r, 2) {
let n = norm(op.pos - p.pos)
let d0 = (D + p.r * p.r - op.r * op.r) / (2*sqrt(D)) // distance from center of circle 0 to intersection plane
let d1 = (D - p.r * p.r + op.r * op.r) / (2*sqrt(D)) // distance from center of circle 1 to intersection plane
let pPastPlane = p.r - d0
let opPastPlane = op.r - d1
let sectionOfPBadDt = pPastPlane / dot(p.v - op.v, n) * dt
let sectionOfPGoodDt = (1 - pPastPlane / dot(p.v - op.v, n)) * dt
p.pos = p.pos - sectionOfPBadDt * p.v
op.pos = op.pos - sectionOfPBadDt * op.v
let momentumBefore = p.m*p.v + op.m*op.v
let normalCollisionVPI = dot(p.v, n)
let normalCollisionVOPI = dot(op.v, n)
// Calculate final collision velocities, need to implement different masses
let normalCollisionVPF = (normalCollisionVPI * (p.m - op.m) + 2*op.m*normalCollisionVOPI) / (p.m + op.m)
let normalCollisionVOPF = (normalCollisionVOPI * (op.m - p.m) + 2*p.m*normalCollisionVPI) / (p.m + op.m)
p.v += (normalCollisionVPF - normalCollisionVPI) * n
op.v += (normalCollisionVOPF - normalCollisionVOPI) * n
let momentumAfter = p.m*p.v + op.m*op.v
p.pos = p.pos + sectionOfPGoodDt * p.v
op.pos = op.pos + sectionOfPGoodDt * op.v
p.didAlreadyCollide = true
op.didAlreadyCollide = true
assert(momentumBefore == momentumAfter, "Momentum has not been conserved.\nP0 = \(momentumBefore)\nPf = \(momentumAfter)\n")
}
}
}
// MARK: - Output Data -
}
|
mit
|
b0929397feeeaca7233160fad10f8235
| 27.183333 | 140 | 0.459491 | 4.045455 | false | false | false | false |
frtlupsvn/Vietnam-To-Go
|
Pods/Former/Former/Commons/Former.swift
|
1
|
42386
|
//
// Former.swift
// Former-Demo
//
// Created by Ryo Aoyama on 7/23/15.
// Copyright © 2015 Ryo Aoyama. All rights reserved.
//
import UIKit
public final class Former: NSObject {
// MARK: Public
/**
InstantiateType is type of instantiate of Cell or HeaderFooterView.
If the cell or HeaderFooterView to instantiate from the nib of mainBudnle , use the case 'Nib(nibName: String)'.
Using the '.NibBundle(nibName: String, bundle: NSBundle)' If also using the custom bundle.
Or if without xib, use '.Class'.
**/
public enum InstantiateType {
case Class
case Nib(nibName: String)
case NibBundle(nibName: String, bundle: NSBundle)
}
/// All SectionFormers. Default is empty.
public private(set) var sectionFormers = [SectionFormer]()
/// Return all RowFormers. Compute each time of called.
public var rowFormers: [RowFormer] {
return sectionFormers.flatMap { $0.rowFormers }
}
/// Number of all sections.
public var numberOfSections: Int {
return sectionFormers.count
}
/// Number of all rows.
public var numberOfRows: Int {
return rowFormers.count
}
/// Returns the first element of all SectionFormers, or `nil` if `self.sectionFormers` is empty.
public var firstSectionFormer: SectionFormer? {
return sectionFormers.first
}
/// Returns the first element of all RowFormers, or `nil` if `self.rowFormers` is empty.
public var firstRowFormer: RowFormer? {
return rowFormers.first
}
/// Returns the last element of all SectionFormers, or `nil` if `self.sectionFormers` is empty.
public var lastSectionFormer: SectionFormer? {
return sectionFormers.last
}
/// Returns the last element of all RowFormers, or `nil` if `self.rowFormers` is empty.
public var lastRowFormer: RowFormer? {
return rowFormers.last
}
public init(tableView: UITableView) {
super.init()
self.tableView = tableView
setupTableView()
}
deinit {
tableView?.delegate = nil
tableView?.dataSource = nil
NSNotificationCenter.defaultCenter().removeObserver(self)
}
public subscript(index: Int) -> SectionFormer {
return sectionFormers[index]
}
public subscript(range: Range<Int>) -> [SectionFormer] {
return Array<SectionFormer>(sectionFormers[range])
}
/// To find RowFormer from indexPath.
@warn_unused_result
public func rowFormer(indexPath: NSIndexPath) -> RowFormer {
return self[indexPath.section][indexPath.row]
}
/// Call when cell has selected.
public func onCellSelected(handler: (NSIndexPath -> Void)) -> Self {
onCellSelected = handler
return self
}
/// Call when tableView has scrolled.
public func onScroll(handler: ((scrollView: UIScrollView) -> Void)) -> Self {
onScroll = handler
return self
}
/// Call when tableView had begin dragging.
public func onBeginDragging(handler: (UIScrollView -> Void)) -> Self {
onBeginDragging = handler
return self
}
/// Call just before cell is deselect.
public func willDeselectCell(handler: (NSIndexPath -> NSIndexPath?)) -> Self {
willDeselectCell = handler
return self
}
/// Call just before cell is display.
public func willDisplayCell(handler: (NSIndexPath -> Void)) -> Self {
willDisplayCell = handler
return self
}
/// Call just before header is display.
public func willDisplayHeader(handler: (/*section:*/Int -> Void)) -> Self {
willDisplayHeader = handler
return self
}
/// Call just before cell is display.
public func willDisplayFooter(handler: (/*section:*/Int -> Void)) -> Self {
willDisplayFooter = handler
return self
}
/// Call when cell has deselect.
public func didDeselectCell(handler: (NSIndexPath -> Void)) -> Self {
didDeselectCell = handler
return self
}
/// Call when cell has Displayed.
public func didEndDisplayingCell(handler: (NSIndexPath -> Void)) -> Self {
didEndDisplayingCell = handler
return self
}
/// Call when header has displayed.
public func didEndDisplayingHeader(handler: (/*section:*/Int -> Void)) -> Self {
didEndDisplayingHeader = handler
return self
}
/// Call when footer has displayed.
public func didEndDisplayingFooter(handler: (/*section:*/Int -> Void)) -> Self {
didEndDisplayingFooter = handler
return self
}
/// Call when cell has highlighted.
public func didHighlightCell(handler: (NSIndexPath -> Void)) -> Self {
didHighlightCell = handler
return self
}
/// Call when cell has unhighlighted.
public func didUnHighlightCell(handler: (NSIndexPath -> Void)) -> Self {
didUnHighlightCell = handler
return self
}
/// 'true' iff can edit previous row.
@warn_unused_result
public func canBecomeEditingPrevious() -> Bool {
var section = selectedIndexPath?.section ?? 0
var row = (selectedIndexPath != nil) ? selectedIndexPath!.row - 1 : 0
guard section < sectionFormers.count else { return false }
if row < 0 {
section--
guard section >= 0 else { return false }
row = self[section].rowFormers.count - 1
}
guard row < self[section].rowFormers.count else { return false }
return self[section][row].canBecomeEditing
}
/// 'true' iff can edit next row.
@warn_unused_result
public func canBecomeEditingNext() -> Bool {
var section = selectedIndexPath?.section ?? 0
var row = (selectedIndexPath != nil) ? selectedIndexPath!.row + 1 : 0
guard section < sectionFormers.count else { return false }
if row >= self[section].rowFormers.count {
guard ++section < sectionFormers.count else { return false }
row = 0
}
guard row < self[section].rowFormers.count else { return false }
return self[section][row].canBecomeEditing
}
/// Edit previous row iff it can.
public func becomeEditingPrevious() -> Self {
if let tableView = tableView where canBecomeEditingPrevious() {
var section = selectedIndexPath?.section ?? 0
var row = (selectedIndexPath != nil) ? selectedIndexPath!.row - 1 : 0
guard section < sectionFormers.count else { return self }
if row < 0 {
section--
guard section >= 0 else { return self }
row = self[section].rowFormers.count - 1
}
guard row < self[section].rowFormers.count else { return self }
let indexPath = NSIndexPath(forRow: row, inSection: section)
select(indexPath: indexPath, animated: false)
let scrollIndexPath = (rowFormer(indexPath) is InlineForm) ?
NSIndexPath(forRow: row + 1, inSection: section) : indexPath
tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: .None, animated: false)
}
return self
}
/// Edit next row iff it can.
public func becomeEditingNext() -> Self {
if let tableView = tableView where canBecomeEditingNext() {
var section = selectedIndexPath?.section ?? 0
var row = (selectedIndexPath != nil) ? selectedIndexPath!.row + 1 : 0
guard section < sectionFormers.count else { return self }
if row >= self[section].rowFormers.count {
guard ++section < sectionFormers.count else { return self }
row = 0
}
guard row < self[section].rowFormers.count else { return self }
let indexPath = NSIndexPath(forRow: row, inSection: section)
select(indexPath: indexPath, animated: false)
let scrollIndexPath = (rowFormer(indexPath) is InlineForm) ?
NSIndexPath(forRow: row + 1, inSection: section) : indexPath
tableView.scrollToRowAtIndexPath(scrollIndexPath, atScrollPosition: .None, animated: false)
}
return self
}
/// To end editing of tableView.
public func endEditing() -> Self {
tableView?.endEditing(true)
if let selectorRowFormer = selectorRowFormer as? SelectorForm {
selectorRowFormer.editingDidEnd()
self.selectorRowFormer = nil
}
return self
}
/// To select row from indexPath.
public func select(indexPath indexPath: NSIndexPath, animated: Bool, scrollPosition: UITableViewScrollPosition = .None) -> Self {
if let tableView = tableView {
tableView.selectRowAtIndexPath(indexPath, animated: animated, scrollPosition: scrollPosition)
self.tableView(tableView, willSelectRowAtIndexPath: indexPath)
self.tableView(tableView, didSelectRowAtIndexPath: indexPath)
}
return self
}
/// To select row from instance of RowFormer.
public func select(rowFormer rowFormer: RowFormer, animated: Bool, scrollPosition: UITableViewScrollPosition = .None) -> Self {
for (section, sectionFormer) in sectionFormers.enumerate() {
if let row = sectionFormer.rowFormers.indexOf({ $0 === rowFormer }) {
return select(indexPath: NSIndexPath(forRow: row, inSection: section), animated: animated, scrollPosition: scrollPosition)
}
}
return self
}
/// To deselect current selecting cell.
public func deselect(animated: Bool) -> Self {
if let indexPath = selectedIndexPath {
tableView?.deselectRowAtIndexPath(indexPath, animated: animated)
}
return self
}
/// Reload All cells.
public func reload() -> Self {
tableView?.reloadData()
removeCurrentInlineRowUpdate()
return self
}
/// Reload sections from section indexSet.
public func reload(sections sections: NSIndexSet, rowAnimation: UITableViewRowAnimation = .None) -> Self {
tableView?.reloadSections(sections, withRowAnimation: rowAnimation)
return self
}
/// Reload sections from instance of SectionFormer.
public func reload(sectionFormer sectionFormer: SectionFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
guard let section = sectionFormers.indexOf({ $0 === sectionFormer }) else { return self }
return reload(sections: NSIndexSet(index: section), rowAnimation: rowAnimation)
}
/// Reload rows from indesPaths.
public func reload(indexPaths indexPaths: [NSIndexPath], rowAnimation: UITableViewRowAnimation = .None) -> Self {
tableView?.reloadRowsAtIndexPaths(indexPaths, withRowAnimation: rowAnimation)
return self
}
/// Reload rows from instance of RowFormer.
public func reload(rowFormer rowFormer: RowFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
for (section, sectionFormer) in sectionFormers.enumerate() {
if let row = sectionFormer.rowFormers.indexOf({ $0 === rowFormer}) {
return reload(indexPaths: [NSIndexPath(forRow: row, inSection: section)], rowAnimation: rowAnimation)
}
}
return self
}
/// Append SectionFormer to last index.
public func append(sectionFormer sectionFormer: SectionFormer...) -> Self {
return add(sectionFormers: sectionFormer)
}
/// Add SectionFormers to last index.
public func add(sectionFormers sectionFormers: [SectionFormer]) -> Self {
self.sectionFormers += sectionFormers
return self
}
/// Insert SectionFormer to index of section with NO updates.
public func insert(sectionFormer sectionFormer: SectionFormer..., toSection: Int) -> Self {
return insert(sectionFormers: sectionFormer, toSection: toSection)
}
/// Insert SectionFormers to index of section with NO updates.
public func insert(sectionFormers sectionFormers: [SectionFormer], toSection: Int) -> Self {
let count = self.sectionFormers.count
if count == 0 || toSection >= count {
add(sectionFormers: sectionFormers)
return self
} else if toSection >= count {
self.sectionFormers.insertContentsOf(sectionFormers, at: 0)
return self
}
self.sectionFormers.insertContentsOf(sectionFormers, at: toSection)
return self
}
/// Insert SectionFormer to above other SectionFormer with NO updates.
public func insert(sectionFormer sectionFormer: SectionFormer..., above: SectionFormer) -> Self {
return insert(sectionFormers: sectionFormer, above: above)
}
/// Insert SectionFormers to above other SectionFormer with NO updates.
public func insert(sectionFormers sectionFormers: [SectionFormer], above: SectionFormer) -> Self {
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormer === above {
return insert(sectionFormers: sectionFormers, toSection: section - 1)
}
}
return add(sectionFormers: sectionFormers)
}
/// Insert SectionFormer to below other SectionFormer with NO updates.
public func insert(sectionFormer sectionFormer: SectionFormer..., below: SectionFormer) -> Self {
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormer === below {
return insert(sectionFormers: sectionFormers, toSection: section + 1)
}
}
add(sectionFormers: sectionFormers)
return insert(sectionFormers: sectionFormer, below: below)
}
/// Insert SectionFormers to below other SectionFormer with NO updates.
public func insert(sectionFormers sectionFormers: [SectionFormer], below: SectionFormer) -> Self {
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormer === below {
return insert(sectionFormers: sectionFormers, toSection: section + 1)
}
}
return add(sectionFormers: sectionFormers)
}
/// Insert SectionFormer to index of section with animated updates.
public func insertUpdate(sectionFormer sectionFormer: SectionFormer..., toSection: Int, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(sectionFormers: sectionFormer, toSection: toSection, rowAnimation: rowAnimation)
}
/// Insert SectionFormers to index of section with animated updates.
public func insertUpdate(sectionFormers sectionFormers: [SectionFormer], toSection: Int, rowAnimation: UITableViewRowAnimation = .None) -> Self {
guard !sectionFormers.isEmpty else { return self }
removeCurrentInlineRowUpdate()
tableView?.beginUpdates()
insert(sectionFormers: sectionFormers, toSection: toSection)
tableView?.insertSections(NSIndexSet(index: toSection), withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
/// Insert SectionFormer to above other SectionFormer with animated updates.
public func insertUpdate(sectionFormer sectionFormer: SectionFormer..., above: SectionFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(sectionFormers: sectionFormer, above: above, rowAnimation: rowAnimation)
}
/// Insert SectionFormers to above other SectionFormer with animated updates.
public func insertUpdate(sectionFormers sectionFormers: [SectionFormer], above: SectionFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormer === above {
let indexSet = NSIndexSet(indexesInRange: NSMakeRange(section, sectionFormers.count))
tableView?.beginUpdates()
insert(sectionFormers: sectionFormers, toSection: section)
tableView?.insertSections(indexSet, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
}
return self
}
/// Insert SectionFormer to below other SectionFormer with animated updates.
public func insertUpdate(sectionFormer sectionFormer: SectionFormer..., below: SectionFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(sectionFormers: sectionFormer, below: below, rowAnimation: rowAnimation)
}
/// Insert SectionFormers to below other SectionFormer with animated updates.
public func insertUpdate(sectionFormers sectionFormers: [SectionFormer], below: SectionFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormer === below {
let indexSet = NSIndexSet(indexesInRange: NSMakeRange(section + 1, sectionFormers.count))
tableView?.beginUpdates()
insert(sectionFormers: sectionFormers, toSection: section + 1)
tableView?.insertSections(indexSet, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
}
return self
}
/// Insert RowFormer with NO updates.
public func insert(rowFormer rowFormer: RowFormer..., toIndexPath: NSIndexPath) -> Self {
return insert(rowFormers: rowFormer, toIndexPath: toIndexPath)
}
/// Insert RowFormers with NO updates.
public func insert(rowFormers rowFormers: [RowFormer], toIndexPath: NSIndexPath) -> Self {
self[toIndexPath.section].insert(rowFormers: rowFormers, toIndex: toIndexPath.row)
return self
}
/// Insert RowFormer to above other RowFormer with NO updates.
public func insert(rowFormer rowFormer: RowFormer..., above: RowFormer) -> Self {
return insert(rowFormers: rowFormer, above: above)
}
/// Insert RowFormers to above other RowFormer with NO updates.
public func insert(rowFormers rowFormers: [RowFormer], above: RowFormer) -> Self {
guard !rowFormers.isEmpty else { return self }
for sectionFormer in self.sectionFormers {
for (row, rowFormer) in sectionFormer.rowFormers.enumerate() {
if rowFormer === above {
sectionFormer.insert(rowFormers: rowFormers, toIndex: row)
return self
}
}
}
return self
}
/// Insert RowFormers to below other RowFormer with NO updates.
public func insert(rowFormer rowFormer: RowFormer..., below: RowFormer) -> Self {
return insert(rowFormers: rowFormer, below: below)
}
/// Insert RowFormers to below other RowFormer with NO updates.
public func insert(rowFormers rowFormers: [RowFormer], below: RowFormer) -> Self {
guard !rowFormers.isEmpty else { return self }
for sectionFormer in self.sectionFormers {
for (row, rowFormer) in sectionFormer.rowFormers.enumerate() {
if rowFormer === below {
sectionFormer.insert(rowFormers: rowFormers, toIndex: row + 1)
return self
}
}
}
return self
}
/// Insert RowFormer with animated updates.
public func insertUpdate(rowFormer rowFormer: RowFormer..., toIndexPath: NSIndexPath, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(rowFormers: rowFormer, toIndexPath: toIndexPath, rowAnimation: rowAnimation)
}
/// Insert RowFormers with animated updates.
public func insertUpdate(rowFormers rowFormers: [RowFormer], toIndexPath: NSIndexPath, rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
guard !rowFormers.isEmpty else { return self }
tableView?.beginUpdates()
insert(rowFormers: rowFormers, toIndexPath: toIndexPath)
let insertIndexPaths = (0..<rowFormers.count).map {
NSIndexPath(forRow: toIndexPath.row + $0, inSection: toIndexPath.section)
}
tableView?.insertRowsAtIndexPaths(insertIndexPaths, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
/// Insert RowFormer to above other RowFormer with animated updates.
public func insertUpdate(rowFormer rowFormer: RowFormer..., above: RowFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(rowFormers: rowFormer, above: above, rowAnimation: rowAnimation)
}
/// Insert RowFormers to above other RowFormer with animated updates.
public func insertUpdate(rowFormers rowFormers: [RowFormer], above: RowFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
for (section, sectionFormer) in self.sectionFormers.enumerate() {
for (row, rowFormer) in sectionFormer.rowFormers.enumerate() {
if rowFormer === above {
let indexPaths = (row..<row + rowFormers.count).map {
NSIndexPath(forRow: $0, inSection: section)
}
tableView?.beginUpdates()
sectionFormer.insert(rowFormers: rowFormers, toIndex: row)
tableView?.insertRowsAtIndexPaths(indexPaths, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
}
}
return self
}
/// Insert RowFormer to below other RowFormer with animated updates.
public func insertUpdate(rowFormer rowFormer: RowFormer..., below: RowFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
return insertUpdate(rowFormers: rowFormer, below: below, rowAnimation: rowAnimation)
}
/// Insert RowFormers to below other RowFormer with animated updates.
public func insertUpdate(rowFormers rowFormers: [RowFormer], below: RowFormer, rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
for (section, sectionFormer) in self.sectionFormers.enumerate() {
for (row, rowFormer) in sectionFormer.rowFormers.enumerate() {
if rowFormer === below {
let indexPaths = (row + 1..<row + 1 + rowFormers.count).map {
NSIndexPath(forRow: $0, inSection: section)
}
tableView?.beginUpdates()
sectionFormer.insert(rowFormers: rowFormers, toIndex: row + 1)
tableView?.insertRowsAtIndexPaths(indexPaths, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
}
}
return self
}
/// Remove All SectionFormers with NO updates.
public func removeAll() -> Self {
sectionFormers = []
return self
}
/// Remove All SectionFormers with animated updates.
public func removeAllUpdate(rowAnimation: UITableViewRowAnimation = .None) -> Self {
let indexSet = NSIndexSet(indexesInRange: NSMakeRange(0, sectionFormers.count))
sectionFormers = []
guard indexSet.count > 0 else { return self }
tableView?.beginUpdates()
tableView?.deleteSections(indexSet, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
/// Remove SectionFormers from section index with NO updates.
public func remove(section section: Int) -> Self {
sectionFormers.removeAtIndex(section)
return self
}
/// Remove SectionFormers from instances of SectionFormer with NO updates.
public func remove(sectionFormer sectionFormer: SectionFormer...) -> Self {
return remove(sectionFormers: sectionFormer)
}
/// Remove SectionFormers from instances of SectionFormer with NO updates.
public func remove(sectionFormers sectionFormers: [SectionFormer]) -> Self {
removeSectionFormers(sectionFormers)
return self
}
/// Remove SectionFormers from instances of SectionFormer with animated updates.
public func removeUpdate(sectionFormer sectionFormer: SectionFormer..., rowAnimation: UITableViewRowAnimation = .None) -> Self {
return removeUpdate(sectionFormers: sectionFormer, rowAnimation: rowAnimation)
}
/// Remove SectionFormers from instances of SectionFormer with animated updates.
public func removeUpdate(sectionFormers sectionFormers: [SectionFormer], rowAnimation: UITableViewRowAnimation = .None) -> Self {
guard !sectionFormers.isEmpty else { return self }
let indexSet = removeSectionFormers(sectionFormers)
guard indexSet.count > 0 else { return self }
tableView?.beginUpdates()
tableView?.deleteSections(indexSet, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
/// Remove RowFormer with NO updates.
public func remove(rowFormer rowFormer: RowFormer...) -> Self {
return remove(rowFormers: rowFormer)
}
/// Remove RowFormers with NO updates.
public func remove(rowFormers rowFormers: [RowFormer]) -> Self {
removeRowFormers(rowFormers)
return self
}
/// Remove RowFormers with animated updates.
public func removeUpdate(rowFormer rowFormer: RowFormer..., rowAnimation: UITableViewRowAnimation = .None) -> Self {
return removeUpdate(rowFormers: rowFormer, rowAnimation: rowAnimation)
}
/// Remove RowFormers with animated updates.
public func removeUpdate(rowFormers rowFormers: [RowFormer], rowAnimation: UITableViewRowAnimation = .None) -> Self {
removeCurrentInlineRowUpdate()
guard !rowFormers.isEmpty else { return self }
tableView?.beginUpdates()
let oldIndexPaths = removeRowFormers(rowFormers)
tableView?.deleteRowsAtIndexPaths(oldIndexPaths, withRowAnimation: rowAnimation)
tableView?.endUpdates()
return self
}
// MARK: Private
private var onCellSelected: ((indexPath: NSIndexPath) -> Void)?
private var onScroll: ((scrollView: UIScrollView) -> Void)?
private var onBeginDragging: ((scrollView: UIScrollView) -> Void)?
private var willDeselectCell: ((indexPath: NSIndexPath) -> NSIndexPath?)?
private var willDisplayCell: ((indexPath: NSIndexPath) -> Void)?
private var willDisplayHeader: ((section: Int) -> Void)?
private var willDisplayFooter: ((section: Int) -> Void)?
private var didDeselectCell: ((indexPath: NSIndexPath) -> Void)?
private var didEndDisplayingCell: ((indexPath: NSIndexPath) -> Void)?
private var didEndDisplayingHeader: ((section: Int) -> Void)?
private var didEndDisplayingFooter: ((section: Int) -> Void)?
private var didHighlightCell: ((indexPath: NSIndexPath) -> Void)?
private var didUnHighlightCell: ((indexPath: NSIndexPath) -> Void)?
private weak var tableView: UITableView?
private weak var inlineRowFormer: RowFormer?
private weak var selectorRowFormer: RowFormer?
private var selectedIndexPath: NSIndexPath?
private var oldBottomContentInset: CGFloat?
private func setupTableView() {
tableView?.delegate = self
tableView?.dataSource = self
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillAppear:", name: UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardWillDisappear:", name: UIKeyboardWillHideNotification, object: nil)
}
private func removeCurrentInlineRow() -> NSIndexPath? {
var indexPath: NSIndexPath? = nil
if let oldInlineRowFormer = (inlineRowFormer as? InlineForm)?.inlineRowFormer,
let removedIndexPath = removeRowFormers([oldInlineRowFormer]).first {
indexPath = removedIndexPath
(inlineRowFormer as? InlineForm)?.editingDidEnd()
inlineRowFormer = nil
}
return indexPath
}
private func removeCurrentInlineRowUpdate() {
if let removedIndexPath = removeCurrentInlineRow() {
tableView?.beginUpdates()
tableView?.deleteRowsAtIndexPaths([removedIndexPath], withRowAnimation: .Middle)
tableView?.endUpdates()
}
}
private func removeSectionFormers(sectionFormers: [SectionFormer]) -> NSIndexSet {
var removedCount = 0
let indexSet = NSMutableIndexSet()
for (section, sectionFormer) in self.sectionFormers.enumerate() {
if sectionFormers.contains({ $0 === sectionFormer}) {
indexSet.addIndex(section)
remove(section: section)
if ++removedCount >= sectionFormers.count {
return indexSet
}
}
}
return indexSet
}
private func removeRowFormers(rowFormers: [RowFormer]) -> [NSIndexPath] {
var removedCount = 0
var removeIndexPaths = [NSIndexPath]()
for (section, sectionFormer) in sectionFormers.enumerate() {
for (row, rowFormer) in sectionFormer.rowFormers.enumerate() {
if rowFormers.contains({ $0 === rowFormer }) {
removeIndexPaths.append(NSIndexPath(forRow: row, inSection: section))
sectionFormer.remove(rowFormers: [rowFormer])
if let oldInlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer {
removeIndexPaths.append(NSIndexPath(forRow: row + 1, inSection: section))
removeRowFormers([oldInlineRowFormer])
(inlineRowFormer as? InlineForm)?.editingDidEnd()
inlineRowFormer = nil
}
if ++removedCount >= rowFormers.count {
return removeIndexPaths
}
}
}
}
return removeIndexPaths
}
private func findFirstResponder(view: UIView?) -> UIView? {
if view?.isFirstResponder() ?? false {
return view
}
for subView in view?.subviews ?? [] {
if let firstResponder = findFirstResponder(subView) {
return firstResponder
}
}
return nil
}
private func findCellWithSubView(view: UIView?) -> UITableViewCell? {
if let view = view {
if let cell = view as? UITableViewCell {
return cell
}
return findCellWithSubView(view.superview)
}
return nil
}
private dynamic func keyboardWillAppear(notification: NSNotification) {
guard let keyboardInfo = notification.userInfo else { return }
if case let (tableView?, cell?) = (tableView, findCellWithSubView(findFirstResponder(tableView))) {
let frame = keyboardInfo[UIKeyboardFrameEndUserInfoKey]!.CGRectValue
let keyboardFrame = tableView.window!.convertRect(frame, toView: tableView.superview!)
let bottomInset = CGRectGetMinY(tableView.frame) + CGRectGetHeight(tableView.frame) - CGRectGetMinY(keyboardFrame)
guard bottomInset > 0 else { return }
if oldBottomContentInset == nil {
oldBottomContentInset = tableView.contentInset.bottom
}
let duration = keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue!
let curve = keyboardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue
guard let indexPath = tableView.indexPathForCell(cell) else { return }
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(duration)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
tableView.contentInset.bottom = bottomInset
tableView.scrollIndicatorInsets.bottom = bottomInset
tableView.scrollToRowAtIndexPath(indexPath, atScrollPosition: .None, animated: false)
UIView.commitAnimations()
}
}
private dynamic func keyboardWillDisappear(notification: NSNotification) {
guard let keyboardInfo = notification.userInfo else { return }
if case let (tableView?, inset?) = (tableView, oldBottomContentInset) {
let duration = keyboardInfo[UIKeyboardAnimationDurationUserInfoKey]!.doubleValue!
let curve = keyboardInfo[UIKeyboardAnimationCurveUserInfoKey]!.integerValue
UIView.beginAnimations(nil, context: nil)
UIView.setAnimationDuration(duration)
UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
tableView.contentInset.bottom = inset
tableView.scrollIndicatorInsets.bottom = inset
UIView.commitAnimations()
oldBottomContentInset = nil
}
}
}
extension Former: UITableViewDelegate, UITableViewDataSource {
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
endEditing()
onBeginDragging?(scrollView: scrollView)
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
onScroll?(scrollView: scrollView)
}
public func tableView(tableView: UITableView, willDeselectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
return willDeselectCell?(indexPath: indexPath) ?? indexPath
}
public func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
willDisplayCell?(indexPath: indexPath)
}
public func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
willDisplayHeader?(section: section)
}
public func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
willDisplayFooter?(section: section)
}
public func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
didDeselectCell?(indexPath: indexPath)
}
public func tableView(tableView: UITableView, didEndDisplayingCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
didEndDisplayingCell?(indexPath: indexPath)
}
public func tableView(tableView: UITableView, didEndDisplayingHeaderView view: UIView, forSection section: Int) {
didEndDisplayingHeader?(section: section)
}
public func tableView(tableView: UITableView, didEndDisplayingFooterView view: UIView, forSection section: Int) {
didEndDisplayingFooter?(section: section)
}
public func tableView(tableView: UITableView, didHighlightRowAtIndexPath indexPath: NSIndexPath) {
didHighlightCell?(indexPath: indexPath)
}
public func tableView(tableView: UITableView, didUnhighlightRowAtIndexPath indexPath: NSIndexPath) {
didUnHighlightCell?(indexPath: indexPath)
}
public func tableView(tableView: UITableView, willSelectRowAtIndexPath indexPath: NSIndexPath) -> NSIndexPath? {
endEditing()
deselect(false)
selectedIndexPath = indexPath
return indexPath
}
public func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let rowFormer = self.rowFormer(indexPath)
guard rowFormer.enabled else { return }
rowFormer.cellSelected(indexPath)
onCellSelected?(indexPath: indexPath)
// InlineRow
if let oldInlineRowFormer = (inlineRowFormer as? InlineForm)?.inlineRowFormer {
if let currentInlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer
where rowFormer !== inlineRowFormer {
self.tableView?.beginUpdates()
if let removedIndexPath = removeRowFormers([oldInlineRowFormer]).first {
let insertIndexPath =
(removedIndexPath.section == indexPath.section && removedIndexPath.row < indexPath.row)
? indexPath : NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)
insert(rowFormers: [currentInlineRowFormer], toIndexPath: insertIndexPath)
self.tableView?.deleteRowsAtIndexPaths([removedIndexPath], withRowAnimation: .Middle)
self.tableView?.insertRowsAtIndexPaths([insertIndexPath], withRowAnimation: .Middle)
}
self.tableView?.endUpdates()
(inlineRowFormer as? InlineForm)?.editingDidEnd()
(rowFormer as? InlineForm)?.editingDidBegin()
inlineRowFormer = rowFormer
} else {
removeCurrentInlineRowUpdate()
}
} else if let inlineRowFormer = (rowFormer as? InlineForm)?.inlineRowFormer {
let inlineIndexPath = NSIndexPath(forRow: indexPath.row + 1, inSection: indexPath.section)
insertUpdate(rowFormers: [inlineRowFormer], toIndexPath: inlineIndexPath, rowAnimation: .Middle)
(rowFormer as? InlineForm)?.editingDidBegin()
self.inlineRowFormer = rowFormer
}
// SelectorRow
if let selectorRow = rowFormer as? SelectorForm {
if let selectorRowFormer = selectorRowFormer {
if !(selectorRowFormer === rowFormer) {
selectorRow.editingDidBegin()
}
} else {
selectorRow.editingDidBegin()
}
selectorRowFormer = rowFormer
rowFormer.cellInstance.becomeFirstResponder()
}
}
public func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
public func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return false
}
// for Cell
public func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return numberOfSections
}
public func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self[section].numberOfRows
}
public func tableView(tableView: UITableView, estimatedHeightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let rowFormer = self.rowFormer(indexPath)
if let dynamicRowHeight = rowFormer.dynamicRowHeight {
rowFormer.rowHeight = dynamicRowHeight(tableView, indexPath)
}
return rowFormer.rowHeight
}
public func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
let rowFormer = self.rowFormer(indexPath)
if let dynamicRowHeight = rowFormer.dynamicRowHeight {
rowFormer.rowHeight = dynamicRowHeight(tableView, indexPath)
}
return rowFormer.rowHeight
}
public func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let rowFormer = self.rowFormer(indexPath)
if rowFormer.former == nil { rowFormer.former = self }
rowFormer.update()
return rowFormer.cellInstance
}
// for HeaderFooterView
public func tableView(tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
let headerViewFormer = self[section].headerViewFormer
if let dynamicViewHeight = headerViewFormer?.dynamicViewHeight {
headerViewFormer?.viewHeight = dynamicViewHeight(tableView, section)
}
return headerViewFormer?.viewHeight ?? 0
}
public func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
let headerViewFormer = self[section].headerViewFormer
if let dynamicViewHeight = headerViewFormer?.dynamicViewHeight {
headerViewFormer?.viewHeight = dynamicViewHeight(tableView, section)
}
return headerViewFormer?.viewHeight ?? 0
}
public func tableView(tableView: UITableView, estimatedHeightForFooterInSection section: Int) -> CGFloat {
let footerViewFormer = self[section].footerViewFormer
if let dynamicViewHeight = footerViewFormer?.dynamicViewHeight {
footerViewFormer?.viewHeight = dynamicViewHeight(tableView, section)
}
return footerViewFormer?.viewHeight ?? 0
}
public func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
let footerViewFormer = self[section].footerViewFormer
if let dynamicViewHeight = footerViewFormer?.dynamicViewHeight {
footerViewFormer?.viewHeight = dynamicViewHeight(tableView, section)
}
return footerViewFormer?.viewHeight ?? 0
}
public func tableView(tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
guard let viewFormer = self[section].headerViewFormer else { return nil }
viewFormer.update()
return viewFormer.viewInstance
}
public func tableView(tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
guard let viewFormer = self[section].footerViewFormer else { return nil }
viewFormer.update()
return viewFormer.viewInstance
}
}
|
mit
|
a24cbc9d4c3fcf7a5295f297378b272d
| 42.031472 | 155 | 0.649381 | 5.667201 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.