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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
stuartjmoore/D-D | D&D/Models/Abilities.swift | 1 | 1299 | //
// Abilities.swift
// D&D
//
// Created by Moore, Stuart on 2/13/15.
// Copyright (c) 2015 Stuart Moore. All rights reserved.
//
struct Abilities {
enum Name {
case Strength, Dexterity, Constitution, Intelligence, Wisdom, Charisma
}
struct Ability {
unowned let character: Player
var score: Int = 0
var proficient: Bool = false
var modifier: Int { return rounddown(score / 2) - 5 }
var savingThrow: Int { return modifier + (proficient ? character.bonus : 0) }
init(character: Player) {
self.character = character
}
}
subscript(index: Name) -> Ability {
get {
return _abilities[index]!
} set (newAbility) {
_abilities[index] = newAbility
}
}
private var _abilities: [Name: Ability]
init(character: Player) {
_abilities = [
.Strength: Ability(character: character),
.Dexterity: Ability(character: character),
.Constitution: Ability(character: character),
.Intelligence: Ability(character: character),
.Wisdom: Ability(character: character),
.Charisma: Ability(character: character)
]
}
}
| unlicense | 261376896a17f8fb5092c75b2c588ae7 | 24.98 | 85 | 0.554273 | 4.301325 | false | false | false | false |
Harekaze/Harekaze-iOS | Harekaze/Models/Program.swift | 1 | 6371 | /**
*
* Program.swift
* Harekaze
* Created by Yuki MIZUNO on 2016/07/10.
*
* Copyright (c) 2016-2018, Yuki MIZUNO
* 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 RealmSwift
import ObjectMapper
import APIKit
import CoreSpotlight
import MobileCoreServices
import Crashlytics
class RealmString: Object {
@objc dynamic var stringValue = ""
}
protocol ProgramDuration {
var startTime: Date { get set }
var endTime: Date { get set }
var duration: Double { get }
}
protocol ProgramKey {
var id: String { get set }
}
class DummyProgram: NSObject, ProgramDuration {
var startTime: Date
var endTime: Date
var duration: Double {
return endTime.timeIntervalSince(startTime)
}
// MARK: - Class initialization
init(startTime: Date, endTime: Date) {
self.startTime = startTime
self.endTime = endTime
}
}
class Program: Object, Mappable, ProgramKey, ProgramDuration {
// MARK: - Managed instance fileds
@objc dynamic var id: String = ""
@objc dynamic var title: String = ""
@objc dynamic var fullTitle: String = ""
@objc dynamic var subTitle: String = ""
@objc dynamic var detail: String = ""
let _attributes = List<RealmString>() // swiftlint:disable:this variable_name
@objc dynamic var genre: String = ""
@objc dynamic var channel: Channel?
@objc dynamic var episode: Int = 0
@objc dynamic var startTime: Date = Date()
@objc dynamic var endTime: Date = Date()
@objc dynamic var duration: Double = 0.0
// MARK: - Unmanaged instance fileds
var attributes: [String] {
get {
return _attributes.map { $0.stringValue }
}
set {
_attributes.removeAll()
newValue.forEach { _attributes.append(RealmString(value: [$0])) }
}
}
let attributeMap: [String: String] = ["ๆ": "๐", "ๅญ": "๐", "ๅ": "๐", "ใ": "๐", "ไบ": "๐", "ๅค": "๐", "่งฃ": "๐", "ๅคฉ": "๐", "ไบค": "๐",
"ๆ ": "๐", "็ก": "๐", "ๆ": "๐", "ๅ": "๐", "ๅพ": "๐", "ๅ": "๐", "ๆฐ": "๐", "ๅ": "๐ ", "็ต": "๐ก",
"็": "๐ข", "่ฒฉ": "๐ฃ", "ๅฃฐ": "๐ค", "ๅน": "๐ฅ", "ๆผ": "๐ฆ", "ๆ": "๐ง", "ๆ": "๐จ", "ไธ": "๐ฉ", "ไธ": "๐ช",
"้": "๐ซ", "ๅทฆ": "๐ฌ", "ไธญ": "๐ญ", "ๅณ": "๐ฎ", "ๆ": "๐ฏ", "่ตฐ": "๐ฐ", "ๆ": "๐ฑ"]
var attributedAttributes: [String] {
return attributes.map {attributeMap[$0] ?? $0}
}
var attributedFullTitle: String {
var newTitle = fullTitle
for index in newTitle.indices.dropLast().dropFirst().reversed() {
if let attribute = attributeMap[String(fullTitle[index])] {
let before = fullTitle.index(before: index)
let after = fullTitle.index(after: index)
if fullTitle[before] == "[" && fullTitle[after] == "]" {
newTitle.replaceSubrange(before...after, with: attribute)
}
}
}
return newTitle
}
// MARK: Spotlight Search item
var attributeSet: CSSearchableItemAttributeSet {
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeMovie as String)
attributeSet.title = self.title
attributeSet.keywords = [self.title]
attributeSet.contentDescription = self.detail
attributeSet.addedDate = self.endTime
attributeSet.duration = self.duration as NSNumber?
attributeSet.metadataModificationDate = self.startTime
attributeSet.contentCreationDate = self.startTime
attributeSet.contentModificationDate = self.startTime
attributeSet.genre = self.genre
attributeSet.information = self.detail
attributeSet.projects = [self.title]
attributeSet.publishers = [self.channel!.name] // ?
attributeSet.organizations = [self.channel!.name]
return attributeSet
}
override static func ignoredProperties() -> [String] {
return ["attributes", "attributeSet", "attributedAttributes", "attributedFullTitle", "attributeMap"]
}
// MARK: - Primary key definition
override static func primaryKey() -> String? {
return "id"
}
// MARK: - Class initialization
required convenience init?(map: Map) {
self.init()
mapping(map: map)
}
// MARK: - JSON value mapping
func mapping(map: Map) {
if map.mappingType == .toJSON {
var id = self.id
id <- map["id"]
} else {
id <- map["id"]
}
title <- map["title"]
fullTitle <- map["fullTitle"]
subTitle <- map["subTitle"]
detail <- map["detail"]
attributes <- map["flags"]
genre <- map["category"]
channel <- map["channel"]
episode <- map["episode"]
startTime <- (map["start"], TimeDateTransform())
endTime <- (map["end"], TimeDateTransform())
duration <- map["seconds"]
}
}
class TimeDateTransform: TransformType {
public func transformFromJSON(_ value: Any?) -> Date? {
if let seconds = value as? Double {
return Date(timeIntervalSince1970: TimeInterval(seconds / 1000))
}
return nil
}
public func transformToJSON(_ value: Date?) -> Double? {
if let date = value {
return date.timeIntervalSince1970 * 1000
}
return nil
}
}
| bsd-3-clause | d1f5df3a3cb2de0dfefb5981b97615f0 | 31.465969 | 128 | 0.681342 | 3.576125 | false | false | false | false |
ProfileCreator/ProfileCreator | ProfileCreator/ProfileCreator/Profile Editor TableView CellViews/PayloadCellViewComboBox.swift | 1 | 8783 | //
// PayloadCellViewPopUpButton.swift
// ProfileCreator
//
// Created by Erik Berglund.
// Copyright ยฉ 2018 Erik Berglund. All rights reserved.
//
import Cocoa
import ProfilePayloads
class PayloadCellViewComboBox: PayloadCellView, ProfileCreatorCellView {
// MARK: -
// MARK: Instance Variables
var comboBox: NSComboBox?
var textFieldUnit: NSTextField?
var valueDefault: Any?
// MARK: -
// MARK: Initialization
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
required init(subkey: PayloadSubkey, payloadIndex: Int, enabled: Bool, required: Bool, editor: ProfileEditor) {
super.init(subkey: subkey, payloadIndex: payloadIndex, enabled: enabled, required: required, editor: editor)
// ---------------------------------------------------------------------
// Setup Custom View Content
// ---------------------------------------------------------------------
var titles = [String]()
if let rangeListTitles = subkey.rangeListTitles {
titles = rangeListTitles
} else if let rangeList = subkey.rangeList {
rangeList.forEach { titles.append(String(describing: $0)) }
}
let comboBox = EditorComboBox.withTitles(titles: titles, cellView: self)
self.comboBox = comboBox
self.setupComboBox()
// ---------------------------------------------------------------------
// Setup Footer
// ---------------------------------------------------------------------
super.setupFooter(belowCustomView: comboBox)
// ---------------------------------------------------------------------
// Set Default Value
// ---------------------------------------------------------------------
if let valueDefault = subkey.defaultValue() {
self.valueDefault = valueDefault
}
// ---------------------------------------------------------------------
// Setup Unit if it is set
// ---------------------------------------------------------------------
if let valueUnit = subkey.valueUnit {
self.textFieldUnit = EditorTextField.label(string: valueUnit,
fontWeight: .regular,
leadingItem: comboBox,
leadingConstant: 7.0,
trailingItem: nil,
constraints: &self.cellViewConstraints,
cellView: self)
self.setupTextFieldUnit()
}
// ---------------------------------------------------------------------
// Get Value
// ---------------------------------------------------------------------
let value: Any?
if let valueUser = self.profile.settings.value(forSubkey: subkey, payloadIndex: payloadIndex) {
value = valueUser
} else if let valueDefault = self.valueDefault {
value = valueDefault
} else {
value = comboBox.objectValues.first
}
// ---------------------------------------------------------------------
// Select Value
// ---------------------------------------------------------------------
if
let selectedValue = value,
let title = PayloadUtility.title(forRangeListValue: selectedValue, subkey: subkey),
comboBox.objectValues.containsAny(value: title, ofType: .string) {
comboBox.selectItem(withObjectValue: title)
} else {
comboBox.objectValue = value
}
// ---------------------------------------------------------------------
// Setup KeyView Loop Items
// ---------------------------------------------------------------------
self.leadingKeyView = comboBox
self.trailingKeyView = comboBox
// ---------------------------------------------------------------------
// Activate Layout Constraints
// ---------------------------------------------------------------------
NSLayoutConstraint.activate(self.cellViewConstraints)
}
// MARK: -
// MARK: PayloadCellView Functions
override func enable(_ enable: Bool) {
self.isEnabled = enable
self.comboBox?.isEnabled = enable
}
}
// MARK: -
// MARK: NSComboBoxDelegate Functions
extension PayloadCellViewComboBox: NSComboBoxDelegate {
func comboBoxSelectionDidChange(_ notification: Notification) {
if let comboBox = notification.object as? NSComboBox, let selectedValue = comboBox.objectValueOfSelectedItem {
if
comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type),
let selectedTitle = selectedValue as? String,
let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) {
self.profile.settings.setValue(value, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
} else {
self.profile.settings.setValue(selectedValue, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
}
comboBox.objectValue = selectedValue
comboBox.highlighSubstrings(for: self.subkey)
if self.subkey.isConditionalTarget {
self.profileEditor.reloadTableView(updateCellViews: true)
}
}
}
}
// MARK: -
// MARK: NSControl Functions
extension PayloadCellViewComboBox {
func controlTextDidChange(_ notification: Notification) {
if let comboBox = notification.object as? NSComboBox, let selectedValue = comboBox.objectValue {
if
comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type),
let selectedTitle = selectedValue as? String,
let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) {
self.profile.settings.setValue(value, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
} else {
self.profile.settings.setValue(selectedValue, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
}
comboBox.highlighSubstrings(for: self.subkey)
}
}
func controlTextDidEndEditing(_ notification: Notification) {
if let comboBox = notification.object as? NSComboBox, let selectedValue = comboBox.objectValue {
if
comboBox.objectValues.contains(value: selectedValue, ofType: self.subkey.type),
let selectedTitle = selectedValue as? String,
let value = PayloadUtility.value(forRangeListTitle: selectedTitle, subkey: self.subkey) {
self.profile.settings.setValue(value, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
} else {
self.profile.settings.setValue(selectedValue, forSubkey: self.subkey, payloadIndex: self.payloadIndex)
}
comboBox.highlighSubstrings(for: self.subkey)
if self.subkey.isConditionalTarget {
self.profileEditor.reloadTableView(updateCellViews: true)
}
}
}
}
// MARK: -
// MARK: Setup NSLayoutConstraints
extension PayloadCellViewComboBox {
private func setupComboBox() {
// ---------------------------------------------------------------------
// Add PopUpButton to TableCellView
// ---------------------------------------------------------------------
guard let comboBox = self.comboBox else { return }
self.addSubview(comboBox)
// ---------------------------------------------------------------------
// Add constraints
// ---------------------------------------------------------------------
// Below
self.addConstraints(forViewBelow: comboBox)
// Leading
self.addConstraints(forViewLeading: comboBox)
// Trailing
self.addConstraints(forViewTrailing: comboBox)
}
private func setupTextFieldUnit() {
// ---------------------------------------------------------------------
// Add TextField to TableCellView
// ---------------------------------------------------------------------
guard let textFieldUnit = self.textFieldUnit, let popUpButton = self.comboBox else { return }
textFieldUnit.textColor = .secondaryLabelColor
popUpButton.setContentHuggingPriority(.defaultHigh, for: .horizontal)
}
}
| mit | cce0376a0c4ee4d639574e990da4ab1f | 40.230047 | 118 | 0.493054 | 6.115599 | false | false | false | false |
kzin/swift-design-patterns | Design Patterns.playground/Pages/Decorator.xcplaygroundpage/Contents.swift | 1 | 1277 | protocol Beverage {
func cost() -> Double
func description() -> String
}
class Coffee: Beverage {
func cost() -> Double {
return 0.95
}
func description() -> String {
return "Coffe"
}
}
class Expresso: Beverage {
func cost() -> Double {
return 0.5
}
func description() -> String {
return "Expresso"
}
}
class Mocha: Beverage {
let beverage: Beverage
init(beverage: Beverage) {
self.beverage = beverage
}
func cost() -> Double {
return 0.2 + self.beverage.cost()
}
func description() -> String {
return self.beverage.description() + ", Mocha"
}
}
class Whip: Beverage {
let beverage: Beverage
init(beverage: Beverage) {
self.beverage = beverage
}
func cost() -> Double {
return 0.45 + self.beverage.cost()
}
func description() -> String {
return self.beverage.description() + ", Whip"
}
}
var darkRoast: Beverage = Coffee()
darkRoast = Mocha(beverage: darkRoast)
darkRoast = Mocha(beverage: darkRoast)
darkRoast = Whip(beverage: darkRoast)
darkRoast.description()
darkRoast.cost()
var expresso: Beverage = Expresso()
expresso.description()
expresso.cost() | mit | 3e895e2f4fa401f8e585d694a7b25331 | 17.794118 | 54 | 0.588097 | 3.66954 | false | false | false | false |
theScud/Lunch | lunchPlanner/Data Layer/DataModels/FSVenue.swift | 1 | 1187 | //
// FQVenue.swift
// lunchPlanner
//
// Created by Sudeep Kini on 03/11/16.
// Copyright ยฉ 2016 TestLabs. All rights reserved.
//
import Foundation
import RealmSwift
import CoreLocation
/// Object representing a Venue in the apps database
class FSVenue:Object{
dynamic var address: String = ""
dynamic var distance: Double = 0.0
dynamic var isYuck: String = "false"
dynamic var id: String = ""
dynamic var latitude: Double = 0.0
dynamic var longitude: Double = 0.0
dynamic var name: String = ""
dynamic var photoURL: String? = ""
dynamic var Categories: String? = ""
dynamic var rating: Double = 0.0
dynamic var ratingsCount: Int = 0
/// CLLoation of Coffee venue.
var coordinate: CLLocation {
return CLLocation(latitude: Double(latitude), longitude: Double(longitude))
}
/// 2D coordinate of Coffee venue.
var coordinate2D: CLLocationCoordinate2D {
return CLLocationCoordinate2D(latitude: Double(latitude), longitude: Double(longitude))
}
/// Using "id" field as primary key in Realm.
override static func primaryKey() -> String? {
return "id"
}
}
| apache-2.0 | 4f0b4b3d2f192e50de9760035ac1cd2c | 24.234043 | 95 | 0.658516 | 4.118056 | false | false | false | false |
formbound/Plume | Sources/SQL/Update.swift | 1 | 1409 | public struct Update {
public let tableName: String
public var predicate: Predicate = .true
public var returning: [Column] = []
fileprivate var values: [Column: Value]
public init(table tableName: String, set values: [Column: ValueRepresentable?]) {
self.tableName = tableName
self.values = values.mapValues {
return $0?.sqlValue ?? .null
}
}
public init<T: Table>(table: T.Type, set values: [Column: ValueRepresentable?]) {
self.init(table: table.tableName, set: values)
}
}
extension Update: ReturningQuery {}
extension Update: PredicatedQuery {}
extension Update: ComponentsRepresentable {
internal var sqlComponents: Components {
var components = Components(compoundOf: ["UPDATE", tableName])
if !values.isEmpty {
components.append("SET")
components.append(
Components(
listOf: values.map {
Components(compoundOf: [$0.0.name, "=", $0.1])
},
separator: ", ")
)
}
if case .true = predicate {} else {
components.append(Components(compoundOf: ["WHERE", predicate]))
}
if let returningComponents = returning.returningComponents {
components.append(returningComponents)
}
return components
}
}
| mit | 9d1c49b54fc69e60b04a9566f9554b8c | 26.096154 | 85 | 0.581263 | 4.825342 | false | false | false | false |
SwiftyMagic/Magic | Magic/Magic/UIKit/UINavigationBarExtension.swift | 1 | 1460 | //
// UINavigationBarExtension.swift
// Magic
//
// Created by Broccoli on 2016/10/14.
// Copyright ยฉ 2016ๅนด broccoliii. All rights reserved.
//
import Foundation
// MARK: - Properties
fileprivate var kBarHeightAssociativeKey = "kBarHeightAssociativeKey"
extension UINavigationBar {
public var barHeight: CGFloat {
get {
return getAssociatedObject(&kBarHeightAssociativeKey) as? CGFloat ?? 44
}
set {
setAssociatedObject(newValue, associativeKey: kBarHeightAssociativeKey, policy: .OBJC_ASSOCIATION_RETAIN_NONATOMIC)
}
}
open override func sizeThatFits(_ size: CGSize) -> CGSize {
return CGSize(width: self.superview!.bounds.size.width, height: barHeight)
}
}
// MARK: - Methods
extension UINavigationBar {
func setColor(_ color: UIColor, for barMetrics: UIBarMetrics) {
let backgroundImage = UIImage(color: color)
setBackgroundImage(backgroundImage, for: barMetrics)
}
func hideBottomBorder() {
self.shadowImage = UIImage()
}
func setBottomBorderColor(color: UIColor, height: CGFloat) {
let bottomBorderRect = CGRect(x: 0, y: frame.height, width: frame.width, height: height)
let bottomBorderView = UIView(frame: bottomBorderRect)
bottomBorderView.backgroundColor = color
addSubview(bottomBorderView)
}
func beginLoading(prompt: String) {
}
}
| mit | ab2877f3d800f15d9928a16158aa7c05 | 27.568627 | 127 | 0.667124 | 4.684887 | false | false | false | false |
CoderST/XMLYDemo | XMLYDemo/XMLYDemo/Class/Home/Controller/SubViewController/PopularViewController/Model/CityColumnModel.swift | 1 | 692 | //
// CityColumnModel.swift
// XMLYDemo
//
// Created by xiudou on 2016/12/22.
// Copyright ยฉ 2016ๅนด CoderST. All rights reserved.
//
import UIKit
class CityColumnModel: BaseModel {
var title : String = ""
var code : String = ""
var list : [CityColumnItem] = [CityColumnItem]()
override func setValue(_ value: Any?, forKey key: String) {
if key == "list"{
if let listArray = value as? [[String : AnyObject]]{
for listDict in listArray {
list.append(CityColumnItem(dict: listDict))
}
}
}else{
super.setValue(value, forKey: key)
}
}
}
| mit | a7233a1212faf038159c2e29deef295a | 22.758621 | 64 | 0.53701 | 4.125749 | false | false | false | false |
relayrides/objective-c-sdk | Pods/Mixpanel-swift/Mixpanel/TweakStore.swift | 1 | 7537 | //
// TweakStore.swift
// SwiftTweaks
//
// Created by Bryan Clark on 11/5/15.
// Copyright ยฉ 2015 Khan Academy. All rights reserved.
//
import UIKit
/// Looks up the persisted state for tweaks.
public final class TweakStore {
/// The "tree structure" for our Tweaks UI.
var tweakCollections: [String: TweakCollection] = [:]
/// Useful when exporting or checking that a tweak exists in tweakCollections
var allTweaks: Set<AnyTweak>
/// We hold a reference to the storeName so we can have a better error message if a tweak doesn't exist in allTweaks.
private let storeName: String
/// Caches "single" bindings - when a tweak is updated, we'll call each of the corresponding bindings.
private var tweakBindings: [String: [AnyTweakBinding]] = [:]
/// Caches "multi" bindings - when any tweak in a Set is updated, we'll call each of the corresponding bindings.
private var tweakSetBindings: [Set<AnyTweak>: [() -> Void]] = [:]
/// Persists tweaks' currentValues and maintains them on disk.
private let persistence: TweakPersistency
/// Determines whether tweaks are enabled, and whether the tweaks UI is accessible
internal let enabled: Bool
///
///
/**
Creates a TweakStore, with information persisted on-disk.
If you want to have multiple TweakStores in your app, you can pass in a unique storeName to keep it separate from others on disk.
- parameter storeName: the name of the store (optional)
- parameter enabled: if debugging is enabled or not
*/
init(storeName: String = "Tweaks", enabled: Bool) {
self.persistence = TweakPersistency(identifier: storeName)
self.storeName = storeName
self.enabled = enabled
self.allTweaks = Set()
}
/// A method for adding Tweaks to the environment
func addTweaks(_ tweaks: [TweakClusterType]) {
self.allTweaks.formUnion(Set(tweaks.reduce([]) { $0 + $1.tweakCluster }))
self.allTweaks.forEach { tweak in
// Find or create its TweakCollection
var tweakCollection: TweakCollection
if let existingCollection = tweakCollections[tweak.collectionName] {
tweakCollection = existingCollection
} else {
tweakCollection = TweakCollection(title: tweak.collectionName)
tweakCollections[tweakCollection.title] = tweakCollection
}
// Find or create its TweakGroup
var tweakGroup: TweakGroup
if let existingGroup = tweakCollection.tweakGroups[tweak.groupName] {
tweakGroup = existingGroup
} else {
tweakGroup = TweakGroup(title: tweak.groupName)
}
// Add the tweak to the tree
tweakGroup.tweaks[tweak.tweakName] = tweak
tweakCollection.tweakGroups[tweakGroup.title] = tweakGroup
tweakCollections[tweakCollection.title] = tweakCollection
}
}
/// Returns the current value for a given tweak
func assign<T>(_ tweak: Tweak<T>) -> T {
return self.currentValueForTweak(tweak)
}
/**
The bind function for Tweaks. This is meant for binding Tweaks to the relevant components.
- parameter tweak: the tweak to bind
- parameter binding: the binding to issue for the tweak
*/
func bind<T>(_ tweak: Tweak<T>, binding: @escaping (T) -> Void) {
// Create the TweakBinding<T>, and wrap it in our type-erasing AnyTweakBinding
let tweakBinding = TweakBinding(tweak: tweak, binding: binding)
let anyTweakBinding = AnyTweakBinding(tweakBinding: tweakBinding)
// Cache the binding
let existingTweakBindings = tweakBindings[tweak.persistenceIdentifier] ?? []
tweakBindings[tweak.persistenceIdentifier] = existingTweakBindings + [anyTweakBinding]
// Then immediately apply the binding on whatever current value we have
binding(currentValueForTweak(tweak))
}
func bindMultiple(_ tweaks: [TweakType], binding: @escaping () -> Void) {
// Convert the array (which makes it easier to call a `bindTweakSet`) into a set (which makes it possible to cache the tweakSet)
let tweakSet = Set(tweaks.map(AnyTweak.init))
// Cache the cluster binding
let existingTweakSetBindings = tweakSetBindings[tweakSet] ?? []
tweakSetBindings[tweakSet] = existingTweakSetBindings + [binding]
// Immediately call the binding
binding()
}
// MARK: - Internal
/// Resets all tweaks to their `defaultValue`
internal func reset() {
persistence.clearAllData()
// Go through all tweaks in our library, and call any bindings they're attached to.
tweakCollections.values.reduce([]) { $0 + $1.sortedTweakGroups.reduce([]) { $0 + $1.sortedTweaks } }
.forEach { updateBindingsForTweak($0)
}
}
internal func currentValueForTweak<T>(_ tweak: Tweak<T>) -> T {
if allTweaks.contains(AnyTweak(tweak: tweak)) {
return enabled ? persistence.currentValueForTweak(tweak) ?? tweak.defaultValue : tweak.defaultValue
} else {
Logger.error(message: "Error: the tweak \"\(tweak.tweakIdentifier)\" isn't included in the tweak store \"\(storeName)\"." +
"Returning the default value.")
return tweak.defaultValue
}
}
internal func currentViewDataForTweak(_ tweak: AnyTweak) -> TweakViewData {
let cachedValue = persistence.persistedValueForTweakIdentifiable(tweak)
switch tweak.tweakDefaultData {
case let .boolean(defaultValue: defaultValue):
let currentValue = cachedValue as? Bool ?? defaultValue
return .boolean(value: currentValue, defaultValue: defaultValue)
case let .integer(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? Int ?? defaultValue
return .integer(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .float(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? CGFloat ?? defaultValue
return .float(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .doubleTweak(defaultValue: defaultValue, min: min, max: max, stepSize: step):
let currentValue = cachedValue as? Double ?? defaultValue
return .doubleTweak(value: currentValue, defaultValue: defaultValue, min: min, max: max, stepSize: step)
case let .color(defaultValue: defaultValue):
let currentValue = cachedValue as? UIColor ?? defaultValue
return .color(value: currentValue, defaultValue: defaultValue)
case let .string(defaultValue: defaultValue):
let currentValue = cachedValue as? String ?? defaultValue
return .string(value: currentValue, defaultValue: defaultValue)
}
}
internal func setValue(_ viewData: TweakViewData, forTweak tweak: AnyTweak) {
persistence.setValue(viewData.value, forTweakIdentifiable: tweak)
updateBindingsForTweak(tweak)
}
// MARK - Private
/// Update Bindings for the Tweaks when a change is needed.
private func updateBindingsForTweak(_ tweak: AnyTweak) {
// Find any 1-to-1 bindings and update them
tweakBindings[tweak.persistenceIdentifier]?.forEach {
$0.applyBindingWithValue(currentViewDataForTweak(tweak).value)
}
// Find any cluster bindings and update them
for (tweakSet, bindingsArray) in tweakSetBindings {
if tweakSet.contains(tweak) {
bindingsArray.forEach { $0() }
}
}
}
}
extension TweakStore {
internal var sortedTweakCollections: [TweakCollection] {
return tweakCollections
.sorted { $0.0 < $1.0 }
.map { return $0.1 }
}
}
| apache-2.0 | b4fbc51571a9e554e631c73b835552ff | 38.25 | 135 | 0.702097 | 4.175069 | false | false | false | false |
cybertunnel/SplashBuddy | SplashBuddy/View/MainViewController_Actions.swift | 1 | 2345 | //
// MainViewController_Actions.swift
// SplashBuddy
//
// Created by Francois Levaux on 02.03.17.
// Copyright ยฉ 2017 Franรงois Levaux-Tiffreau. All rights reserved.
//
import Foundation
extension MainViewController {
func setupInstalling() {
indeterminateProgressIndicator.startAnimation(self)
indeterminateProgressIndicator.isHidden = false
installingLabel.stringValue = NSLocalizedString("Installingโฆ", comment: "")
statusLabel.stringValue = ""
continueButton.isEnabled = false
}
func errorWhileInstalling() {
indeterminateProgressIndicator.isHidden = true
installingLabel.stringValue = ""
continueButton.isEnabled = true
statusLabel.textColor = .red
let _failedSoftwareArray = SoftwareArray.sharedInstance.failedSoftwareArray()
if _failedSoftwareArray.count == 1 {
if let failedDisplayName = _failedSoftwareArray[0].displayName {
statusLabel.stringValue = String.localizedStringWithFormat(NSLocalizedString(
"%@ failed to install. Support has been notified.",
comment: "A specific application failed to install"), failedDisplayName)
} else {
statusLabel.stringValue = NSLocalizedString(
"An application failed to install. Support has been notified.",
comment: "One (unnamed) application failed to install")
}
} else {
statusLabel.stringValue = NSLocalizedString(
"Some applications failed to install. Support has been notified.",
comment: "More than one application failed to install")
}
}
func canContinue() {
continueButton.isEnabled = true
}
func doneInstalling() {
indeterminateProgressIndicator.isHidden = true
installingLabel.stringValue = ""
statusLabel.textColor = .labelColor
statusLabel.stringValue = NSLocalizedString(
"All applications were installed. Please click continue.",
comment: "All applications were installed. Please click continue.")
}
}
| apache-2.0 | 294a56073718ae62cd69230721ab3ca1 | 29.402597 | 93 | 0.605297 | 6.242667 | false | false | false | false |
joostholslag/BNRiOS | iOSProgramming6ed/15 - Camera/Solutions/Homepwner/Homepwner/AppDelegate.swift | 1 | 2437 | //
// Copyright ยฉ 2015 Big Nerd Ranch
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]?) -> Bool {
// Override point for customization after application launch.
let itemStore = ItemStore()
let imageStore = ImageStore()
let navController = window!.rootViewController as! UINavigationController
let itemsController = navController.topViewController as! ItemsViewController
itemsController.itemStore = itemStore
itemsController.imageStore = imageStore
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:.
}
}
| gpl-3.0 | d0af5facaba6d136aa9c950076f8db27 | 47.72 | 285 | 0.742611 | 5.95599 | false | false | false | false |
1457792186/JWSwift | SwiftLearn/SwiftDemo/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Evaporate.swift | 3 | 3038 | //
// LTMorphingLabel+Evaporate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.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
extension LTMorphingLabel {
@objc
func EvaporateLoad() {
progressClosures["Evaporate\(LTMorphingPhases.progress)"] = {
(index: Int, progress: Float, isNewChar: Bool) in
let j: Int = Int(round(cos(Double(index)) * 1.2))
let delay = isNewChar ? self.morphingCharacterDelay * -1.0 : self.morphingCharacterDelay
return min(1.0, max(0.0, self.morphingProgress + delay * Float(j)))
}
effectClosures["Evaporate\(LTMorphingPhases.disappear)"] = {
char, index, progress in
let newProgress = LTEasing.easeOutQuint(progress, 0.0, 1.0, 1.0)
let yOffset: CGFloat = -0.8 * CGFloat(self.font.pointSize) * CGFloat(newProgress)
let currentRect = self.previousRects[index].offsetBy(dx: 0, dy: yOffset)
let currentAlpha = CGFloat(1.0 - newProgress)
return LTCharacterLimbo(
char: char,
rect: currentRect,
alpha: currentAlpha,
size: self.font.pointSize,
drawingProgress: 0.0)
}
effectClosures["Evaporate\(LTMorphingPhases.appear)"] = {
char, index, progress in
let newProgress = 1.0 - LTEasing.easeOutQuint(progress, 0.0, 1.0)
let yOffset = CGFloat(self.font.pointSize) * CGFloat(newProgress) * 1.2
return LTCharacterLimbo(
char: char,
rect: self.newRects[index].offsetBy(dx: 0, dy: yOffset),
alpha: CGFloat(self.morphingProgress),
size: self.font.pointSize,
drawingProgress: 0.0
)
}
}
}
| apache-2.0 | 4cc958caa336234ae29c1f2f2d94f35b | 39.945946 | 100 | 0.628383 | 4.469027 | false | false | false | false |
4np/UitzendingGemist | UitzendingGemist/ByDayDetailedCollectionViewCell.swift | 1 | 1894 | //
// ByDayDetailedCollectionViewCell.swift
// UitzendingGemist
//
// Created by Jeroen Wesbeek on 02/08/16.
// Copyright ยฉ 2016 Jeroen Wesbeek. All rights reserved.
//
import Foundation
import UIKit
import NPOKit
import CocoaLumberjack
class ByDayDetailedCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var episodeImageView: UIImageView!
@IBOutlet weak var programNameLabel: UILabel!
@IBOutlet weak var episodeNameAndTimeLabel: UILabel!
fileprivate var imageRequest: NPORequest?
// MARK: Lifecycle
override func prepareForReuse() {
super.prepareForReuse()
episodeImageView.image = nil
programNameLabel.text = nil
episodeNameAndTimeLabel.text = nil
}
// MARK: Configuration
func configure(withEpisode episode: NPOEpisode) {
let names = episode.getNames()
programNameLabel.text = names.programName
episodeNameAndTimeLabel.text = names.episodeNameAndInfo
// Somehow in tvOS 10 / Xcode 8 / Swift 3 the frame will initially be 1000x1000
// causing the images to look compressed so hardcode the dimensions for now...
// TODO: check if this is solved in later releases...
//let size = episodeImageView.frame.size
let size = CGSize(width: 375, height: 211)
// get image
imageRequest = episode.getImage(ofSize: size) { [weak self] image, _, request in
guard let imageRequest = self?.imageRequest, request == imageRequest else {
return
}
self?.episodeImageView.image = image
}
}
// MARK: Focus engine
override func didUpdateFocus(in context: UIFocusUpdateContext, with coordinator: UIFocusAnimationCoordinator) {
episodeImageView.adjustsImageWhenAncestorFocused = self.isFocused
}
}
| apache-2.0 | 9705a9525edfa91e34f3651e825b106b | 31.084746 | 115 | 0.66561 | 5.172131 | false | false | false | false |
ais-recognition/speaker | SwiftMQTT/CocoaMQTTMessage.swift | 1 | 1352 | //
// CocoaMQTTMessage.swift
// CocoaMQTT
//
// Created by Feng Lee<[email protected]> on 14/8/3.
// Copyright (c) 2014ๅนด slimpp.io. All rights reserved.
//
import Foundation
/**
* MQTT Messgae
*/
class CocoaMQTTMessage {
var topic: String
var payload: [UInt8]
//utf8 bytes array to string
var string: String? {
get {
return NSString(bytes: payload, length: payload.count, encoding: NSUTF8StringEncoding) as? String
// return String.stringWithBytes(payload,
// length: payload.count,
// encoding: NSUTF8StringEncoding)
}
}
var qos: CocoaMQTTQOS = .QOS1
var retain: Bool = false
var dup: Bool = false
init(topic: String, string: String, qos: CocoaMQTTQOS = .QOS1) {
self.topic = topic
self.payload = [UInt8](string.utf8)
self.qos = qos
}
init(topic: String, payload: [UInt8], qos: CocoaMQTTQOS = .QOS1, retain: Bool = false, dup: Bool = false) {
self.topic = topic
self.payload = payload
self.qos = qos
self.retain = retain
self.dup = dup
}
}
/**
* MQTT Will Message
**/
class CocoaMQTTWill: CocoaMQTTMessage {
init(topic: String, message: String) {
super.init(topic: topic, payload: message.bytesWithLength)
}
}
| mit | 1c6bb6d38a7fe45e25dccbcba61f52ab | 20.774194 | 111 | 0.594074 | 3.658537 | false | false | false | false |
alexktchen/rescue.iOS | Rescue/CustomAnnotationView.swift | 1 | 1901 | //
// KTAnnotationView.swift
// Rescue
//
// Created by Alex Chen on 2015/1/18.
// Copyright (c) 2015ๅนด Alex Chen. All rights reserved.
//
import UIKit
import MapKit
class CustomAnnotationView :MKPinAnnotationView{
var calloutView: CalloutDirectionsView?
override init!(annotation: MKAnnotation!, reuseIdentifier: String!) {
super.init(annotation: annotation, reuseIdentifier: reuseIdentifier)
let Arrowimageimage = UIImage(named: "calloutDirectionsArrow") as UIImage?
var button: UIButton = UIButton()
button.addTarget(self, action: "tappedButton:", forControlEvents: UIControlEvents.TouchUpInside)
button.frame = CGRectMake(0, 0, 48, 48)
button.setImage(Arrowimageimage, forState: UIControlState.Normal)
var leftView: UIView = UIView(frame: CGRectMake(0, 0, 48, 48))
leftView.backgroundColor = UIColor(red: 0/255, green: 163/255, blue: 68/255, alpha: 1)
leftView.addSubview(button)
self.leftCalloutAccessoryView = leftView
}
func tappedButton(sender: UIButton!){
var add = "q="
add += String(format:"%f", self.annotation.coordinate.latitude)
add += ","
add += String(format:"%f", self.annotation.coordinate.longitude)
// if (UIApplication.sharedApplication().canOpenURL(NSURL(string:"comgooglemaps://")!)) {
UIApplication.sharedApplication().openURL(NSURL(string:
"http://maps.apple.com/map?"+add)!)
// } else {
NSLog("Can't use comgooglemaps://");
// }
println("tapped button")
}
override init(frame: CGRect) {
super.init(frame:frame)
}
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
| mit | 55d74d7eed0b1a345ac75191e648a011 | 29.629032 | 104 | 0.611901 | 4.620438 | false | false | false | false |
merlos/iOS-Open-GPX-Tracker | Pods/MapCache/MapCache/Classes/MapCacheConfig.swift | 1 | 4149 | //
// MapCacheConfig.swift
// MapCache
//
// Created by merlos on 13/05/2019.
//
import Foundation
import CoreGraphics
///
/// Settings of your MapCache.
///
///
public struct MapCacheConfig {
/// Each time a tile is going to be retrieved from the server its x,y and z (zoom) values are plugged into this URL template.
///
/// Default value `"https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png`
///
/// Where
/// 1. `{s}` Replaced with one of the subdomains defined in `subdomains`.
/// 2. `{z}` Replaced with the zoom level value.
/// 3. `{x}` Replaced with the position of the tile in the X asis for this zoom level
/// 4. `{y}` Replaced with the position of the tile in the X asis for this zoom level
///
/// - SeeAlso: [Tiles servers in OpenStreetMap wiki](https://en.wikipedia.org/wiki/Tiled_web_map)
/// - SeeAlso: [Tiled we maps in wikipedia](https://en.wikipedia.org/wiki/Tiled_web_map)
public var urlTemplate: String = "https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/// Subdomains used on the `urlTemplate`
public var subdomains: [String] = ["a","b","c"]
///
/// It must be smaller or equal than `maximumZ`
///
/// Default value is 0.
public var minimumZ: Int = 0
///
/// Maximum supported zoom by the tile server
///
/// Tiles with a z zoom beyond `maximumZ` supported by the tile server will return a HTTP 404 error.
///
/// Values vary from server to server. For example OpenStreetMap supports 19, but OpenCycleMap supports 22
///
/// Default value: 19. If 0 or negative is set iOS default value (i.e. 21)
///
/// - SeeAlso: [OpenStreetMap Wiki Slippy map tilenames](https://wiki.openstreetmap.org/wiki/Slippy_map_tilenames)
///
public var maximumZ: Int = 19
///
/// If set to true when zooming in beyond `maximumZ` the tiles at `maximumZ` will be upsampled and shown.
/// This mitigates the issue of showing an empty map when zooming in beyond `maximumZ`.
///
/// `maximumZ` is vital to zoom working, make sure it is properly set.
///
public var overZoomMaximumZ: Bool = true
///
/// Name of the cache
/// A folder will be created with this name all files will be stored in that folder
///
/// Default value "MapCache"
public var cacheName: String = "MapCache"
///
/// Cache capacity in bytes
///
public var capacity: UInt64 = UINT64_MAX
///
/// Tile size of the tile. Default is 256x256
///
public var tileSize: CGSize = CGSize(width: 256, height: 256)
///
/// Load tile mode.
/// Sets the strategy to be used when loading a tile.
/// By default loads from the cache and if it fails loads from the server
///
/// - SeeAlso: `LoadTileMode`
public var loadTileMode: LoadTileMode = .cacheThenServer
///
/// Constructor with all the default values.
///
public init() {
}
///
///Constructor that overwrites the `urlTemplate``
///
/// - Parameter withUrlTemplate: is the string of the `urlTemplate`
///
public init(withUrlTemplate urlTemplate: String) {
self.urlTemplate = urlTemplate
}
///
/// Selects one of the subdomains randomly.
///
public func randomSubdomain() -> String? {
if subdomains.count == 0 {
return nil
}
let rand = Int(arc4random_uniform(UInt32(subdomains.count)))
return subdomains[rand]
}
/// Keeps track of the index of the last subdomain requested for round robin
private var subdomainRoundRobin: Int = 0
/// Round Robin algorithm
/// If subdomains are a,b,c then it makes requests to a,b,c,a,b,c,a,b,c...
///
/// It uniformly makes requests to all the subdomains.
public mutating func roundRobinSubdomain() -> String? {
if subdomains.count == 0 {
return nil
}
self.subdomainRoundRobin = (self.subdomainRoundRobin + 1) % subdomains.count
return subdomains[subdomainRoundRobin]
}
}
| gpl-3.0 | 1f768102aed02f1ee8d92f885b71070d | 31.162791 | 129 | 0.61557 | 3.989423 | false | false | false | false |
abertelrud/swift-package-manager | Sources/PackageCollectionsSigning/Key/ASN1/ASN1.swift | 2 | 14532 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift open source project
//
// Copyright (c) 2021 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//===----------------------------------------------------------------------===//
//
// This source file is part of the SwiftCrypto open source project
//
// Copyright (c) 2019-2020 Apple Inc. and the SwiftCrypto project authors
// Licensed under Apache License v2.0
//
// See http://swift.org/LICENSE.txt for license information
// See CONTRIBUTORS.md for the list of SwiftCrypto project authors
//
//===----------------------------------------------------------------------===//
import Foundation
// Source code in the ASN1 subdirectory is taken from SwiftCrypto and provides an even more
// limited set of functionalities than what's in SwiftCrypto. The sole purpose is to parse
// keys in PEM format for older macOS versions, since `init(pemRepresentation:)` is not
// available until macOS 11. For complete source files, see https://github.com/apple/swift-crypto.
// Source: https://github.com/apple/swift-crypto/blob/main/Sources/Crypto/ASN1/ASN1.swift
internal enum ASN1 {}
// MARK: - Parser Node
extension ASN1 {
/// An `ASN1ParserNode` is a representation of a parsed ASN.1 TLV section. An `ASN1ParserNode` may be primitive, or may be composed of other `ASN1ParserNode`s.
/// In our representation, we keep track of this by storing a node "depth", which allows rapid forward and backward scans to hop over sections
/// we're uninterested in.
///
/// This type is not exposed to users of the API: it is only used internally for implementation of the user-level API.
fileprivate struct ASN1ParserNode {
/// The identifier.
var identifier: ASN1Identifier
/// The depth of this node.
var depth: Int
/// The data bytes for this node, if it is primitive.
var dataBytes: ArraySlice<UInt8>?
}
}
extension ASN1.ASN1ParserNode: Hashable {}
// MARK: - Sequence
extension ASN1 {
/// Parse the node as an ASN.1 sequence.
internal static func sequence<T>(_ node: ASN1Node, _ builder: (inout ASN1.ASN1NodeCollection.Iterator) throws -> T) throws -> T {
guard node.identifier == .sequence, case .constructed(let nodes) = node.content else {
throw ASN1Error.unexpectedFieldType
}
var iterator = nodes.makeIterator()
let result = try builder(&iterator)
guard iterator.next() == nil else {
throw ASN1Error.invalidASN1Object
}
return result
}
}
// MARK: - Optional explicitly tagged
extension ASN1 {
/// Parses an optional explicitly tagged element. Throws on a tag mismatch, returns nil if the element simply isn't there.
///
/// Expects to be used with the `ASN1.sequence` helper function.
internal static func optionalExplicitlyTagged<T>(_ nodes: inout ASN1.ASN1NodeCollection.Iterator, tagNumber: Int, tagClass: ASN1.ASN1Identifier.TagClass, _ builder: (ASN1Node) throws -> T) throws -> T? {
var localNodesCopy = nodes
guard let node = localNodesCopy.next() else {
// Node not present, return nil.
return nil
}
let expectedNodeID = ASN1.ASN1Identifier(explicitTagWithNumber: tagNumber, tagClass: tagClass)
assert(expectedNodeID.constructed)
guard node.identifier == expectedNodeID else {
// Node is a mismatch, with the wrong tag. Our optional isn't present.
return nil
}
// We have the right optional, so let's consume it.
nodes = localNodesCopy
// We expect a single child.
guard case .constructed(let nodes) = node.content else {
// This error is an internal parser error: the tag above is always constructed.
preconditionFailure("Explicit tags are always constructed")
}
var nodeIterator = nodes.makeIterator()
guard let child = nodeIterator.next(), nodeIterator.next() == nil else {
throw ASN1Error.invalidASN1Object
}
return try builder(child)
}
}
// MARK: - Parsing
extension ASN1 {
/// A parsed representation of ASN.1.
fileprivate struct ASN1ParseResult {
private static let maximumNodeDepth = 10
var nodes: ArraySlice<ASN1ParserNode>
private init(_ nodes: ArraySlice<ASN1ParserNode>) {
self.nodes = nodes
}
fileprivate static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1ParseResult {
var data = data
var nodes = [ASN1ParserNode]()
nodes.reserveCapacity(16)
try self.parseNode(from: &data, depth: 1, into: &nodes)
guard data.count == 0 else {
throw ASN1Error.invalidASN1Object
}
return ASN1ParseResult(nodes[...])
}
/// Parses a single ASN.1 node from the data and appends it to the buffer. This may recursively
/// call itself when there are child nodes for constructed nodes.
private static func parseNode(from data: inout ArraySlice<UInt8>, depth: Int, into nodes: inout [ASN1ParserNode]) throws {
guard depth <= ASN1.ASN1ParseResult.maximumNodeDepth else {
// We defend ourselves against stack overflow by refusing to allocate more than 10 stack frames to
// the parsing.
throw ASN1Error.invalidASN1Object
}
guard let rawIdentifier = data.popFirst() else {
throw ASN1Error.truncatedASN1Field
}
let identifier = try ASN1Identifier(rawIdentifier: rawIdentifier)
guard let wideLength = try data.readASN1Length() else {
throw ASN1Error.truncatedASN1Field
}
// UInt is sometimes too large for us!
guard let length = Int(exactly: wideLength) else {
throw ASN1Error.invalidASN1Object
}
var subData = data.prefix(length)
data = data.dropFirst(length)
guard subData.count == length else {
throw ASN1Error.truncatedASN1Field
}
if identifier.constructed {
nodes.append(ASN1ParserNode(identifier: identifier, depth: depth, dataBytes: nil))
while subData.count > 0 {
try self.parseNode(from: &subData, depth: depth + 1, into: &nodes)
}
} else {
nodes.append(ASN1ParserNode(identifier: identifier, depth: depth, dataBytes: subData))
}
}
}
}
extension ASN1.ASN1ParseResult: Hashable {}
extension ASN1 {
static func parse(_ data: [UInt8]) throws -> ASN1Node {
return try self.parse(data[...])
}
static func parse(_ data: ArraySlice<UInt8>) throws -> ASN1Node {
var result = try ASN1ParseResult.parse(data)
// There will always be at least one node if the above didn't throw, so we can safely just removeFirst here.
let firstNode = result.nodes.removeFirst()
let rootNode: ASN1Node
if firstNode.identifier.constructed {
// We need to feed it the next set of nodes.
let nodeCollection = result.nodes.prefix { $0.depth > firstNode.depth }
result.nodes = result.nodes.dropFirst(nodeCollection.count)
rootNode = ASN1.ASN1Node(identifier: firstNode.identifier, content: .constructed(.init(nodes: nodeCollection, depth: firstNode.depth)))
} else {
rootNode = ASN1.ASN1Node(identifier: firstNode.identifier, content: .primitive(firstNode.dataBytes!))
}
precondition(result.nodes.count == 0, "ASN1ParseResult unexpectedly allowed multiple root nodes")
return rootNode
}
}
// MARK: - ASN1NodeCollection
extension ASN1 {
/// Represents a collection of ASN.1 nodes contained in a constructed ASN.1 node.
///
/// Constructed ASN.1 nodes are made up of multiple child nodes. This object represents the collection of those child nodes.
/// It allows us to lazily construct the child nodes, potentially skipping over them when we don't care about them.
internal struct ASN1NodeCollection {
private var nodes: ArraySlice<ASN1ParserNode>
private var depth: Int
fileprivate init(nodes: ArraySlice<ASN1ParserNode>, depth: Int) {
self.nodes = nodes
self.depth = depth
precondition(self.nodes.allSatisfy { $0.depth > depth })
if let firstDepth = self.nodes.first?.depth {
precondition(firstDepth == depth + 1)
}
}
}
}
extension ASN1.ASN1NodeCollection: Sequence {
struct Iterator: IteratorProtocol {
private var nodes: ArraySlice<ASN1.ASN1ParserNode>
private var depth: Int
fileprivate init(nodes: ArraySlice<ASN1.ASN1ParserNode>, depth: Int) {
self.nodes = nodes
self.depth = depth
}
mutating func next() -> ASN1.ASN1Node? {
guard let nextNode = self.nodes.popFirst() else {
return nil
}
assert(nextNode.depth == self.depth + 1)
if nextNode.identifier.constructed {
// We need to feed it the next set of nodes.
let nodeCollection = self.nodes.prefix { $0.depth > nextNode.depth }
self.nodes = self.nodes.dropFirst(nodeCollection.count)
return ASN1.ASN1Node(identifier: nextNode.identifier, content: .constructed(.init(nodes: nodeCollection, depth: nextNode.depth)))
} else {
// There must be data bytes here, even if they're empty.
return ASN1.ASN1Node(identifier: nextNode.identifier, content: .primitive(nextNode.dataBytes!))
}
}
}
func makeIterator() -> Iterator {
return Iterator(nodes: self.nodes, depth: self.depth)
}
}
// MARK: - ASN1Node
extension ASN1 {
/// An `ASN1Node` is a single entry in the ASN.1 representation of a data structure.
///
/// Conceptually, an ASN.1 data structure is rooted in a single node, which may itself contain zero or more
/// other nodes. ASN.1 nodes are either "constructed", meaning they contain other nodes, or "primitive", meaning they
/// store a base data type of some kind.
///
/// In this way, ASN.1 objects tend to form a "tree", where each object is represented by a single top-level constructed
/// node that contains other objects and primitives, eventually reaching the bottom which is made up of primitive objects.
internal struct ASN1Node {
internal var identifier: ASN1Identifier
internal var content: Content
}
}
// MARK: - ASN1Node.Content
extension ASN1.ASN1Node {
/// The content of a single ASN1Node.
enum Content {
case constructed(ASN1.ASN1NodeCollection)
case primitive(ArraySlice<UInt8>)
}
}
// MARK: - Helpers
internal protocol ASN1Parseable {
init(asn1Encoded: ASN1.ASN1Node) throws
}
extension ASN1Parseable {
internal init(asn1Encoded sequenceNodeIterator: inout ASN1.ASN1NodeCollection.Iterator) throws {
guard let node = sequenceNodeIterator.next() else {
throw ASN1Error.invalidASN1Object
}
self = try .init(asn1Encoded: node)
}
internal init(asn1Encoded: [UInt8]) throws {
self = try .init(asn1Encoded: ASN1.parse(asn1Encoded))
}
}
extension ArraySlice where Element == UInt8 {
fileprivate mutating func readASN1Length() throws -> UInt? {
guard let firstByte = self.popFirst() else {
return nil
}
switch firstByte {
case 0x80:
// Indefinite form. Unsupported.
throw ASN1Error.unsupportedFieldLength
case let val where val & 0x80 == 0x80:
// Top bit is set, this is the long form. The remaining 7 bits of this octet
// determine how long the length field is.
let fieldLength = Int(val & 0x7F)
guard self.count >= fieldLength else {
return nil
}
// We need to read the length bytes
let lengthBytes = self.prefix(fieldLength)
self = self.dropFirst(fieldLength)
let length = try UInt(bigEndianBytes: lengthBytes)
// DER requires that we enforce that the length field was encoded in the minimum number of octets necessary.
let requiredBits = UInt.bitWidth - length.leadingZeroBitCount
switch requiredBits {
case 0 ... 7:
// For 0 to 7 bits, the long form is unacceptable and we require the short.
throw ASN1Error.unsupportedFieldLength
case 8...:
// For 8 or more bits, fieldLength should be the minimum required.
let requiredBytes = (requiredBits + 7) / 8
if fieldLength > requiredBytes {
throw ASN1Error.unsupportedFieldLength
}
default:
// This is not reachable, but we'll error anyway.
throw ASN1Error.unsupportedFieldLength
}
return length
case let val:
// Short form, the length is only one 7-bit integer.
return UInt(val)
}
}
}
extension FixedWidthInteger {
internal init<Bytes: Collection>(bigEndianBytes bytes: Bytes) throws where Bytes.Element == UInt8 {
guard bytes.count <= (Self.bitWidth / 8) else {
throw ASN1Error.invalidASN1Object
}
self = 0
let shiftSizes = stride(from: 0, to: bytes.count * 8, by: 8).reversed()
var index = bytes.startIndex
for shift in shiftSizes {
self |= Self(truncatingIfNeeded: bytes[index]) << shift
bytes.formIndex(after: &index)
}
}
}
extension FixedWidthInteger {
// Bytes needed to store a given integer.
internal var neededBytes: Int {
let neededBits = self.bitWidth - self.leadingZeroBitCount
return (neededBits + 7) / 8
}
}
| apache-2.0 | f12dc76a40917a27b705685281bce624 | 36.357326 | 207 | 0.620493 | 4.472761 | false | false | false | false |
badoo/Chatto | ChattoApp/ChattoApp/Source/Chat Items/Compound Messages/DemoDateMessageContentFactory.swift | 1 | 3787 | //
// The MIT License (MIT)
//
// Copyright (c) 2015-present Badoo Trading Limited.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Chatto
import ChattoAdditions
struct DemoDateMessageContentFactory: MessageContentFactoryProtocol {
private static let dateFormatter: DateFormatter = {
let formatter = DateFormatter()
formatter.locale = Locale.current
formatter.dateStyle = .medium
return formatter
}()
private let textInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
private let font = UIFont.systemFont(ofSize: 17)
func canCreateMessageContent(forModel model: DemoCompoundMessageModel) -> Bool {
return true
}
func createContentView() -> UIView {
let label = UILabel()
label.textAlignment = .right
return DateInfoView(label: label, insets: self.textInsets)
}
func createContentPresenter(forModel model: DemoCompoundMessageModel) -> MessageContentPresenterProtocol {
return DefaultMessageContentPresenter<DemoCompoundMessageModel, DateInfoView>(
message: model,
showBorder: true,
onBinding: { message, dateInfoView in
dateInfoView?.text = DemoDateMessageContentFactory.dateFormatter.string(from: message.date)
dateInfoView?.textColor = message.isIncoming ? .black : .white
}
)
}
func createLayoutProvider(forModel model: DemoCompoundMessageModel) -> MessageManualLayoutProviderProtocol {
let text = DemoDateMessageContentFactory.dateFormatter.string(from: model.date)
return TextMessageLayoutProvider(
text: text,
font: self.font,
textInsets: self.textInsets
)
}
func createMenuPresenter(forModel model: DemoCompoundMessageModel) -> ChatItemMenuPresenterProtocol? {
return nil
}
}
private final class DateInfoView: UIView {
private let label: UILabel
private let insets: UIEdgeInsets
init(label: UILabel, insets: UIEdgeInsets) {
self.label = label
self.insets = insets
super.init(frame: .zero)
self.addSubview(self.label)
self.backgroundColor = .clear
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func layoutSubviews() {
super.layoutSubviews()
self.label.frame = self.bounds.inset(by: self.insets).inset(by: self.safeAreaInsets)
}
var text: String? {
get { return self.label.text }
set { self.label.text = newValue }
}
var textColor: UIColor? {
get { return self.label.textColor }
set { self.label.textColor = newValue }
}
}
| mit | 31a5580edfdacef9a9a127737bbc3f3e | 35.066667 | 112 | 0.692897 | 4.855128 | false | false | false | false |
vector-im/vector-ios | RiotSwiftUI/Modules/Common/Theme/ThemePublisher.swift | 1 | 1580 | //
// Copyright 2021 New Vector Ltd
//
// 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 Combine
/// Provides the theme and theme updates to SwiftUI.
///
/// Replaces the old ThemeObserver. Riot app can push updates to this class
/// removing the dependency of this class on the `ThemeService`.
@available(iOS 14.0, *)
class ThemePublisher: ObservableObject {
private static var _shared: ThemePublisher? = nil
static var shared: ThemePublisher {
if _shared == nil {
configure(themeId: .light)
}
return _shared!
}
@Published private(set) var theme: ThemeSwiftUI
static func configure(themeId: ThemeIdentifier) {
_shared = ThemePublisher(themeId: themeId)
}
init(themeId: ThemeIdentifier) {
_theme = Published.init(initialValue: themeId.themeSwiftUI)
}
func republish(themeIdPublisher: AnyPublisher<ThemeIdentifier, Never>) {
themeIdPublisher
.map(\.themeSwiftUI)
.assign(to: &$theme)
}
}
| apache-2.0 | a0d93fe1c1a75f2cb000fb79a759c6f1 | 30.6 | 76 | 0.679747 | 4.438202 | false | false | false | false |
wangkai678/WKDouYuZB | WKDouYuZB/WKDouYuZB/Classes/Main/Controller/BaseViewController.swift | 1 | 1265 | //
// BaseViewController.swift
// WKDouYuZB
//
// Created by wangkai on 2017/5/31.
// Copyright ยฉ 2017ๅนด wk. All rights reserved.
//
import UIKit
class BaseViewController: UIViewController {
var contentView : UIView?
fileprivate lazy var animImageView : UIImageView = { [unowned self] in
let imageView = UIImageView(image: UIImage(named: "img_loading_1"))
imageView.center = self.view.center
imageView.animationImages = [UIImage(named: "img_loading_1")!,UIImage(named: "img_loading_2")!]
imageView.animationDuration = 0.5
imageView.animationRepeatCount = LONG_MAX
imageView.autoresizingMask = [.flexibleTopMargin,.flexibleBottomMargin,.flexibleLeftMargin,.flexibleRightMargin]
return imageView
}()
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
extension BaseViewController{
func setupUI(){
contentView?.isHidden = true
view.addSubview(animImageView)
animImageView.startAnimating()
view.backgroundColor = UIColor(r: 250, g: 250, b: 250)
}
func loadDataFinished(){
animImageView.stopAnimating()
animImageView.isHidden = true
contentView?.isHidden = false
}
}
| mit | ab19bbcef2fcedcdb0dcf6af38f87230 | 27.044444 | 120 | 0.663233 | 4.726592 | false | false | false | false |
fleurdeswift/data-structure | ExtraDataStructures/AtomicMax.swift | 1 | 1025 | //
// AtomicMax.swift
// ExtraDataStructures
//
// Copyright ยฉ 2015 Fleur de Swift. All rights reserved.
//
import Foundation
public func AtomicMax(inout left: CGFloat, _ right: CGFloat) -> CGFloat {
while true {
let initialValue = left;
let newValue = max(initialValue, right);
if (AtomicCompareAndSwap(initialValue, newValue, &left)) {
return newValue;
}
}
}
public func AtomicMax(inout left: Float, _ right: Float) -> Float {
while true {
let initialValue = left;
let newValue = max(initialValue, right);
if (AtomicCompareAndSwap(initialValue, newValue, &left)) {
return newValue;
}
}
}
public func AtomicMax(inout left: Double, _ right: Double) -> Double {
while true {
let initialValue = left;
let newValue = max(initialValue, right);
if (AtomicCompareAndSwap(initialValue, newValue, &left)) {
return newValue;
}
}
}
| mit | 8da2ce8f51015120a5f53dda4d792140 | 23.97561 | 73 | 0.586914 | 4.413793 | false | false | false | false |
lightbluefox/rcgapp | IOS App/RCGApp/RCGApp/VacancyFeedTableViewController.swift | 1 | 10280 | //
// VacancyFeedTableViewController.swift
// RCGApp
//
// Created by iFoxxy on 14.06.15.
// Copyright (c) 2015 LightBlueFox. All rights reserved.
//
import UIKit
class VacancyFeedTableViewController: UITableViewController {
@IBOutlet var vacancyFeedView: UITableView!
var itemsReceiver = NewsAndVacanciesReceiver()
override func viewDidLoad() {
super.viewDidLoad()
self.navigationItem.title = "ะะะะะะกะะ"
self.navigationController?.navigationBar.translucent = false;
self.vacancyFeedView.rowHeight = 80
//ะะฟะธััะฒะฐะตะผ ะฟัะป-ัั-ัะตััะตั
self.refreshControl = UIRefreshControl();
self.refreshControl?.attributedTitle = NSAttributedString(string: "ะะพััะฝะธัะต ะฒะฝะธะท, ััะพะฑั ะพะฑะฝะพะฒะธัั");
self.refreshControl?.addTarget(self, action: "refresh:", forControlEvents: UIControlEvents.ValueChanged)
//ะะพะปััะตะฝะธะต ะฒัะตั
ะฒะฐะบะฐะฝัะธะน
//MARK: ะธัะฟะพะปัะทัั MBProgressHUD ะดะตะปะฐะตะผ ัะบัะฐะฝ ะทะฐะณััะทะบะธ, ะฟะพะบะฐ ะฟะพะดะณััะถะฐัััั ะฒะฐะบะฐะฝัะธะธ
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.navigationController?.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.color = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 0.8);
loadingNotification.labelFont = UIFont(name: "Roboto Regular", size: 12)
loadingNotification.labelText = "ะะฐะณััะทะบะฐ..."
self.itemsReceiver.getAllVacancies({(success: Bool, result: String) in
if success {
loadingNotification.hide(true)
self.vacancyFeedView.reloadData()
}
else if !success
{
loadingNotification.hide(true)
let failureNotification = MBProgressHUD.showHUDAddedTo(self.navigationController?.view, animated: true)
failureNotification.mode = MBProgressHUDMode.Text
failureNotification.color = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 0.8);
failureNotification.labelFont = UIFont(name: "Roboto Regular", size: 12)
failureNotification.labelText = "ะัะธะฑะบะฐ!"
failureNotification.detailsLabelText = result
failureNotification.hide(true, afterDelay: 3)
self.vacancyFeedView.reloadData()
}
})
//
}
func refresh(sender:AnyObject) {
//MARK: ะธัะฟะพะปัะทัั MBProgressHUD ะดะตะปะฐะตะผ ัะบัะฐะฝ ะทะฐะณััะทะบะธ, ะฟะพะบะฐ ะฟะพะดะณััะถะฐัััั ะฝะพะฒะพััะธ
let loadingNotification = MBProgressHUD.showHUDAddedTo(self.navigationController?.view, animated: true)
loadingNotification.mode = MBProgressHUDMode.Indeterminate
loadingNotification.color = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 0.8);
loadingNotification.labelFont = UIFont(name: "Roboto Regular", size: 12)
loadingNotification.labelText = "ะะฐะณััะทะบะฐ..."
self.itemsReceiver.getAllNews({(success: Bool, result: String) in
if success {
loadingNotification.hide(true)
self.vacancyFeedView.reloadData()
}
else if !success
{
loadingNotification.hide(true)
let failureNotification = MBProgressHUD.showHUDAddedTo(self.navigationController?.view, animated: true)
failureNotification.mode = MBProgressHUDMode.Text
failureNotification.color = UIColor(red: 194/255, green: 0, blue: 18/255, alpha: 0.8);
failureNotification.labelFont = UIFont(name: "Roboto Regular", size: 12)
failureNotification.labelText = "ะัะธะฑะบะฐ!"
failureNotification.detailsLabelText = result
failureNotification.hide(true, afterDelay: 3)
self.vacancyFeedView.reloadData()
}
})
vacancyFeedView.reloadData();
self.refreshControl?.endRefreshing();
}
override func viewWillAppear(animated: Bool) {
vacancyFeedView.reloadData();
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Table view data source
//override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
// return 0
//}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
//println(itemsReceiver.newsStack.count);
return itemsReceiver.vacStack.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
//let cell = tableView.dequeueReusableCellWithIdentifier("NewsCell", forIndexPath: indexPath) as NewsCellViewController
let cell = self.vacancyFeedView.dequeueReusableCellWithIdentifier("VacancyCell") as! VacancyCellViewController
// Configure the cell...
let currentVac = itemsReceiver.vacStack[indexPath.row];
cell.cellVacTitle?.text = currentVac.title;
cell.cellVacDate?.text = currentVac.createdDate;
if currentVac.announceImageURL != ""
{
cell.cellVacAnnounceImage.sd_setImageWithURL(NSURL(string: currentVac.announceImageURL))
cell.cellVacAnnounceImage.layer.cornerRadius = 3.0
cell.cellVacAnnounceImage.layer.masksToBounds = true
}
else
{
cell.cellVacAnnounceImage.image = UIImage(named: "FullTextImage")!
cell.cellVacAnnounceImage.layer.cornerRadius = 3.0
cell.cellVacAnnounceImage.layer.masksToBounds = true
}
switch currentVac.gender {
case 0 : cell.cellVacFemaleImage?.image = UIImage(named: "femaleRed"); cell.cellVacMaleImage?.image = UIImage(named: "maleGray");
case 1 : cell.cellVacFemaleImage?.image = UIImage(named: "femaleGray"); cell.cellVacMaleImage?.image = UIImage(named: "maleRed");
case 2 : cell.cellVacFemaleImage?.image = UIImage(named: "femaleRed"); cell.cellVacMaleImage?.image = UIImage(named: "maleRed");
default : cell.cellVacFemaleImage?.image = UIImage(named: "femaleRed"); cell.cellVacMaleImage?.image = UIImage(named: "maleRed");
}
cell.cellVacAnnouncement?.text = currentVac.announcement;
cell.cellVacMoney?.text = currentVac.rate;
return cell
}
/*
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("reuseIdentifier", forIndexPath: indexPath) as UITableViewCell
// Configure the cell...
return cell
}
*/
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView, moveRowAtIndexPath fromIndexPath: NSIndexPath, toIndexPath: NSIndexPath) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView, canMoveRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using [segue destinationViewController].
var vacancyViewController = segue.destinationViewController as! VacancyViewController
// Pass the selected object to the new view controller.
let cell = sender as! VacancyCellViewController
var indexPath = self.vacancyFeedView.indexPathForCell(cell)
let currentVac = self.itemsReceiver.vacStack[indexPath!.row]
vacancyViewController.fullTextImageURL = currentVac.fullTextImageURL
vacancyViewController.heading = currentVac.title
vacancyViewController.announcement = currentVac.announcement
vacancyViewController.createdDate = currentVac.createdDate
vacancyViewController.rate = currentVac.rate
vacancyViewController.fullText = currentVac.fullText
vacancyViewController.vacancyId = currentVac.id
switch currentVac.gender {
case 0 : vacancyViewController.femaleImg = UIImage(named: "femaleRed"); vacancyViewController.maleImg = UIImage(named: "maleGray");
case 1 : vacancyViewController.femaleImg = UIImage(named: "femaleGray"); vacancyViewController.maleImg = UIImage(named: "maleRed");
case 2 : vacancyViewController.femaleImg = UIImage(named: "femaleRed"); vacancyViewController.maleImg = UIImage(named: "maleRed");
default : vacancyViewController.femaleImg = UIImage(named: "femaleRed"); vacancyViewController.maleImg = UIImage(named: "maleRed");
}
}
}
| gpl-2.0 | 80506d15bad5c83c47b2bf7fc1737418 | 45.860465 | 157 | 0.674839 | 4.71676 | false | false | false | false |
liuchuo/Swift-practice | 20150617-1.playground/Contents.swift | 1 | 1867 | //: Playground - noun: a place where people can play
import UIKit
//ๆไธพ - ๆๅๅผ
enum WeekDays {
case Monday
case Tuesday
case Wednsday
case Thursday
case Friday
}
var day = WeekDays.Friday
day = WeekDays.Wednsday
day = .Monday
func writeGreeting(day : WeekDays) {
switch day {
case .Monday :
println("ๆๆไธๅฅฝ~")
case .Tuesday :
println("ๆๆไบๅฅฝ~~")
case .Wednsday :
println("ๆๆไธๅฅฝ~~")
case .Thursday :
println("ๆๆๅๅฅฝ~~~")
case .Friday :
println("ๆๆไบๅฅฝ~~~~")
}
}
//ๅจswitch่ฏญๅฅไธญไฝฟ็จๆไธพ็ฑปๅๅฏไปฅๆฒกๆdefaultๅๆฏ๏ผ่ฟๅจๅ
ถไป็ฑปๅๆถๆฏไธๅ
่ฎธ็
writeGreeting(day)
writeGreeting(WeekDays.Friday)
ๆไธพ - ๅๅงๅผ
ๆไธพๅ+โ:โ+ๆฐๆฎ็ฑปๅ
enum WeekDays : Int {
case Monday = 0
case Tuesday = 1
case Wednsday = 2
case Thursday = 3
case Friday = 4
}
//enum WeekDays : Int {
// case Monday = 0,Tuesday,Wednsday,Thursday,Friday
//}
var day = WeekDays.Friday
func writeGreeting(day : WeekDays) {
switch day {
case .Monday :
println("ๆๆไธๅฅฝ~")
case .Tuesday :
println("ๆๆไบๅฅฝ~~")
case .Wednsday :
println("ๆๆไธๅฅฝ~~")
case .Thursday :
println("ๆๆๅๅฅฝ~~~")
case .Friday :
println("ๆๆไบๅฅฝ~~~~")
}
}
let friday = WeekDays.Friday.rawValue
if let thursday = WeekDays(rawValue : 3) {
println(thursday.rawValue)
}
if(WeekDays.Friday.rawValue == 4) {
println("ไปๅคฉๆฏๆๆไบ")
}
//toRaw()ๅฐๆๅๅผ่ฝฌๆขไธบๅๅงๅผ๏ผfromRaw()ๅฐๅๅงๅผ่ฝฌๆขไธบๆๅๅผ
//toRawๆนไธบ: let friday = WeekDays.Friday.rawValue(ๅๆๅ็ๅๅงๅผ)
//formRawๆนไธบ: let thursday = WeekDays(rawValue : 3)(ๅๅงๅไธบๆๆๅ็ๆๅๅผ)
writeGreeting(day)
writeGreeting(WeekDays.Friday)
| gpl-2.0 | 717d95add69c562cfa5c4e555c9e30e5 | 16.898876 | 63 | 0.627119 | 3.284536 | false | false | false | false |
Ryukie/Ryubo | Ryubo/Ryubo/Classes/View/Home/Cell/RYPicsView.swift | 1 | 3513 | //
// RYPicsView.swift
// Ryubo
//
// Created by ็่ฃๅบ on 16/2/19.
// Copyright ยฉ 2016ๅนด Ryukie. All rights reserved.
//
import UIKit
class RYPicsView: UICollectionView {
private let itemID = "picView"
var picURLs : [NSURL]? {
didSet {
layoutItems()
self.reloadData()
}
}
override init(frame: CGRect, collectionViewLayout layout: UICollectionViewLayout) {
flowLayout = UICollectionViewFlowLayout()//ไธๅฎ่ฆๆไธช้็ฉบ็ๅธๅฑๅฏน่ฑก
flowLayout!.minimumInteritemSpacing = picCellMargin
flowLayout!.minimumLineSpacing = picCellMargin
// let insert = UIEdgeInsets(top: 5, left: 0, bottom: 5, right: 5)
// flowLayout?.sectionInset = insert
super.init(frame: frame, collectionViewLayout: flowLayout!)
scrollEnabled = false
dataSource = self
registerClass(RYPictureCell.self, forCellWithReuseIdentifier: itemID)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private var flowLayout : UICollectionViewFlowLayout?
}
//========================================================
// MARK: - ๅธๅฑๅญๆงไปถ
extension RYPicsView {
private func layoutItems () {
//ๆ นๆฎๅพ็ๆฐ้ๅณๅฎไฝฟ็จไฝ็งๅพ็ๅธๅฑ
let num = picURLs?.count ?? 0
//ๆฒกๆ้
ๅพ่งๅพ
if num == 0 {
self.snp_updateConstraints { (make) -> Void in
make.size.equalTo(CGSizeZero)
}
return
}
if num == 1 {
setOnePicView()
return
}
if num == 4 {
setFourPicView()
return
}
let width = (scrWidth - picCellMargin*2 - margin*2)/3
let row = CGFloat((num-1)/3 + 1)
flowLayout!.itemSize = CGSize(width:width, height: width)
self.snp_updateConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: width*3 + 2*picCellMargin, height: width*row + picCellMargin*(row-1)))
}
}
private func setOnePicView () {
flowLayout!.itemSize = CGSize(width:180, height: 120)//้ฟ < ๅฎฝ
self.snp_updateConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: 180, height: 120))
}
}
private func setFourPicView () {
let width = (scrWidth*0.681 - picCellMargin - margin*2)/2
flowLayout!.itemSize = CGSize(width:width, height: width)
self.snp_updateConstraints { (make) -> Void in
make.size.equalTo(CGSize(width: 2*width + picCellMargin, height: width*2 + picCellMargin))
}
}
}
//========================================================
// MARK: - ๆฐๆฎๆบๆนๆณ
extension RYPicsView:UICollectionViewDataSource {
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
collectionView.collectionViewLayout.invalidateLayout()
return 1
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return picURLs?.count ?? 0
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let item = collectionView.dequeueReusableCellWithReuseIdentifier(itemID, forIndexPath: indexPath) as! RYPictureCell
item.backgroundColor = UIColor(white: 0.95, alpha: 1)
item.imageURL = picURLs![indexPath.item]
return item
}
}
| mit | 4433b3586be01187409a58529859d761 | 35.297872 | 130 | 0.609613 | 4.667579 | false | false | false | false |
HTWDD/HTWDresden-iOS | HTWDD/Core/UI/Views/BlurredSectionHeader.swift | 1 | 2370 | //
// BlurredSectionHeader.swift
// HTWDD
//
// Created by Mustafa Karademir on 19.07.19.
// Copyright ยฉ 2019 HTW Dresden. All rights reserved.
//
import Foundation
class BlurredSectionHeader: UIView {
// MARK: - Config
private enum Constant {
static let topSpace: CGFloat = 8
static let leadingSpace: CGFloat = 10
}
// MARK: - Blurred View
private lazy var wrapper: UIView = {
return UIView(frame: CGRect(x: 0, y: 0, width: self.bounds.width, height: 60)).also { wrapperView in
wrapperView.addSubview(UIVisualEffectView(effect: UIBlurEffect(style: .regular)).also { effectView in
effectView.frame = wrapperView.bounds
})
}
}()
// MARK: - Header & SubHeader
private lazy var header: UILabel = {
return UILabel().also {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.textColor = UIColor.htw.Label.primary
$0.font = UIFont.from(style: .big)
}
}()
private lazy var subHeader: UILabel = {
return UILabel().also {
$0.textColor = UIColor.htw.Label.secondary
$0.font = UIFont.from(style: .small)
}
}()
// MARK: - Lifecycle
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
init(frame: CGRect, header: String, subHeader: String) {
super.init(frame: frame)
self.header.text = header
self.subHeader.text = subHeader
setup()
}
// MARK: - Setup
private func setup() {
let vStack = UIStackView(arrangedSubviews: [header, subHeader]).also {
$0.translatesAutoresizingMaskIntoConstraints = false
$0.axis = .vertical
$0.distribution = .fill
$0.spacing = 2
}
wrapper.addSubview(vStack)
NSLayoutConstraint.activate([
vStack.leadingAnchor.constraint(equalTo: wrapper.leadingAnchor, constant: Constant.leadingSpace),
vStack.topAnchor.constraint(equalTo: wrapper.topAnchor, constant: Constant.topSpace)
])
addSubview(wrapper)
}
}
| gpl-2.0 | 27207f0973d9da62b52ac36273a9ffed | 29.371795 | 113 | 0.577459 | 4.564547 | false | false | false | false |
Punch-In/PunchInIOSApp | PunchIn/ClassNameCollectionViewCell.swift | 1 | 1125 | //
// ClassNameCollectionViewCell.swift
// PunchIn
//
// Created by Nilesh Agrawal on 10/31/15.
// Copyright ยฉ 2015 Nilesh Agrawal. All rights reserved.
//
import UIKit
class ClassNameCollectionViewCell: UICollectionViewCell {
@IBOutlet weak var className: UILabel!
@IBOutlet weak var classDescription: UILabel!
@IBOutlet weak var classDate: UILabel!
weak var displayClass: Class! {
didSet {
className.text = displayClass.name
classDescription.text = displayClass.classDescription
classDate.text = displayClass.dateString
}
}
func setUpclassCell(){
className.textColor = ThemeManager.theme().primaryDarkBlueColor()
//className.font = ThemeManager.theme().primaryTitleFont()
classDescription.textColor = ThemeManager.theme().primaryBlueColor()
//classDescription.font = ThemeManager.theme().primarySubTitleFont()
classDate.textColor = ThemeManager.theme().primaryGreyColor()
//classDescription.font = ThemeManager.theme().primarySubTitleFont()
}
}
| mit | a789ab28620466bfd20ef2731ebc22c3 | 29.378378 | 76 | 0.673488 | 5.063063 | false | false | false | false |
drewcrawford/DCAKit | DCAKit/UIKit Additions/ViewAdditions/View+Trees.swift | 1 | 1913 | //
// View+Contains.swift
// DCAKit
//
// Created by Drew Crawford on 11/22/14.
// Copyright (c) 2014 DrewCrawfordApps.
// This file is part of DCAKit. It is subject to the license terms in the LICENSE
// file found in the top level of this distribution and at
// https://github.com/drewcrawford/DCAKit/blob/master/LICENSE.
// No part of DCAKit, including this file, may be copied, modified,
// propagated, or distributed except according to the terms contained
// in the LICENSE file.
import UIKit
extension UIView {
/**A view contain search function. Returns true if the given view is a subview of the view (or any of its children) or false otherwise */
public func containsView(view: UIView) -> Bool {
//depth-first search
for searchView in self.subviews as! [UIView] {
if (searchView == view) {
return true
}
if (searchView.containsView(view)) { return true }
}
return false
}
/**A superview search function. Returns the first superview that matches the specified type.
If a superview cannot be found, returns nil.
:note: due to rdar://20256107, you must specify the return value in optional form (e.g. let k : UITableView! = foo.findSuperview()), rather than putting the exclamation mark on the findSuperview() call itself.
*/
public func findSuperview<T: AnyObject where T : UIView>() -> T? {
//work around rdar://20272689
if NSStringFromClass(self.dynamicType)==NSStringFromClass(T.self) {
//if self.dynamicType === T.self {
return (self as! T)
}
if self.superview == nil {
return nil
}
return self.superview!.findSuperview()
}
public func removeAllSubviews() {
for view in self.subviews as! [UIView] {
view.removeFromSuperview()
}
}
}
| mit | 84781c053e03167ae14eda8db84b636b | 36.509804 | 213 | 0.637219 | 4.270089 | false | false | false | false |
openbuild-sheffield/jolt | Sources/RouteCMS/model.CMSWords200Update.swift | 1 | 1895 | import OpenbuildExtensionPerfect
public class ModelCMSWords200Update: ResponseModel200EntityUpdated, DocumentationProtocol {
public var descriptions = [
"error": "An error has occurred, will always be false",
"message": "Will always be 'Successfully updated the entity.'",
"old": "Object describing the Words entity in it's original state.",
"updated": "Object describing the Words entity in it's updated state."
]
public init(old: ModelCMSWords, updated: ModelCMSWords) {
super.init(old: old, updated: updated)
}
public static func describeRAML() -> [String] {
if let docs = ResponseDocumentation.getRAML(key: "RouteCMS.ModelCMSWords200Update") {
return docs
} else {
let entityOld = ModelCMSWords(
cms_words_id: 1,
handle: "test",
words: "These are some words."
)
let entityUpdated = ModelCMSWords(
cms_words_id: 1,
handle: "test",
words: "These are some updated words."
)
let model = ModelCMSWords200Update(old: entityOld, updated: entityUpdated)
let aMirror = Mirror(reflecting: model)
let docs = ResponseDocumentation.genRAML(mirror: aMirror, descriptions: model.descriptions)
ResponseDocumentation.setRAML(key: "RouteCMS.ModelCMSWords200Update", lines: docs)
return docs
}
}
}
extension ModelCMSWords200Update: CustomReflectable {
open var customMirror: Mirror {
return Mirror(
self,
children: [
"error": self.error,
"message": self.message,
"old": self.old,
"updated": self.updated
],
displayStyle: Mirror.DisplayStyle.class
)
}
} | gpl-2.0 | 87bb3d49267ffffe1d61893bbef3222b | 28.169231 | 103 | 0.585224 | 4.785354 | false | false | false | false |
natecook1000/swift | stdlib/public/core/Pointer.swift | 2 | 13103 | //===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A stdlib-internal protocol modeled by the intrinsic pointer types,
/// UnsafeMutablePointer, UnsafePointer, UnsafeRawPointer,
/// UnsafeMutableRawPointer, and AutoreleasingUnsafeMutablePointer.
public protocol _Pointer
: Hashable, Strideable, CustomDebugStringConvertible, CustomReflectable {
/// A type that represents the distance between two pointers.
typealias Distance = Int
associatedtype Pointee
/// The underlying raw pointer value.
var _rawValue: Builtin.RawPointer { get }
/// Creates a pointer from a raw value.
init(_ _rawValue: Builtin.RawPointer)
}
extension _Pointer {
/// Creates a new typed pointer from the given opaque pointer.
///
/// - Parameter from: The opaque pointer to convert to a typed pointer.
@_transparent
public init(_ from : OpaquePointer) {
self.init(from._rawValue)
}
/// Creates a new typed pointer from the given opaque pointer.
///
/// - Parameter from: The opaque pointer to convert to a typed pointer. If
/// `from` is `nil`, the result of this initializer is `nil`.
@_transparent
public init?(_ from : OpaquePointer?) {
guard let unwrapped = from else { return nil }
self.init(unwrapped)
}
/// Creates a new pointer from the given address, specified as a bit
/// pattern.
///
/// The address passed as `bitPattern` must have the correct alignment for
/// the pointer's `Pointee` type. That is,
/// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`.
///
/// - Parameter bitPattern: A bit pattern to use for the address of the new
/// pointer. If `bitPattern` is zero, the result is `nil`.
@_transparent
public init?(bitPattern: Int) {
if bitPattern == 0 { return nil }
self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue))
}
/// Creates a new pointer from the given address, specified as a bit
/// pattern.
///
/// The address passed as `bitPattern` must have the correct alignment for
/// the pointer's `Pointee` type. That is,
/// `bitPattern % MemoryLayout<Pointee>.alignment` must be `0`.
///
/// - Parameter bitPattern: A bit pattern to use for the address of the new
/// pointer. If `bitPattern` is zero, the result is `nil`.
@_transparent
public init?(bitPattern: UInt) {
if bitPattern == 0 { return nil }
self.init(Builtin.inttoptr_Word(bitPattern._builtinWordValue))
}
/// Creates a new pointer from the given pointer.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init(_ other: Self) {
self.init(other._rawValue)
}
/// Creates a new pointer from the given pointer.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?(_ other: Self?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped._rawValue)
}
// all pointers are creatable from mutable pointers
/// Creates a new pointer from the given mutable pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert.
@_transparent
public init<T>(_ other: UnsafeMutablePointer<T>) {
self.init(other._rawValue)
}
/// Creates a new raw pointer from the given typed pointer.
///
/// Use this initializer to explicitly convert `other` to an `UnsafeRawPointer`
/// instance. This initializer creates a new pointer to the same address as
/// `other` and performs no allocation or copying.
///
/// - Parameter other: The typed pointer to convert. If `other` is `nil`, the
/// result is `nil`.
@_transparent
public init?<T>(_ other: UnsafeMutablePointer<T>?) {
guard let unwrapped = other else { return nil }
self.init(unwrapped)
}
}
// well, this is pretty annoying
extension _Pointer /*: Equatable */ {
// - Note: This may be more efficient than Strideable's implementation
// calling self.distance().
/// Returns a Boolean value indicating whether two pointers are equal.
///
/// - Parameters:
/// - lhs: A pointer.
/// - rhs: Another pointer.
/// - Returns: `true` if `lhs` and `rhs` reference the same memory address;
/// otherwise, `false`.
@_transparent
public static func == (lhs: Self, rhs: Self) -> Bool {
return Bool(Builtin.cmp_eq_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension _Pointer /*: Comparable */ {
// - Note: This is an unsigned comparison unlike Strideable's
// implementation.
/// Returns a Boolean value indicating whether the first pointer references
/// an earlier memory location than the second pointer.
///
/// - Parameters:
/// - lhs: A pointer.
/// - rhs: Another pointer.
/// - Returns: `true` if `lhs` references a memory address earlier than
/// `rhs`; otherwise, `false`.
@_transparent
public static func < (lhs: Self, rhs: Self) -> Bool {
return Bool(Builtin.cmp_ult_RawPointer(lhs._rawValue, rhs._rawValue))
}
}
extension _Pointer /*: Strideable*/ {
/// Returns a pointer to the next consecutive instance.
///
/// The resulting pointer must be within the bounds of the same allocation as
/// this pointer.
///
/// - Returns: A pointer advanced from this pointer by
/// `MemoryLayout<Pointee>.stride` bytes.
@inlinable
public func successor() -> Self {
return advanced(by: 1)
}
/// Returns a pointer to the previous consecutive instance.
///
/// The resulting pointer must be within the bounds of the same allocation as
/// this pointer.
///
/// - Returns: A pointer shifted backward from this pointer by
/// `MemoryLayout<Pointee>.stride` bytes.
@inlinable
public func predecessor() -> Self {
return advanced(by: -1)
}
/// Returns the distance from this pointer to the given pointer, counted as
/// instances of the pointer's `Pointee` type.
///
/// With pointers `p` and `q`, the result of `p.distance(to: q)` is
/// equivalent to `q - p`.
///
/// Typed pointers are required to be properly aligned for their `Pointee`
/// type. Proper alignment ensures that the result of `distance(to:)`
/// accurately measures the distance between the two pointers, counted in
/// strides of `Pointee`. To find the distance in bytes between two
/// pointers, convert them to `UnsafeRawPointer` instances before calling
/// `distance(to:)`.
///
/// - Parameter end: The pointer to calculate the distance to.
/// - Returns: The distance from this pointer to `end`, in strides of the
/// pointer's `Pointee` type. To access the stride, use
/// `MemoryLayout<Pointee>.stride`.
@inlinable
public func distance(to end: Self) -> Int {
return
Int(Builtin.sub_Word(Builtin.ptrtoint_Word(end._rawValue),
Builtin.ptrtoint_Word(_rawValue)))
/ MemoryLayout<Pointee>.stride
}
/// Returns a pointer offset from this pointer by the specified number of
/// instances.
///
/// With pointer `p` and distance `n`, the result of `p.advanced(by: n)` is
/// equivalent to `p + n`.
///
/// The resulting pointer must be within the bounds of the same allocation as
/// this pointer.
///
/// - Parameter n: The number of strides of the pointer's `Pointee` type to
/// offset this pointer. To access the stride, use
/// `MemoryLayout<Pointee>.stride`. `n` may be positive, negative, or
/// zero.
/// - Returns: A pointer offset from this pointer by `n` instances of the
/// `Pointee` type.
@inlinable
public func advanced(by n: Int) -> Self {
return Self(Builtin.gep_Word(
self._rawValue, n._builtinWordValue, Pointee.self))
}
}
extension _Pointer /*: Hashable */ {
@inlinable
public func hash(into hasher: inout Hasher) {
hasher.combine(UInt(bitPattern: self))
}
@inlinable
public func _rawHashValue(seed: (UInt64, UInt64)) -> Int {
return Hasher._hash(seed: seed, UInt(bitPattern: self))
}
}
extension _Pointer /*: CustomDebugStringConvertible */ {
/// A textual representation of the pointer, suitable for debugging.
public var debugDescription: String {
return _rawPointerToString(_rawValue)
}
}
extension _Pointer /*: CustomReflectable */ {
public var customMirror: Mirror {
let ptrValue = UInt64(
bitPattern: Int64(Int(Builtin.ptrtoint_Word(_rawValue))))
return Mirror(self, children: ["pointerValue": ptrValue])
}
}
extension Int {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable
public init<P: _Pointer>(bitPattern pointer: P?) {
if let pointer = pointer {
self = Int(Builtin.ptrtoint_Word(pointer._rawValue))
} else {
self = 0
}
}
}
extension UInt {
/// Creates a new value with the bit pattern of the given pointer.
///
/// The new value represents the address of the pointer passed as `pointer`.
/// If `pointer` is `nil`, the result is `0`.
///
/// - Parameter pointer: The pointer to use as the source for the new
/// integer.
@inlinable
public init<P: _Pointer>(bitPattern pointer: P?) {
if let pointer = pointer {
self = UInt(Builtin.ptrtoint_Word(pointer._rawValue))
} else {
self = 0
}
}
}
// Pointer arithmetic operators (formerly via Strideable)
extension Strideable where Self : _Pointer {
@_transparent
public static func + (lhs: Self, rhs: Self.Stride) -> Self {
return lhs.advanced(by: rhs)
}
@_transparent
public static func + (lhs: Self.Stride, rhs: Self) -> Self {
return rhs.advanced(by: lhs)
}
@_transparent
public static func - (lhs: Self, rhs: Self.Stride) -> Self {
return lhs.advanced(by: -rhs)
}
@_transparent
public static func - (lhs: Self, rhs: Self) -> Self.Stride {
return rhs.distance(to: lhs)
}
@_transparent
public static func += (lhs: inout Self, rhs: Self.Stride) {
lhs = lhs.advanced(by: rhs)
}
@_transparent
public static func -= (lhs: inout Self, rhs: Self.Stride) {
lhs = lhs.advanced(by: -rhs)
}
}
/// Derive a pointer argument from a convertible pointer type.
@_transparent
public // COMPILER_INTRINSIC
func _convertPointerToPointerArgument<
FromPointer : _Pointer,
ToPointer : _Pointer
>(_ from: FromPointer) -> ToPointer {
return ToPointer(from._rawValue)
}
/// Derive a pointer argument from the address of an inout parameter.
@_transparent
public // COMPILER_INTRINSIC
func _convertInOutToPointerArgument<
ToPointer : _Pointer
>(_ from: Builtin.RawPointer) -> ToPointer {
return ToPointer(from)
}
/// Derive a pointer argument from a value array parameter.
///
/// This always produces a non-null pointer, even if the array doesn't have any
/// storage.
@_transparent
public // COMPILER_INTRINSIC
func _convertConstArrayToPointerArgument<
FromElement,
ToPointer: _Pointer
>(_ arr: [FromElement]) -> (AnyObject?, ToPointer) {
let (owner, opaquePointer) = arr._cPointerArgs()
let validPointer: ToPointer
if let addr = opaquePointer {
validPointer = ToPointer(addr._rawValue)
} else {
let lastAlignedValue = ~(MemoryLayout<FromElement>.alignment - 1)
let lastAlignedPointer = UnsafeRawPointer(bitPattern: lastAlignedValue)!
validPointer = ToPointer(lastAlignedPointer._rawValue)
}
return (owner, validPointer)
}
/// Derive a pointer argument from an inout array parameter.
///
/// This always produces a non-null pointer, even if the array's length is 0.
@_transparent
public // COMPILER_INTRINSIC
func _convertMutableArrayToPointerArgument<
FromElement,
ToPointer : _Pointer
>(_ a: inout [FromElement]) -> (AnyObject?, ToPointer) {
// TODO: Putting a canary at the end of the array in checked builds might
// be a good idea
// Call reserve to force contiguous storage.
a.reserveCapacity(0)
_debugPrecondition(a._baseAddressIfContiguous != nil || a.isEmpty)
return _convertConstArrayToPointerArgument(a)
}
/// Derive a UTF-8 pointer argument from a value string parameter.
@inlinable // FIXME(sil-serialize-all)
public // COMPILER_INTRINSIC
func _convertConstStringToUTF8PointerArgument<
ToPointer : _Pointer
>(_ str: String) -> (AnyObject?, ToPointer) {
let utf8 = Array(str.utf8CString)
return _convertConstArrayToPointerArgument(utf8)
}
| apache-2.0 | df2fa84aadeee75cc2c57a9e7f088e83 | 32.005038 | 81 | 0.672212 | 4.241826 | false | false | false | false |
dclelland/AudioKit | AudioKit/iOS/AudioKit/AudioKit.playground/Pages/AutoWah Operation.xcplaygroundpage/Contents.swift | 1 | 725 | //: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
//:
//: ---
//:
//: ## AutoWah Operation
//:
import XCPlayground
import AudioKit
let bundle = NSBundle.mainBundle()
let file = bundle.pathForResource("guitarloop", ofType: "wav")
var player = AKAudioPlayer(file!)
player.looping = true
let wahAmount = AKOperation.sineWave(frequency: 0.6).scale(minimum: 1, maximum: 0)
let autowah = AKOperation.input.autoWah(wah: wahAmount, mix: 1, amplitude: 1)
let effect = AKOperationEffect(player, operation: autowah)
AudioKit.output = effect
AudioKit.start()
player.play()
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
//: [TOC](Table%20Of%20Contents) | [Previous](@previous) | [Next](@next)
| mit | bc8d567e035c9c8ba78884f7fd032544 | 26.884615 | 82 | 0.724138 | 3.452381 | false | false | false | false |
AlucarDWeb/Weather | Weather/controller/TodayUIViewController.swift | 1 | 1737 | //
// TodayUIViewController.swift
// Weather
//
//
// Copyright ยฉ 2017 Ferdinando Furci. All rights reserved.
//
import UIKit
import CoreLocation
class TodayUIViewController: BaseViewController {
@IBOutlet weak var weatherImageView: UIImageView!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var weatherLabel: UILabel!
@IBOutlet weak var directionLabel: UILabel!
@IBOutlet weak var windLabel: UILabel!
@IBOutlet weak var pressureLabel: UILabel!
@IBOutlet weak var rainMmLabel: UILabel!
@IBOutlet weak var rainPercentageLabel: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
func updateUI() {
guard let viewModel = todayViewModel else {
return
}
weatherImageView.image = viewModel.WeatherConditionImage
locationLabel.attributedText = viewModel.locationText
weatherLabel.text = viewModel.weatherPrimaryLabelText
directionLabel.text = viewModel.directionText
windLabel.text = viewModel.windText
pressureLabel.text = viewModel.pressureText
rainPercentageLabel.text = viewModel.rainPercentageText
rainMmLabel.text = viewModel.rainMM
}
override func viewDidAppear(_ animated: Bool) {
self.navigationController?.navigationBar.topItem?.title = "Today".localized
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | f1a6c9acfbe3100c9ca775c9a2d0e30a | 20.432099 | 83 | 0.614631 | 5.636364 | false | false | false | false |
weiss19ja/LocalizableUI | LocalizableUI Example/CustomView.swift | 1 | 1355 | //
// CustomView.swift
// LocalizableUI Example
//
// Created by Philipp Weiร on 23.10.17.
// Copyright ยฉ 2017 Jan Weiร, Philipp Weiร. All rights reserved.
//
import UIKit
import LocalizableUI
private enum Constants {
static let titleStringID = "example-customView-label"
}
/// Implementation of a custom view.
/// This file shows how to implement the Localizable protocol and how to add it to the LocalizationManager
class CustomView: UIView {
/// Label where the text is manual organized
let label = UILabel(frame: CGRect(x: 0, y: 50, width: 300, height: 50))
/// Label where the text is organized by the Localizable Property
lazy var labelOrganized: UILabel = {
let newLabel = UILabel(frame: CGRect(x: 0, y: 150, width: 300, height: 50))
newLabel.localizedKey = Constants.titleStringID
return newLabel
}()
required init(coder: NSCoder) {
super.init(coder: coder)!
setupView()
}
func setupView() {
// add subviews
addSubview(label)
addSubview(labelOrganized)
// add new Localizable to the manager
addToManager()
}
}
// MARK: - Implement Localizable
extension CustomView: Localizable {
func updateLocalizedStrings() {
label.text = LocalizationManager.localizedStringFor(Constants.titleStringID)
}
}
| mit | 672804226306b43b0412adeb5b06e40a | 24.980769 | 106 | 0.674315 | 4.330128 | false | false | false | false |
casd82/powerup-iOS | Powerup/MiniGameViewController.swift | 2 | 2698 | import UIKit
import SpriteKit
enum MiniGameIndex: Int {
case unknown = 0
case minesweeper = -1
case sinkToSwim = -2
case vocabMatching = -3
}
class MiniGameViewController: UIViewController,SegueHandler {
enum SegueIdentifier: String {
case toResultSceneView = "toResultScene"
}
// MARK: Properties
var completedScenarioID: Int = -1
// Keep a reference of the background image so that result scene could use it. (This is being assigned by ScenarioViewController).
var scenarioBackgroundImage: UIImage? = nil
var scenarioName: String = ""
// Will be assigned in the previous VC (ScenarioViewController).
var gameIndex: MiniGameIndex = .unknown
// Score of the played minigame (will be used to update karma points)
var score: Int = 0
// MARK: Functions
override func viewDidLoad() {
super.viewDidLoad()
var gameScene: SKScene!
let skView = view as! SKView
// Determine which mini game to load.
switch (gameIndex) {
// Mine Sweeper
case .minesweeper:
let minesweeperGame = MinesweeperGameScene(size: view.bounds.size)
minesweeperGame.viewController = self
gameScene = minesweeperGame
// Vocab Matching
case .vocabMatching:
let vocabMatchingGame = VocabMatchingGameScene(size: view.bounds.size)
vocabMatchingGame.viewController = self
gameScene = vocabMatchingGame
// Sink to Swim Game
case .sinkToSwim:
let sinkToSwimGame = SinkToSwimGameScene(size: view.bounds.size)
sinkToSwimGame.viewController = self
gameScene = sinkToSwimGame
default:
print("Unknown mini game.")
}
gameScene.scaleMode = .resizeFill
skView.ignoresSiblingOrder = true
skView.presentScene(gameScene)
}
// Hide status bar.
override var prefersStatusBarHidden: Bool {
return true
}
// Called by the mini game.
func endGame() {
performSegueWithIdentifier(.toResultSceneView, sender: self)
}
// MARK: Segues
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if let resultVC = segue.destination as? ResultsViewController {
resultVC.completedScenarioID = completedScenarioID
resultVC.completedScenarioName = scenarioName
resultVC.karmaGain = 20 + score
}
}
@IBAction func unwindToMiniGame(unwindSegue: UIStoryboardSegue) {
// Reset mini game
}
}
| gpl-2.0 | 864c35a17d7aea676379a9f5462b0647 | 29.659091 | 134 | 0.623054 | 4.887681 | false | false | false | false |
aryshin2016/swfWeibo | WeiBoSwift/WeiBoSwift/Classes/SwiftClass/RootTabBarController.swift | 1 | 4337 | //
// RootTabBarController.swift
// WeiBoSwift
//
// Created by itogame on 2017/8/15.
// Copyright ยฉ 2017ๅนด itogame. All rights reserved.
//
import UIKit
class RootTabBarController: UITabBarController {
@objc lazy var plusBtn:UIButton = {
let plusBtn = UIButton(imageName: "tabbar_compose_icon_add", backgroundImageName: "tabbar_compose_button", titleText: nil)
plusBtn.addTarget(self, action: #selector(plusClicked(btn:)), for: UIControlEvents.touchUpInside)
return plusBtn
}()
override func viewDidLoad() {
super.viewDidLoad()
tabBar.backgroundImage = UIImage(named: "tabbar_background")
tabBar.backgroundColor = UIColor(white: 1.0, alpha: 0.95)
// ่ฎพ็ฝฎ้ป่ฎค็้ป่ฒ๏ผไธๅ็ฐ๏ผ
UITabBarItem.appearance().setTitleTextAttributes([NSAttributedStringKey.foregroundColor : UIColor.black], for: UIControlState.normal)
// ๅๅงๅUI.
setupUI()
// ่ฎพ็ฝฎไปฃ็๏ผ็ๅฌtabbarItem็็นๅป่ทณ่ฝฌ
delegate = self
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
/* ๆขๆไบๅจไปฃ็ไธญๆงๅถ
// ็ฆๆญขไธญ้ดitem็็นๅป-ๅฆๆๅๅจviewWillAppearไธญๆbug๏ผๅๆขๅคๆฌกๅๅฏผ่ด"ๆถๆฏ"ไธ่ฝ็นๅป
//tabBar.subviews[3].isUserInteractionEnabled = false
*/
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
tabBar.tintColor = UIColor.black
// tabbar็ไธญ้ดโๆ้ฎ
creatThePlusBtn()
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
// ่ฐๆดไธญ้ดโๆ้ฎ็ไฝ็ฝฎ
// ๏ผbug๏ผๅฐฑ็ฎ่ฆ็ไธญ้ดitem็ไฝ็ฝฎ๏ผๅด่ฟๆฏๅจๅณไพงๅฏไปฅ็นๅปๅพๅฐ
self.plusBtn.center.x = self.tabBar.bounds.width * CGFloat(0.5)
}
// MARK: - UI็ธๅ
ณ
private func setupUI() -> () {
//
let weiboVC = WeiboTableViewController()
self.creatOneChildVC(title: "ๅพฎๅ", VC: weiboVC, imageName: "tabbar_home")
//
let msgVC = MsgTableViewController()
self.creatOneChildVC(title: "ๆถๆฏ", VC: msgVC, imageName: "tabbar_message_center")
//
let none = UIViewController()
none.view.backgroundColor = UIColor.clear
self.creatOneChildVC(title: "", VC: none, imageName: "")
//
let disVC = DisTableViewController(style:UITableViewStyle.plain)
self.creatOneChildVC(title: "ๅ็ฐ", VC: disVC, imageName: "tabbar_discover")
//
let meVC = MeTableViewController()
self.creatOneChildVC(title: "ๆ", VC: meVC, imageName: "tabbar_profile")
}
/// ๅๅปบๅญๆงๅถๅจ
private func creatOneChildVC(title:String, VC:UIViewController, imageName:String) ->(){
VC.title = title
// ่ฎพ็ฝฎๅพๆ ไธๆธฒๆ๏ผไธๅ็ฐ๏ผ
VC.tabBarItem.image = UIImage(named: imageName)?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
VC.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.withRenderingMode(UIImageRenderingMode.alwaysOriginal)
self.addChildViewController(RootNavController(rootViewController: VC))
}
/// ๆทปๅ ไธญ้จโๆ้ฎ
private func creatThePlusBtn() -> (){
tabBar.addSubview(plusBtn)
}
@objc private func plusClicked(btn:UIButton) -> (){
let plusVC = PluseViewController()
// ่ฟๆ ทๆ่ฝ้ฎไฝtabbar
plusVC.view.frame = UIScreen.main.bounds
// MARK: ่ฟๆ ท่ฎพ็ฝฎ-ไธปๅจpresentๆงๅถๅจ็viewไธๆถๅคฑ๏ผๆๅฉไบๅฎ็ฐ่ๆฏ็ฉฟ้ๆๆ
plusVC.modalPresentationStyle = UIModalPresentationStyle.overCurrentContext
present(plusVC, animated: false, completion: {() ->() in
ASLog("")
})
}
}
/// MARK : - UITabBarControllerDelegate
extension RootTabBarController : UITabBarControllerDelegate {
func tabBarController(_ tabBarController: UITabBarController, shouldSelect viewController: UIViewController) -> Bool {
// ็ฆๆญขไธญ้ดitem็็นๅปๅๆข
if viewController.isEqual(tabBarController.childViewControllers[2]) {
ASLog(viewController)
return false
}else {
return true
}
}
}
| mit | e4433a3b659a4b16539eff22f39c6f8c | 33.310345 | 141 | 0.644221 | 4.373626 | false | false | false | false |
iKyle/DraggableFloatingViewController | YouTubeDraggableVideo/Demo/FirstViewController.swift | 2 | 1321 | //
// FirstViewController.swift
// YouTubeDraggableVideo
//
// Created by Takuya Okamoto on 2015/05/28.
// Copyright (c) 2015ๅนด Sandeep Mukherjee. All rights reserved.
//
import UIKit
class FirstViewController: UIViewController {
override func viewDidLoad() {
self.view.backgroundColor = UIColor.whiteColor()
let btn = UIButton()
btn.frame = CGRect(x: 10, y: 10, width: 100, height: 100)
btn.backgroundColor = UIColor.redColor()
btn.addTarget(self, action: "onTapShowButton", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(btn)
let dismissBtn = UIButton()
dismissBtn.frame = CGRect(x: 150, y: 150, width: 100, height: 100)
dismissBtn.backgroundColor = UIColor.greenColor()
dismissBtn.addTarget(self, action: "onTapShowSecondVCButton", forControlEvents: UIControlEvents.TouchUpInside)
self.view.addSubview(dismissBtn)
}
func onTapShowButton() {
// AppDelegate.videoController().show()//๐
// AppDelegate.video
}
func onTapShowSecondVCButton() {
// AppDelegate.videoController().bringToFront()
let secondVC = SecondViewController()
self.presentViewController(secondVC, animated: true, completion: nil)
}
} | mit | 0579f583bf1d67009b26ee8cbede07d0 | 30.357143 | 118 | 0.666413 | 4.461017 | false | false | false | false |
IamDrizzle/CPSC491-2-test | SwiftHTTP-master/Request.swift | 6 | 11520 | //
// Request.swift
// SwiftHTTP
//
// Created by Dalton Cherry on 8/16/15.
// Copyright ยฉ 2015 vluxe. All rights reserved.
//
import Foundation
extension String {
/**
A simple extension to the String object to encode it for web request.
:returns: Encoded version of of string it was called as.
*/
var escaped: String? {
return self.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())
}
}
/**
The standard HTTP Verbs
*/
public enum HTTPVerb: String {
case GET = "GET"
case POST = "POST"
case PUT = "PUT"
case HEAD = "HEAD"
case DELETE = "DELETE"
case PATCH = "PATCH"
case OPTIONS = "OPTIONS"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
case UNKNOWN = "UNKNOWN"
}
/**
This is used to create key/value pairs of the parameters
*/
public struct HTTPPair {
var key: String?
let storeVal: AnyObject
/**
Create the object with a possible key and a value
*/
init(key: String?, value: AnyObject) {
self.key = key
self.storeVal = value
}
/**
Computed property of the string representation of the storedVal
*/
var upload: Upload? {
return storeVal as? Upload
}
/**
Computed property of the string representation of the storedVal
*/
var value: String {
if let v = storeVal as? String {
return v
} else if let v = storeVal.description {
return v
}
return ""
}
/**
Computed property of the string representation of the storedVal escaped for URLs
*/
var escapedValue: String {
if let v = value.escaped {
if let k = key {
if let escapedKey = k.escaped {
return "\(escapedKey)=\(v)"
}
}
return v
}
return ""
}
}
/**
Enum used to describe what kind of Parameter is being interacted with.
This allows us to only support an Array or Dictionary and avoid having to use AnyObject
*/
public enum HTTPParamType {
case Array
case Dictionary
case Upload
}
/**
This protocol is used to make the dictionary and array serializable into key/value pairs.
*/
public protocol HTTPParameterProtocol {
func paramType() -> HTTPParamType
func createPairs(key: String?) -> Array<HTTPPair>
}
/**
Support for the Dictionary type as an HTTPParameter.
*/
extension Dictionary: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .Dictionary
}
public func createPairs(key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
for (k, v) in self {
if let nestedKey = k as? String, let nestedVal = v as? AnyObject {
let useKey = key != nil ? "\(key!)[\(nestedKey)]" : nestedKey
if let subParam = v as? HTTPParameterProtocol {
collect.appendContentsOf(subParam.createPairs(useKey))
} else {
collect.append(HTTPPair(key: useKey, value: nestedVal))
}
}
}
return collect
}
}
/**
Support for the Array type as an HTTPParameter.
*/
extension Array: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .Array
}
public func createPairs(key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
for v in self {
if let nestedVal = v as? AnyObject {
if let subParam = v as? HTTPParameterProtocol {
collect.appendContentsOf(subParam.createPairs(key != nil ? "\(key!)[]" : key))
} else {
collect.append(HTTPPair(key: key, value: nestedVal))
}
}
}
return collect
}
}
/**
Support for the Upload type as an HTTPParameter.
*/
extension Upload: HTTPParameterProtocol {
public func paramType() -> HTTPParamType {
return .Upload
}
public func createPairs(key: String?) -> Array<HTTPPair> {
var collect = Array<HTTPPair>()
collect.append(HTTPPair(key: key, value: self))
return collect
}
}
/**
Adds convenience methods to NSMutableURLRequest to make using it with HTTP much simpler.
*/
extension NSMutableURLRequest {
/**
Convenience init to allow init with a string.
-parameter urlString: The string representation of a URL to init with.
*/
public convenience init?(urlString: String) {
if let url = NSURL(string: urlString) {
self.init(URL: url)
} else {
return nil
}
}
/**
Convenience method to avoid having to use strings and allow using an enum
*/
public var verb: HTTPVerb {
set {
HTTPMethod = newValue.rawValue
}
get {
if let v = HTTPVerb(rawValue: HTTPMethod) {
return v
}
return .UNKNOWN
}
}
/**
Used to update the content type in the HTTP header as needed
*/
var contentTypeKey: String {
return "Content-Type"
}
/**
append the parameters using the standard HTTP Query model.
This is parameters in the query string of the url (e.g. ?first=one&second=two for GET, HEAD, DELETE.
It uses 'application/x-www-form-urlencoded' for the content type of POST/PUT requests that don't contains files.
If it contains a file it uses `multipart/form-data` for the content type.
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
public func appendParameters(parameters: HTTPParameterProtocol) throws {
if isURIParam() {
appendParametersAsQueryString(parameters)
} else if containsFile(parameters) {
try appendParametersAsMultiPartFormData(parameters)
} else {
appendParametersAsUrlEncoding(parameters)
}
}
/**
append the parameters as a HTTP Query string. (e.g. domain.com?first=one&second=two)
-parameter parameters: The container (array or dictionary) to convert and append to the URL
*/
public func appendParametersAsQueryString(parameters: HTTPParameterProtocol) {
let queryString = parameters.createPairs(nil).map({ (pair) in
return pair.escapedValue
}).joinWithSeparator("&")
if let u = self.URL where queryString.characters.count > 0 {
let para = u.query != nil ? "&" : "?"
self.URL = NSURL(string: "\(u.absoluteString)\(para)\(queryString)")
}
}
/**
append the parameters as a url encoded string. (e.g. in the body of the request as: first=one&second=two)
-parameter parameters: The container (array or dictionary) to convert and append to the HTTP body
*/
public func appendParametersAsUrlEncoding(parameters: HTTPParameterProtocol) {
if valueForHTTPHeaderField(contentTypeKey) == nil {
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))
setValue("application/x-www-form-urlencoded; charset=\(charset)",
forHTTPHeaderField:contentTypeKey)
}
let queryString = parameters.createPairs(nil).map({ (pair) in
return pair.escapedValue
}).joinWithSeparator("&")
HTTPBody = queryString.dataUsingEncoding(NSUTF8StringEncoding)
}
/**
append the parameters as a multpart form body. This is the type normally used for file uploads.
-parameter parameters: The container (array or dictionary) to convert and append to the HTTP body
*/
public func appendParametersAsMultiPartFormData(parameters: HTTPParameterProtocol) throws {
let boundary = "Boundary+\(arc4random())\(arc4random())"
if valueForHTTPHeaderField(contentTypeKey) == nil {
setValue("multipart/form-data; boundary=\(boundary)",
forHTTPHeaderField:contentTypeKey)
}
let mutData = NSMutableData()
let multiCRLF = "\r\n"
mutData.appendData("--\(boundary)".dataUsingEncoding(NSUTF8StringEncoding)!)
print("--\(boundary)")
for pair in parameters.createPairs(nil) {
guard let key = pair.key else { continue } //this won't happen, but just to properly unwrap
mutData.appendData("\(multiCRLF)".dataUsingEncoding(NSUTF8StringEncoding)!)
print("\(multiCRLF)")
if let upload = pair.upload {
let data = try upload.getData()
mutData.appendData(multiFormHeader(key, fileName: upload.fileName,
type: upload.mimeType, multiCRLF: multiCRLF).dataUsingEncoding(NSUTF8StringEncoding)!)
mutData.appendData(data)
} else {
let str = "\(multiFormHeader(key, fileName: nil, type: nil, multiCRLF: multiCRLF))\(pair.value)"
mutData.appendData(str.dataUsingEncoding(NSUTF8StringEncoding)!)
}
mutData.appendData("\(multiCRLF)--\(boundary)".dataUsingEncoding(NSUTF8StringEncoding)!)
print("\(multiCRLF)--\(boundary)")
}
mutData.appendData("--\(multiCRLF)".dataUsingEncoding(NSUTF8StringEncoding)!)
print("--\(multiCRLF)")
HTTPBody = mutData
}
/**
Helper method to create the multipart form data
*/
func multiFormHeader(name: String, fileName: String?, type: String?, multiCRLF: String) -> String {
var str = "Content-Disposition: form-data; name=\"\(name.escaped!)\""
if let name = fileName {
str += "; filename=\"\(name)\""
}
str += multiCRLF
if let t = type {
str += "Content-Type: \(t)\(multiCRLF)"
}
str += multiCRLF
print("\(str)")
return str
}
/**
send the parameters as a body of JSON
-parameter parameters: The container (array or dictionary) to convert and append to the URL or Body
*/
public func appendParametersAsJSON(parameters: HTTPParameterProtocol) throws {
if isURIParam() {
appendParametersAsQueryString(parameters)
} else {
do {
HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters as! AnyObject, options: NSJSONWritingOptions())
} catch let error {
throw error
}
let charset = CFStringConvertEncodingToIANACharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding));
setValue("application/json; charset=\(charset)", forHTTPHeaderField: contentTypeKey)
}
}
/**
Check if the request requires the parameters to be appended to the URL
*/
public func isURIParam() -> Bool {
if verb == .GET || verb == .HEAD || verb == .DELETE {
return true
}
return false
}
/**
check if the parameters contain a file object within them
-parameter parameters: The parameters to search through for an upload object
*/
public func containsFile(parameters: Any) -> Bool {
guard let params = parameters as? HTTPParameterProtocol else { return false }
for pair in params.createPairs(nil) {
if let _ = pair.upload {
return true
}
}
return false
}
}
| mit | 0e445bff5f3e13c4171f276ac1859dad | 32.485465 | 132 | 0.612119 | 4.823702 | false | false | false | false |
wireapp/wire-ios | Wire-iOS/Sources/UserInterface/GroupDetails/ConversationActions/ConversationActionController+Block.swift | 1 | 2795 | //
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
import WireDataModel
enum BlockResult {
case block(isBlocked: Bool), cancel
var title: String {
return localizationKey.localized
}
private var localizationKey: String {
switch self {
case .cancel: return "profile.block_dialog.button_cancel"
case .block(isBlocked: false): return "profile.block_button_title_action"
case .block(isBlocked: true): return "profile.unblock_button_title_action"
}
}
private var style: UIAlertAction.Style {
guard case .cancel = self else { return .destructive }
return .cancel
}
func action(_ handler: @escaping (BlockResult) -> Void) -> UIAlertAction {
return .init(title: title, style: style) { _ in handler(self) }
}
static func title(for user: UserType) -> String? {
// Do not show the title if the user is already blocked and we want to unblock them.
if user.isBlocked {
return nil
}
return "profile.block_dialog.message".localized(args: user.name ?? "")
}
static func all(isBlocked: Bool) -> [BlockResult] {
return [.block(isBlocked: isBlocked), .cancel]
}
}
extension ConversationActionController {
func requestBlockResult(for conversation: ZMConversation, handler: @escaping (BlockResult) -> Void) {
guard let user = conversation.connectedUser else { return }
let controller = UIAlertController(title: BlockResult.title(for: user), message: nil, preferredStyle: .actionSheet)
BlockResult.all(isBlocked: user.isBlocked).map { $0.action(handler) }.forEach(controller.addAction)
present(controller)
}
func handleBlockResult(_ result: BlockResult, for conversation: ZMConversation) {
guard case .block = result else { return }
conversation.connectedUser?.block(completion: { [weak self] error in
if let error = error as? LocalizedError {
self?.presentError(error)
} else {
self?.transitionToListAndEnqueue {}
}
})
}
}
| gpl-3.0 | a748f200d09bcfeb9f6c3ca4ad838001 | 33.506173 | 123 | 0.666905 | 4.464856 | false | false | false | false |
zhaobin19918183/zhaobinCode | swift_NavigationController/swift_iPad/NavigationViewController.swift | 1 | 3827 | //
// NavigationViewController.swift
// swift_iPad
//
// Created by Zhao.bin on 16/3/25.
// Copyright ยฉ 2016ๅนด Zhao.bin. All rights reserved.
//
import UIKit
import Alamofire
class NavigationViewController: UINavigationController {
var titleLabel = UILabel()
var HUDProgtess = MBProgressHUD()
var count:NSInteger!
override func viewDidLoad() {
super.viewDidLoad()
self.navigationBar.setBackgroundImage(UIImage(named: "P_NavigationViewController_Bar_1024x64.png"), forBarMetrics: UIBarMetrics.Default)
titleLabel = UILabel(frame: CGRectMake(self.navigationBar.bounds.size.width/3, -20, self.navigationBar.bounds.size.width/3+50, self.navigationBar.bounds.size.height+20))
titleLabel.textColor = UIColor.whiteColor()
//ๆๅญๅฑ
ไธญ
titleLabel.textAlignment = NSTextAlignment.Center
titleLabel.text = "ๆฐ้ป็ญ็น"
self.navigationBar.addSubview(titleLabel)
reloadData()
}
func reloadData()
{
let BaiduURL = "http://op.juhe.cn/onebox/news/words?dtype=&key=c3184060738e9895f1f66bd9af7e1d87"
self.defaultShow()
Alamofire.request(.GET, BaiduURL).response{(request, response, data, error) in
let jsonArr = try! NSJSONSerialization.JSONObjectWithData(data!,
options: NSJSONReadingOptions.MutableContainers) as? NSMutableDictionary
self.count = jsonArr?.valueForKey("result")?.count
self.hiddenHUD()
}
}
func defaultShow(){
HUDProgtess = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
HUDProgtess.labelText = "ๆญฃๅจๅๆญฅ่ฏท็จ็ญ....."
//่ๆฏๆธๅๆๆ
HUDProgtess.dimBackground = true
}
func hiddenHUD()
{
HUDProgtess.mode = MBProgressHUDMode.CustomView
HUDProgtess.customView = UIImageView(image: UIImage(named: "yes")!)
HUDProgtess.labelText = "ๆฐๆฎ่ฏทๆฑๆๅ"
//ๅปถ่ฟ้่
HUDProgtess.hide(true, afterDelay: 1)
}
func textShow(){
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.Text
hud.labelText = "่ฟๆฏ็บฏๆๆฌๆ็คบ"
hud.detailsLabelText = "่ฟๆฏ่ฏฆ็ปไฟกๆฏๅ
ๅฎน๏ผไผๅพ้ฟๅพ้ฟๅข"
//ๅปถ่ฟ้่
hud.hide(true, afterDelay: 0.8)
}
func customShow(){
let hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.mode = MBProgressHUDMode.CustomView
hud.customView = UIImageView(image: UIImage(named: "yes")!)
hud.labelText = "่ฟๆฏ่ชๅฎไน่งๅพ"
//ๅปถ่ฟ้่
hud.hide(true, afterDelay: 0.8)
}
func asyncShow(){
var hud = MBProgressHUD.showHUDAddedTo(self.view, animated: true)
hud.labelText = "่ฏท็จ็ญ๏ผๆฐๆฎๅ ่ฝฝไธญ,้ข่ฎก10็งไธญ"
hud.showAnimated(true, whileExecutingBlock: {
//ๅผๆญฅไปปๅก๏ผๅจๅๅฐ่ฟ่ก็ไปปๅก
sleep(10)
}) {
//ๆง่กๅฎๆๅ็ๆไฝ๏ผ็งป้ค
hud.removeFromSuperview()
hud = nil
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
| gpl-3.0 | f71a7aff06f2744628043f5e52af3b14 | 28.867769 | 178 | 0.618428 | 4.428922 | false | false | false | false |
JARinteractive/ESCFutures | ESCFutures/Promise.swift | 1 | 901 | //
// Promise.swift
// ESCFutures
//
// Created by JARinteractive on 7/24/14.
// Copyright (c) 2014 Escappe. All rights reserved.
//
public class Box<T> {
public let value:T
init(_ theValue:T) {
value = theValue
}
}
public enum PromiseResult<T> {
case success(Box<T>)
case failure(NSError)
}
public class Promise<T> {
public private(set) var result: PromiseResult<T>? = nil
public let future: Future<T> = Future()
// public var value: T? { get { return promiseResult? == .success ? promiseResult. } }
// public var error: NSError? { get { return promiseResult?.error } }
public init() {}
public func success(value: T) {
self.complete(.success(Box(value)))
}
public func failure(error: NSError) {
self.complete(.failure(error))
}
public func complete(result: PromiseResult<T>) {
if (self.result == nil) {
self.result = result
future.complete(result)
}
}
} | mit | c5a24c90bc54d942a0a607b38d8e9a1d | 19.5 | 86 | 0.664817 | 3.003333 | false | false | false | false |
ifabijanovic/RxBattleNet | RxBattleNet/WoW/Model/PetAbility.swift | 1 | 1325 | //
// PetAbility.swift
// RxBattleNet
//
// Created by Ivan Fabijanoviฤ on 07/08/16.
// Copyright ยฉ 2016 Ivan Fabijanovic. All rights reserved.
//
import SwiftyJSON
public extension WoW {
public struct PetAbility: Model {
// MARK: - Properties
public let cooldown: Int
public let hideHints: Bool
public let icon: String
public let id: Int
public let isPassive: Bool
public let name: String
public let petTypeId: Int
public let rounds: Int
public let order: Int
public let requiredLevel: Int
public let slot: Int
// MARK: - Init
internal init(json: JSON) {
self.cooldown = json["cooldown"].intValue
self.hideHints = json["hideHints"].boolValue
self.icon = json["icon"].stringValue
self.id = json["id"].intValue
self.isPassive = json["isPassive"].boolValue
self.name = json["name"].stringValue
self.petTypeId = json["petTypeId"].intValue
self.rounds = json["rounds"].intValue
self.order = json["order"].intValue
self.requiredLevel = json["requiredLevel"].intValue
self.slot = json["slot"].intValue
}
}
}
| mit | b58253c92adb5c2ca15e406a2ce9d91a | 27.148936 | 63 | 0.566138 | 4.674912 | false | false | false | false |
piyushjo/demo-quiz-app | QuizApp/CategoriesViewController.swift | 1 | 7012 |
import UIKit
import FBSDKCoreKit
import MicrosoftAzureMobile
import MobileCenterAnalytics
class CategoriesViewController: UIViewController {
@IBOutlet weak var welcomeMessageLabel: UILabel!
@IBOutlet weak var lastScoreLabelField: UILabel!
var store : MSCoreDataStore?
var offlineTable : MSSyncTable?
override func viewDidLoad() {
super.viewDidLoad();
// Displays a welcome message & player's current score
self.getAndDisplayPlayerLastScore();
// Initialization for Azure Mobile Apps Data sync
initializeLocalStorageDb();
}
func getAndDisplayPlayerLastScore() {
// STEP 1
// Mobile Center: Tables ->
// Demonstrate how we can pull the data directly from the Azure service backend storage
let table = MyGlobalVariables.azureMobileClient.table(withName: "LastPlayedScore");
table.read { (result, error) in
// Query the LastPlayedScore table
if let err = error {
print("Azure Mobile Apps: Error in connecting to the table: ", err)
} else if (result?.items) != nil && (result?.items?.count)! > 0 {
// If table access was succesful and an item was found
let playerRecord = result?.items?[0];
let playerLastScore = (String(format: "%@", playerRecord?["score"] as! CVarArg) as String);
// Display the last played score using the FB name if available
let defaults = UserDefaults.standard;
if let playerName = defaults.string(forKey: "playerName") {
self.welcomeMessageLabel.text = String(format: "Welcome back, %@!", playerName);
}
else {
self.welcomeMessageLabel.text = String(format: "Welcome back!");
}
self.lastScoreLabelField.text = String(format: "Your last score was: %@", playerLastScore);
} else {
// No score found. Playing for the first time
let defaults = UserDefaults.standard;
if let playerName = defaults.string(forKey: "playerName") {
self.welcomeMessageLabel.text = String(format: "Welcome, %@!", playerName);
}
else {
self.welcomeMessageLabel.text = String(format: "Welcome!");
}
}
}
}
func initializeLocalStorageDb() {
// STEP 2
// Mobile Center: Tables ->
// Demonstrates initialization of local storage for offline access of data
// Reference: https://docs.microsoft.com/en-us/azure/app-service-mobile/app-service-mobile-ios-get-started-offline-data
let client = MyGlobalVariables.azureMobileClient;
let managedObjectContext = (UIApplication.shared.delegate as! AppDelegate).managedObjectContext!;
self.store = MSCoreDataStore(managedObjectContext: managedObjectContext);
client.syncContext = MSSyncContext(delegate: nil, dataSource: self.store, callback: nil);
self.offlineTable = client.syncTable(withName: "LastPlayedScore");
UIApplication.shared.isNetworkActivityIndicatorVisible = true;
// Pulling the table data into local storage for offline work
// If there are pending changes then it also pushes them to the backend
self.offlineTable!.pull(with: self.offlineTable?.query(), queryId: "AllRecords") {
(error) -> Void in
UIApplication.shared.isNetworkActivityIndicatorVisible = false;
if (error != nil) {
print("Azure Mobile Apps: Error in setting up offline sync", error.debugDescription);
}
else {
print("Data succesfully synced between client and Azure backend service");
// This will ensure that the last score is correctly displayed from the backend
self.getAndDisplayPlayerLastScore();
}
}
}
// Called when score is submitted from the final question screen
func updatePlayerScore() {
// STEP 3
// Mobile Center: Tables ->
// Demonstrate how we can update the local storage for offline access
let userId = MyGlobalVariables.azureMobileClient.currentUser?.userId;
// Updating the table in the local storage
let table = self.offlineTable;
table!.read { (result, error) in
// Query the LastPlayedScore table
if let err = error {
print("Azure Mobile Apps: Error in connecting to the table: ", err)
} else if (result?.items) != nil && (result?.items?.count)! > 0 {
// If table access was succesful and an item was found
// Update
print("Azure Mobile Apps: Player record found.");
let playerRecord = result?.items?[0];
let playerRecordId = playerRecord?["id"];
table!.update(["id": playerRecordId!, "score": MyGlobalVariables.playerScore]) { (error) in
if let err = error {
print("Azure Mobile Apps: Error in updating player record:", err);
} else {
print("Azure Mobile Apps: Updated score to", MyGlobalVariables.playerScore, "for player", userId ?? "" );
}
}
} else {
// Insert
print("Azure Mobile Apps: Player record not found.");
let newItem = ["score": MyGlobalVariables.playerScore]
table!.insert(newItem) { (result, error) in
if let err = error {
print("Azure Mobile Apps: Error in inserting player record:", err);
} else if let item = result {
print("Azure Mobile Apps: Score inserted", item["score"]!, "for player", userId ?? "" );
}
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning();
}
// MARK - Actions events
@IBAction func categoryButtonClicked(_ sender: UIButton) {
// STEP 2
// Mobile Center: Analytics ->
// Send an event to track which is the most commonly played category of logos
MSAnalytics.trackEvent("SelectedCategory", withProperties: ["Category" : sender.currentTitle!]);
}
@IBAction func unwindtoCategories(sender: UIStoryboardSegue) {
if sender.source is Question3ViewController {
self.lastScoreLabelField.text = "Your score in the last game was: " + String(MyGlobalVariables.playerScore);
// Update this score in the backend also
updatePlayerScore();
}
}
}
| mit | 1de50370bb18a8bc11d39c0f9b990b20 | 42.552795 | 129 | 0.577724 | 5.28012 | false | false | false | false |
hyperoslo/CalendarKit | Source/Timeline/Event.swift | 1 | 1791 | import UIKit
public final class Event: EventDescriptor {
public var startDate = Date()
public var endDate = Date()
public var isAllDay = false
public var text = ""
public var attributedText: NSAttributedString?
public var lineBreakMode: NSLineBreakMode?
public var color = SystemColors.systemBlue {
didSet {
updateColors()
}
}
public var backgroundColor = SystemColors.systemBlue.withAlphaComponent(0.3)
public var textColor = SystemColors.label
public var font = UIFont.boldSystemFont(ofSize: 12)
public var userInfo: Any?
public weak var editedEvent: EventDescriptor? {
didSet {
updateColors()
}
}
public init() {}
public func makeEditable() -> Event {
let cloned = Event()
cloned.startDate = startDate
cloned.endDate = endDate
cloned.isAllDay = isAllDay
cloned.text = text
cloned.attributedText = attributedText
cloned.lineBreakMode = lineBreakMode
cloned.color = color
cloned.backgroundColor = backgroundColor
cloned.textColor = textColor
cloned.userInfo = userInfo
cloned.editedEvent = self
return cloned
}
public func commitEditing() {
guard let edited = editedEvent else {return}
edited.startDate = startDate
edited.endDate = endDate
}
private func updateColors() {
(editedEvent != nil) ? applyEditingColors() : applyStandardColors()
}
private func applyStandardColors() {
backgroundColor = color.withAlphaComponent(0.3)
var h: CGFloat = 0, s: CGFloat = 0, b: CGFloat = 0, a: CGFloat = 0
color.getHue(&h, saturation: &s, brightness: &b, alpha: &a)
textColor = UIColor(hue: h, saturation: s, brightness: b * 0.4, alpha: a)
}
private func applyEditingColors() {
backgroundColor = color
textColor = .white
}
}
| mit | aa5944a545dd46530569ff4830bc0c41 | 26.984375 | 78 | 0.692909 | 4.422222 | false | false | false | false |
OscarSwanros/swift | test/Parse/ConditionalCompilation/switch_case_executable.swift | 11 | 3204 | // RUN: rm -rf %t && mkdir -p %t
// RUN: %target-build-swift %s -o %t/test1 -module-name main -D PATTERN_1
// RUN: %target-build-swift %s -o %t/test2 -module-name main -D PATTERN_2
// RUN: %target-run %t/test1 | %FileCheck -check-prefix=CHECK -check-prefix=CHECK1 %s
// RUN: %target-run %t/test2 | %FileCheck -check-prefix=CHECK -check-prefix=CHECK2 %s
// REQUIRES: executable_test
//------------------------------------------------------------------------------
print("START: switch toplevel")
// CHECK-LABEL: START: switch toplevel
let val = 1
switch val {
case 100:
break
#if PATTERN_1
case 1:
print("output1")
#elseif PATTERN_2
case 1:
print("output2")
#endif
default:
print("never")
}
// CHECK1-NEXT: output1
// CHECK2-NEXT: output2
print("END: switch toplevel")
// CHECK-NEXT: END: switch toplevel
//------------------------------------------------------------------------------
print("START: switch func")
// CHECK-LABEL: START: switch func
enum MyEnum {
case A, B
#if PATTERN_1
case str(String)
#elseif PATTERN_2
case int(Int)
#endif
}
func test1(_ val: MyEnum) {
switch val {
case .A, .B:
print("never")
#if PATTERN_1
case let .str(v):
print("output3 - " + v)
#elseif PATTERN_2
case let .int(v):
print("output4 - \(v + 12)")
#endif
}
}
#if PATTERN_1
test1(.str("foo bar"))
#elseif PATTERN_2
test1(.int(42))
#endif
// CHECK1-NEXT: output3 - foo bar
// CHECK2-NEXT: output4 - 54
print("END: switch func")
// CHECK-NEXT: END: switch func
//------------------------------------------------------------------------------
print("START: func local")
// CHECK-LABEL: func local
func test2(_ val: Int) -> () -> Void {
let ret: () -> Void
switch val {
#if PATTERN_1
case let v:
struct Foo : CustomStringConvertible {
let val: Int
var description: String { return "Foo(\(val))" }
}
func fn() {
print("output5 - \(Foo(val:v))")
}
ret = fn
#elseif PATTERN_2
case let v:
struct Bar : CustomStringConvertible {
let val: Int
var description: String { return "Bar(\(val))" }
}
ret = { print("output6 - \(Bar(val: v))") }
#endif
}
return ret
}
test2(42)()
// CHECK1-NEXT: output5 - Foo(42)
// CHECK2-NEXT: output6 - Bar(42)
print("END: func local")
// CHECK-NEXT: END: func local
//------------------------------------------------------------------------------
print("START: nested directives")
// CHECK-LABEL: START: nested directives
#if PATTERN_1 || PATTERN_2
func test3() {
#if PATTERN_1 || PATTERN_2
class Nested {
#if PATTERN_1 || PATTERN_2
func foo(_ x: Int) {
switch x {
#if true
#if PATTERN_1
case 0..<42:
print("output7 - 0..<42 \(x)")
#elseif PATTERN_2
case 0..<42:
print("output8 - 0..<42 \(x)")
#else
case 0..<42:
print("NEVER")
#endif
default:
print("output9 - default \(x)")
#endif
}
}
#endif
}
Nested().foo(12)
#endif
Nested().foo(53)
}
#endif
test3()
// CHECK1-NEXT: output7 - 0..<42 12
// CHECK1-NEXT: output9 - default 53
// CHECK2-NEXT: output8 - 0..<42 12
// CHECK2-NEXT: output9 - default 53
print("END: nested directives")
// CHECK-NEXT: END: nested directives
| apache-2.0 | 130c96cf385970764b9c245fe18c674d | 20.36 | 85 | 0.549938 | 3.289528 | false | true | false | false |
36Kr-Mobile/Cupid | CupidDemo/Cupid/Cupid/Service Provider/WeChatServiceProvider.swift | 1 | 7682 | //
// WeChatServiceProvider.swift
// China
//
// Created by Shannon Wu on 11/29/15.
// Copyright ยฉ 2015 36Kr. All rights reserved.
//
import UIKit
///This service provider is used to oauth and share content to WeChat, check [this website](https://open.weixin.qq.com) to learn more
public class WeChatServiceProvier: ShareServiceProvider {
/// Share destination
public enum Destination: Int {
/// Share to chat session
case Session = 0
/// Share to moments
case Timeline = 1
}
public static var appInstalled: Bool {
return URLHandler.canOpenURL(NSURL(string: "weixin://"))
}
/// True if app is installed
public static var canOAuth: Bool {
return appInstalled
}
/// App id
public private(set) var appID: String
/// App key
public private(set) var appKey: String?
/// Destination to share
public private(set) var destination: Destination?
/// Completion handler after share
public private(set) var shareCompletionHandler: ShareCompletionHandler?
/// Completion handler after OAuth
public private(set) var oauthCompletionHandler: NetworkResponseHandler?
/// Init a new service provider with the given information, if you want to share content, you must provide the share destination.
public init(appID: String, appKey: String?, destination: Destination? = nil) {
self.appID = appID
self.appKey = appKey
self.destination = destination
}
/// True if app is installed
public static func canShareContent(content: Content) -> Bool {
return appInstalled
}
/// True if app is installed
public func canShareContent(content: Content) -> Bool {
return WeChatServiceProvier.canShareContent(content)
}
/// Share content to WeChat, with a optional completion block
/// The title of the content is used for the title of the shared message
/// The description of the content is used for the brief intro of the shared message
/// The thumbnail of the content is used for the thumbnail of the shared message
/// The media is the payload of the shared message
public func shareContent(content: Content, completionHandler: ShareCompletionHandler? = nil) throws {
self.shareCompletionHandler = completionHandler
guard WeChatServiceProvier.canShareContent(content) else {
throw ShareError.ContentCannotShare
}
var weChatMessageInfo: [String:AnyObject]
if let destination = destination {
weChatMessageInfo = ["result": "1", "returnFromApp": "0", "scene": destination.rawValue, "sdkver": "1.5", "command": "1010", ]
}
else {
throw ShareError.DestinationNotPointed
}
if let title = content.title {
weChatMessageInfo["title"] = title
}
if let description = content.description {
weChatMessageInfo["description"] = description
}
if let thumbnailImage = content.thumbnail,
let thumbnailData = UIImageJPEGRepresentation(thumbnailImage, 0.5) {
weChatMessageInfo["thumbData"] = thumbnailData
}
if let media = content.media {
switch media {
case .URL(let URL):
weChatMessageInfo["objectType"] = "5"
weChatMessageInfo["mediaUrl"] = URL.absoluteString
case .Image(let image):
weChatMessageInfo["objectType"] = "2"
if let fileImageData = UIImageJPEGRepresentation(image, 1) {
weChatMessageInfo["fileData"] = fileImageData
}
case .Audio(let audioURL, let linkURL):
weChatMessageInfo["objectType"] = "3"
if let linkURL = linkURL {
weChatMessageInfo["mediaUrl"] = linkURL.absoluteString
}
weChatMessageInfo["mediaDataUrl"] = audioURL.absoluteString
case .Video(let URL):
weChatMessageInfo["objectType"] = "4"
weChatMessageInfo["mediaUrl"] = URL.absoluteString
}
}
else {
weChatMessageInfo["command"] = "1020"
}
let weChatMessage = [appID: weChatMessageInfo]
guard let data = try? NSPropertyListSerialization.dataWithPropertyList(weChatMessage, format: .BinaryFormat_v1_0, options: 0) else {
throw ShareError.FormattingError
}
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: "content")
let weChatSchemeURLString = "weixin://app/\(appID)/sendreq/?"
if !URLHandler.openURL(URLString: weChatSchemeURLString) {
throw ShareError.FormattingError
}
}
/// OAuth to Wechat, the completion handler cantains the information from Wechat
public func OAuth(completionHandler: NetworkResponseHandler) throws {
oauthCompletionHandler = completionHandler
guard WeChatServiceProvier.appInstalled else {
throw ShareError.AppNotInstalled
}
let scope = "snsapi_userinfo"
URLHandler.openURL(URLString: "weixin://app/\(appID)/auth/?scope=\(scope)&state=Weixinauth")
}
func fetchWeChatOAuthInfoByCode(code code: String, completionHandler: NetworkResponseHandler) {
guard let key = appKey else {
completionHandler(["code": code], nil, nil)
return
}
var accessTokenAPI = "https://api.weixin.qq.com/sns/oauth2/access_token?"
accessTokenAPI += "appid=" + appID
accessTokenAPI += "&secret=" + key
accessTokenAPI += "&code=" + code + "&grant_type=authorization_code"
Cupid.networkingProvier.request(accessTokenAPI, method: CupidNetworkingMethod.GET, parameters: nil) {
(OAuthJSON, response, error) -> Void in
completionHandler(OAuthJSON, response, error)
}
}
/// Handle URL callback for Wechat
public func handleOpenURL(URL: NSURL) -> Bool? {
if URL.scheme.hasPrefix("wx") {
// WeChat OAuth
if URL.absoluteString.containsString("&state=Weixinauth") {
let components = NSURLComponents(URL: URL, resolvingAgainstBaseURL: false)
guard let items = components?.queryItems else {
return false
}
var infos = [String: AnyObject]()
items.forEach {
infos[$0.name] = $0.value
}
guard let code = infos["code"] as? String else {
return false
}
// Login Succcess
fetchWeChatOAuthInfoByCode(code: code) {
(info, response, error) -> Void in
self.oauthCompletionHandler?(info, response, error)
}
return true
}
// WeChat Share
guard let data = UIPasteboard.generalPasteboard().dataForPasteboardType("content") else {
return false
}
if let dic = try? NSPropertyListSerialization.propertyListWithData(data, options: .Immutable, format: nil) {
if let dic = dic[appID] as? NSDictionary,
result = dic["result"]?.integerValue {
let succeed = (result == 0)
shareCompletionHandler?(succeed: succeed)
return succeed
}
}
}
// Other
return nil
}
}
| mit | 818da8a9c696444fdb4271241c21ebf4 | 34.892523 | 140 | 0.59836 | 5.165434 | false | false | false | false |
strivingboy/CocoaChinaPlus | Code/CocoaChinaPlus/Application/Business/Util/Helper/CCSqlite/Service/CCArticleService.swift | 1 | 5513 | //
// CCSqlite.swift
// CocoaChinaPlus
//
// Created by chenyl on 15/9/8.
// Copyright ยฉ 2015ๅนด zixun. All rights reserved.
//
import UIKit
import SQLite
import ZXKit
let kArticleDAO = CCDB.tableManager.articleDAO
enum CCArticleType {
case All
case UnCollection
case Collection
}
class CCArticleService: NSObject {
//ๆๅ
ฅไธ็ฏๆ็ซ
class func insertArtice(model:CCArticleModel) -> Bool {
do{
try CCDB.connection.run(kArticleDAO.table.insert(
kArticleDAO.identity <- model.identity,
kArticleDAO.title <- model.title,
kArticleDAO.linkURL <- model.linkURL,
kArticleDAO.imageURL <- model.imageURL,
kArticleDAO.type <- 0,
kArticleDAO.dateOfRead <- NSDate().string()))
CCArticleCache.sharedCache.updateCache()
return true;
}catch {
println("add failed: \(error)")
return false
}
}
//ๆ็ซ ๆฏๅฆๅญๅจ ไป็ผๅญไธญๅๅฏๆ้ซๆง่ฝ๏ผipodๆต่ฏ๏ผๆฏไธ่กๆธฒๆๅฏไปฅๆ้ซ162ms๏ผ
class func isArticleExsitById(identity:String?) -> Bool {
guard identity != nil else {
return false
}
for model in kArticleCache.articlesOfType(.All) {
if model.identity == identity {
return true
}
}
return false
}
class func isArticleCollectioned(identity:String) ->Bool {
for model in kArticleCache.articlesOfType(.Collection) {
if model.identity == identity {
return true
}
}
return false
}
//ๆถ่ๆ็ซ
class func collectArticleById(identity:String) -> Bool {
let update = kArticleDAO.table.filter(kArticleDAO.identity == identity)
.update(kArticleDAO.type <- 1,
kArticleDAO.dateOfCollection <- NSDate().string())
if try! CCDB.connection.run(update) > 0 {
print("update alice")
CCArticleCache.sharedCache.updateCache()
return true;
} else {
print("update not found")
return false;
}
}
//ๅๆถๆถ่
class func decollectArticleById(identity:String) -> Bool {
let update = kArticleDAO.table.filter(kArticleDAO.identity == identity)
.update(kArticleDAO.type <- 0)
if try! CCDB.connection.run(update) > 0 {
print("update alice")
CCArticleCache.sharedCache.updateCache()
return true;
} else {
print("update not found")
return false;
}
}
//ๆธ
็ฉบไธไธชๆๅ้
่ฏปๆชๆถ่็ๆ็ซ
class func cleanMouthAgo() {
let now = NSDate()
let articles = CCArticleService.queryArticles(CCArticleType.UnCollection, index: -1)
for article in articles {
let dateOfRead = article.dateOfRead!.date()
let secondsInterval = now.timeIntervalSinceDate(dateOfRead)
if secondsInterval >= 60 * 60 * 24 * 30 {//
CCArticleService.deleteArticleById(article.identity)
}
}
CCArticleCache.sharedCache.updateCache()
}
class func queryArticles(type:CCArticleType) ->[CCArticleModel] {
return CCArticleService.queryArticles(type, index: -1)
}
//ๆฃ็ดขๆ็ซ
class func queryArticles(type:CCArticleType,index:Int) ->[CCArticleModel] {
var query:QueryType = kArticleDAO.table.select(kArticleDAO.identity,
kArticleDAO.linkURL,
kArticleDAO.title,
kArticleDAO.imageURL,
kArticleDAO.dateOfCollection,
kArticleDAO.dateOfRead,
kArticleDAO.type)
if type == CCArticleType.Collection {
query = query.filter(kArticleDAO.type == 1)
}else if type == CCArticleType.UnCollection {
query = query.filter(kArticleDAO.type == 0)
}
if index >= 0 {
query = query.limit(20, offset: index*20)
}
var result = [CCArticleModel]()
for article in CCDB.connection.prepare(query) {
let model = CCArticleModel()
model.identity = article[kArticleDAO.identity]
model.linkURL = article[kArticleDAO.linkURL]
model.title = article[kArticleDAO.title]
model.imageURL = article[kArticleDAO.imageURL]
model.dateOfCollection = article[kArticleDAO.dateOfCollection]
model.dateOfRead = article[kArticleDAO.dateOfRead]
model.type = article[kArticleDAO.type]
result.append(model)
}
return result
}
//ๅ ้คๆ็ซ
private class func deleteArticleById(identity:String) -> Bool {
do {
let alice = kArticleDAO.table.filter(kArticleDAO.identity == identity)
if try CCDB.connection.run(alice.delete()) > 0 {
print("deleted alice")
CCArticleCache.sharedCache.updateCache()
return true;
} else {
print("alice not found")
return false;
}
} catch {
print("delete failed: \(error)")
return false;
}
}
}
| mit | e9ae7a0c64dab566525c5148da5a6241 | 29.731429 | 96 | 0.553923 | 4.592656 | false | false | false | false |
dreamsxin/swift | stdlib/public/core/OptionSet.swift | 1 | 14581 | //===--- OptionSet.swift --------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A type that presents a mathematical set interface to a bit mask.
///
/// You use the `OptionSet` protocol to represent bit mask types, where
/// individual bits represent members of the set. Adopting this protocol in
/// your custom types lets you perform set-related operations such as
/// membership tests, unions, and intersections on those types. What's more,
/// when implemented using specific criteria, adoption of this protocol
/// requires no extra work on your part.
///
/// When creating an option set, include a `rawValue` property in your type
/// declaration. The `rawValue` property must be of a type that conforms to
/// the `BitwiseOperations` protocol, such as `Int` or `UInt8`. Next, create
/// unique options as static properties of your custom type using unique
/// powers of two (1, 2, 4, 8, 16, and so forth) for each individual
/// property's raw value so that each property can be represented by a single
/// bit of the type's raw value.
///
/// For example, consider a custom type called `ShippingOptions` that is an
/// option set of the possible ways to ship a customer's purchase.
/// `ShippingOptions` includes a `rawValue` property of type `Int` that stores
/// the bit mask of available shipping options. The static members `NextDay`,
/// `SecondDay`, `Priority`, and `Standard` are unique, individual options.
///
/// struct ShippingOptions: OptionSet {
/// let rawValue: Int
///
/// static let nextDay = ShippingOptions(rawValue: 1 << 0)
/// static let secondDay = ShippingOptions(rawValue: 1 << 1)
/// static let priority = ShippingOptions(rawValue: 1 << 2)
/// static let standard = ShippingOptions(rawValue: 1 << 3)
///
/// static let express: ShippingOptions = [.nextDay, .secondDay]
/// static let all: ShippingOptions = [.express, .priority, .standard]
/// }
///
/// Declare additional preconfigured option set values as static properties
/// initialized with an array literal containing other option values. In the
/// example, because the `express` static property is assigned an array
/// literal with the `nextDay` and `secondDay` options, it will contain those
/// two elements.
///
/// Using an Option Set Type
/// ========================
///
/// When you need to create an instance of an option set, assign one of the
/// type's static members to your variable or constant. Alternately, to create
/// an option set instance with multiple members, assign an array literal with
/// multiple static members of the option set. To create an empty instance,
/// assign an empty array literal to your variable.
///
/// let singleOption: ShippingOptions = .priority
/// let multipleOptions: ShippingOptions = [.nextDay, .secondDay, .priority]
/// let noOptions: ShippingOptions = []
///
/// Use set-related operations to check for membership and to add or remove
/// members from an instance of your custom option set type. The following
/// example shows how you can determine free shipping options based on a
/// customer's purchase price:
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = []
/// if purchasePrice > 50 {
/// freeOptions.insert(.priority)
/// }
///
/// if freeOptions.contains(.priority) {
/// print("You've earned free priority shipping!")
/// } else {
/// print("Add more to your cart for free priority shipping!")
/// }
/// // Prints "You've earned free priority shipping!"
///
/// - SeeAlso: `BitwiseOperations`, `SetAlgebra`
public protocol OptionSet : SetAlgebra, RawRepresentable {
// We can't constrain the associated Element type to be the same as
// Self, but we can do almost as well with a default and a
// constrained extension
/// The element type of the option set.
///
/// To inherit all the default implementations from the `OptionSet` protocol,
/// the `Element` type must be `Self`, the default.
associatedtype Element = Self
// FIXME: This initializer should just be the failable init from
// RawRepresentable. Unfortunately, current language limitations
// that prevent non-failable initializers from forwarding to
// failable ones would prevent us from generating the non-failing
// default (zero-argument) initializer. Since OptionSet's main
// purpose is to create convenient conformances to SetAlgebra,
// we opt for a non-failable initializer.
/// Creates a new option set from the given raw value.
///
/// This initializer always succeeds, even if the value passed as `rawValue`
/// exceeds the static properties declared as part of the option set. This
/// example creates an instance of `ShippingOptions` with a raw value beyond
/// the highest element, with a bit mask that effectively contains all the
/// declared static members.
///
/// let extraOptions = ShippingOptions(rawValue: 255)
/// print(extraOptions.isStrictSuperset(of: .all))
/// // Prints "true"
///
/// - Parameter rawValue: The raw value of the option set to create. Each bit
/// of `rawValue` potentially represents an element of the option set,
/// though raw values may include bits that are not defined as distinct
/// values of the `OptionSet` type.
init(rawValue: RawValue)
}
/// `OptionSet` requirements for which default implementations
/// are supplied.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet {
/// Returns a new option set of the elements contained in this set, in the
/// given set, or in both.
///
/// This example uses the `union(_:)` method to add two more shipping options
/// to the default set.
///
/// let defaultShipping = ShippingOptions.standard
/// let memberShipping = defaultShipping.union([.secondDay, .priority])
/// print(memberShipping.contains(.priority))
/// // Prints "true"
///
/// - Parameter other: An option set.
/// - Returns: A new option set made up of the elements contained in this
/// set, in `other`, or in both.
public func union(_ other: Self) -> Self {
var r: Self = Self(rawValue: self.rawValue)
r.formUnion(other)
return r
}
/// Returns a new option set with only the elements contained in both this
/// set and the given set.
///
/// This example uses the `intersection(_:)` method to limit the available
/// shipping options to what can be used with a PO Box destination.
///
/// // Can only ship standard or priority to PO Boxes
/// let poboxShipping: ShippingOptions = [.standard, .priority]
/// let memberShipping: ShippingOptions =
/// [.standard, .priority, .secondDay]
///
/// let availableOptions = memberShipping.intersection(poboxShipping)
/// print(availableOptions.contains(.priority))
/// // Prints "true"
/// print(availableOptions.contains(.secondDay))
/// // Prints "false"
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in both this
/// set and `other`.
public func intersection(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formIntersection(other)
return r
}
/// Returns a new option set with the elements contained in this set or in
/// the given set, but not in both.
///
/// - Parameter other: An option set.
/// - Returns: A new option set with only the elements contained in either
/// this set or `other`, but not in both.
public func symmetricDifference(_ other: Self) -> Self {
var r = Self(rawValue: self.rawValue)
r.formSymmetricDifference(other)
return r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `Element == Self`, which is the default.
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where Element == Self {
/// Returns a Boolean value that indicates whether a given element is a
/// member of the option set.
///
/// This example uses the `contains(_:)` method to check whether next-day
/// shipping is in the `availableOptions` instance.
///
/// let availableOptions = ShippingOptions.express
/// if availableOptions.contains(.nextDay) {
/// print("Next day shipping available")
/// }
/// // Prints "Next day shipping available"
///
/// - Parameter member: The element to look for in the option set.
/// - Returns: `true` if the option set contains `member`; otherwise,
/// `false`.
public func contains(_ member: Self) -> Bool {
return self.isSuperset(of: member)
}
/// Inserts the given element into the option set if it is not already a
/// member.
///
/// For example:
///
/// let purchasePrice = 87.55
///
/// var freeOptions: ShippingOptions = [.standard, .priority]
/// if purchasePrice > 50 {
/// freeOptions.insert(.secondDay)
/// }
/// print(freeOptions.contains(.secondDay))
/// // Prints "true"
///
/// - Parameter newMember: The element to insert.
/// - Returns: `(true, newMember)` if `newMember` was not contained in
/// `self`. Otherwise, returns `(false, oldMember)`, where `oldMember` is
/// the member of the set equal to `newMember`.
public mutating func insert(
_ newMember: Element
) -> (inserted: Bool, memberAfterInsert: Element) {
let oldMember = self.intersection(newMember)
let shouldInsert = oldMember != newMember
let result = (
inserted: shouldInsert,
memberAfterInsert: shouldInsert ? newMember : oldMember)
if shouldInsert {
self.formUnion(newMember)
}
return result
}
/// Removes the given element and all elements subsumed by the given element.
///
/// For example:
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let priorityOption = options.remove(.priority)
/// print(priorityOption == .priority)
/// // Prints "true"
///
/// print(options.remove(.priority))
/// // Prints "nil"
///
/// In the following example, the `.express` element is passed to
/// `remove(_:)`. Although `.express` is not a member of `options`,
/// `.express` subsumes the remaining `.secondDay` element of the option
/// set. Therefore, `options` is emptied and the intersection between
/// `.express` and `options` is returned.
///
/// let expressOption = options.remove(.express)
/// print(expressOption == .express)
/// // Prints "false"
/// print(expressOption == .secondDay)
/// // Prints "true"
///
/// - Parameter member: The element of the set to remove.
/// - Returns: The intersection of `[member]` and the set if the intersection
/// was nonempty; otherwise, `nil`.
@discardableResult
public mutating func remove(_ member: Element) -> Element? {
let r = isSuperset(of: member) ? Optional(member) : nil
self.subtract(member)
return r
}
/// Inserts the given element into the set.
///
/// If `newMember` is not contained in the set but subsumes current members
/// of the set, the subsumed members are returned.
///
/// var options: ShippingOptions = [.secondDay, .priority]
/// let replaced = options.update(with: .express)
/// print(replaced == .secondDay)
/// // Prints "true"
///
/// - Returns: The intersection of `[newMember]` and the set if the
/// intersection was nonempty; otherwise, `nil`.
@discardableResult
public mutating func update(with newMember: Element) -> Element? {
let r = self.intersection(newMember)
self.formUnion(newMember)
return r.isEmpty ? nil : r
}
}
/// `OptionSet` requirements for which default implementations are
/// supplied when `RawValue` conforms to `BitwiseOperations`,
/// which is the usual case. Each distinct bit of an option set's
/// `.rawValue` corresponds to a disjoint value of the `OptionSet`.
///
/// - `union` is implemented as a bitwise "or" (`|`) of `rawValue`s
/// - `intersection` is implemented as a bitwise "and" (`&`) of
/// `rawValue`s
/// - `symmetricDifference` is implemented as a bitwise "exclusive or"
/// (`^`) of `rawValue`s
///
/// - Note: A type conforming to `OptionSet` can implement any of
/// these initializers or methods, and those implementations will be
/// used in lieu of these defaults.
extension OptionSet where RawValue : BitwiseOperations {
/// Creates an empty option set.
///
/// This initializer creates an option set with a raw value of zero.
public init() {
self.init(rawValue: .allZeros)
}
/// Inserts the elements of another set into this option set.
///
/// This method is implemented as a `|` (bitwise OR) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formUnion(_ other: Self) {
self = Self(rawValue: self.rawValue | other.rawValue)
}
/// Removes all elements of this option set that are not
/// also present in the given set.
///
/// This method is implemented as a `&` (bitwise AND) operation on the
/// two sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formIntersection(_ other: Self) {
self = Self(rawValue: self.rawValue & other.rawValue)
}
/// Replaces this set with a new set containing all elements
/// contained in either this set or the given set, but not in both.
///
/// This method is implemented as a `^` (bitwise XOR) operation on the two
/// sets' raw values.
///
/// - Parameter other: An option set.
public mutating func formSymmetricDifference(_ other: Self) {
self = Self(rawValue: self.rawValue ^ other.rawValue)
}
}
@available(*, unavailable, renamed: "OptionSet")
public typealias OptionSetType = OptionSet
| apache-2.0 | 58d2d0f0dcabb261296242253433df64 | 39.502778 | 80 | 0.663123 | 4.393191 | false | false | false | false |
HQL-yunyunyun/SinaWeiBo | SinaWeiBo/SinaWeiBo/Class/ViewModel/HQLStatusViewModel.swift | 1 | 2574 | //
// HQLStatusViewModel.swift
// SinaWeiBo
//
// Created by ไฝๅฏไบฎ on 16/5/18.
// Copyright ยฉ 2016ๅนด HQL. All rights reserved.
//
import Foundation
class HQLStatusViewModel: NSObject {
// ๅไพ
static let shareInstance: HQLStatusViewModel = HQLStatusViewModel()
// ==================MARK: - ๆ้ ๆนๆณ
/// ็งๆๆ้ ๅฝๆฐ ่ฟๆ ทๅฐฑๅช่ฝ่ฐ็จๅไพ
private override init() {
super.init()
}
// ==================MARK: - ๅ ่ฝฝๅพฎๅๆฐๆฎ
/**
้ญๅ
่ฟๅ็ๆฏๅพฎๅๆฐ็ป
*/
func loadStatus(loadStatusCallBack:(status: [HQLStatus]?, error: NSError?) -> ()){
// ๅคๆญtokenๆฏๅฆไธบ็ฉบ
guard let access_token = HQLUserAccountViewModel.shareInstance.userAccount?.access_token else{
let error = NSError(domain: "tokenไธบ็ฉบ", code: #line, userInfo: nil)
loadStatusCallBack(status: nil, error: error)
return
}
// ๅๆฐ
let urlString = "2/statuses/friends_timeline.json"
let parameters = [
"access_token": access_token
]
// ่ฏทๆฑ
HQLNetWorkTool.shareInstance.request(RequestMethod.GET, URLString: urlString, parameters: parameters, success: { (_, responseObject) in
// ่ฝฌๅญๅ
ธ
var error = NSError(domain: "ๆฐๆฎ่ฝฌๆขๅคฑ่ดฅ", code: #line, userInfo: nil)
guard let dict = responseObject as? [String: AnyObject] else{
// ่ฝฌๅคฑ่ดฅ
loadStatusCallBack(status: nil, error: error)
return
}
// ่ฝฌๆๅ -> ๅพฎๅๅญๅ
ธ่ฝฌๆข
guard let statusDict = dict["statuses"] as? [[String: AnyObject]] else{
// ๅพฎๅๅญๅ
ธ่ฝฌๆขๅคฑ่ดฅ
error = NSError(domain: "ๅพฎๅๅญๅ
ธ่ฝฌๆขๅคฑ่ดฅ", code: #line, userInfo: nil)
loadStatusCallBack(status: nil, error: error)
return
}
// ่กจๆ่ฝฌๆขๆๅ
var statusArray = [HQLStatus]()
// ๅผๅง่ฝฌๆข
for statuDict in statusDict {
// ๅผๅง่ฝฌๆข
let statu = HQLStatus(dict: statuDict)
statusArray.append(statu)
}
// ๅฐๅพฎๅๆฐๆฎๅ่ฏhomeViewController(่ฐ็จ็ไบบ) ่ฝฌๆขๅฎ
loadStatusCallBack(status: statusArray, error: nil)
}) { (_, error) in
loadStatusCallBack(status: nil, error: error)
}
}
}
| apache-2.0 | 1d9e9f3d119601a73ac8fb3982d44300 | 30.581081 | 143 | 0.523748 | 4.555556 | false | false | false | false |
theisegeberg/BasicJSON | BasicJSON/JSONRepresentable.swift | 1 | 3404 | //
// JSONRepresentable.swift
// BasicJSON
//
// Created by Theis Egeberg on 01/05/2017.
// Copyright ยฉ 2017 Theis Egeberg. All rights reserved.
//
import Foundation
public protocol JSONRepresentable {
func jsonValue<T>() -> T
func asBool() -> Bool
func asString() -> String
func asDouble() -> Double
func asFloat() -> Float
func asInt() -> Int
func asPureJSON() -> PureJSON
func asPureJSONArray() -> [PureJSON]
}
extension JSONRepresentable {
public func asBool() -> Bool {
if let convertible = self as? Convertible {
return convertible.boolConverted
}
return false
}
public func asString() -> String {
if let convertible = self as? Convertible {
return convertible.stringConverted
}
return ""
}
public func asFloat() -> Float {
if let convertible = self as? Convertible {
return Float(convertible.doubleConverted)
}
return 0.0
}
public func asDouble() -> Double {
if let convertible = self as? Convertible {
return convertible.doubleConverted
}
return 0.0
}
public func asInt() -> Int {
if let convertible = self as? Convertible {
return convertible.intConverted
}
return 0
}
public func asPureJSON() -> PureJSON {
if let rawSelf = self as? RawJSON {
return PureJSON(raw:rawSelf)
}
return PureJSON()
}
public func asPureJSONArray() -> [PureJSON] {
if let rawList = self as? [RawJSON] {
return rawList.map({ (rawJSON) -> PureJSON in
return PureJSON(raw:rawJSON)
})
}
return [PureJSON]()
}
public func jsonValue<T>() -> T {
if let selfRef = self as? T {
return selfRef
}
if let boolValue = self.asBool() as? T {
return boolValue
}
if let intValue = self.asInt() as? T {
return intValue
}
if let floatValue = self.asFloat() as? T {
return floatValue
}
if let doubleValue = self.asDouble() as? T {
return doubleValue
}
if let jsonValue = self.asPureJSON() as? T {
return jsonValue
}
if let jsonValue = self.asPureJSONArray() as? T {
return jsonValue
}
if let stringValue = self.asString() as? T {
return stringValue
}
fatalError("Something couldn't get converted: \(self)")
}
public func toObject<T: JSONObject>() -> T {
if let rawJSON = self as? RawJSON {
return JSON.buildObject(rawJSON: rawJSON)
}
return T()
}
public func toList<T: JSONObject>() -> [T] {
if let rawJSONList = self as? [RawJSON] {
return JSON.buildList(rawJSON: rawJSONList)
}
return [T]()
}
}
extension String:JSONRepresentable {}
extension Bool:JSONRepresentable {}
extension Double:JSONRepresentable {}
extension Float:JSONRepresentable {}
extension Int:JSONRepresentable {}
extension JSON:JSONRepresentable {}
extension NSString:JSONRepresentable {}
extension Dictionary:JSONRepresentable {}
extension Array:JSONRepresentable {}
extension NSDictionary:JSONRepresentable {}
extension NSNumber:JSONRepresentable {}
| mit | f3312d4bebff79531027cda259fb85a9 | 24.780303 | 63 | 0.582133 | 4.573925 | false | false | false | false |
DylanModesitt/Picryption_iOS | Pods/Eureka/Source/Validations/RuleLength.swift | 4 | 2249 | // RuleLength.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs SRL ( http://xmartlabs.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 Foundation
public struct RuleMinLength: RuleType {
let min: UInt
public var id: String?
public var validationError: ValidationError
public init(minLength: UInt){
min = minLength
validationError = ValidationError(msg: "Field value must have at least \(min) characters")
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value, value.characters.count >= Int(min) else { return validationError }
return nil
}
}
public struct RuleMaxLength: RuleType {
let max: UInt
public var id: String?
public var validationError: ValidationError
public init(maxLength: UInt){
max = maxLength
validationError = ValidationError(msg: "Field value must have less than \(max) characters")
}
public func isValid(value: String?) -> ValidationError? {
guard let value = value , value.characters.count <= Int(max) else { return validationError }
return nil
}
}
| mit | 05b254ddcdd397bf57828b180e0079cc | 35.274194 | 100 | 0.705647 | 4.685417 | false | false | false | false |
lenglengiOS/BuDeJie | ็พๆไธๅพๅง/Pods/Charts/Charts/Classes/Data/ScatterChartData.swift | 35 | 1425 | //
// ScatterChartData.swift
// Charts
//
// Created by Daniel Cohen Gindi on 26/2/15.
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
//
import UIKit
public class ScatterChartData: BarLineScatterCandleBubbleChartData
{
public override init()
{
super.init()
}
public override init(xVals: [String?]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
public override init(xVals: [NSObject]?, dataSets: [ChartDataSet]?)
{
super.init(xVals: xVals, dataSets: dataSets)
}
/// - returns: the maximum shape-size across all DataSets.
public func getGreatestShapeSize() -> CGFloat
{
var max = CGFloat(0.0)
for set in _dataSets
{
let scatterDataSet = set as? ScatterChartDataSet
if (scatterDataSet == nil)
{
print("ScatterChartData: Found a DataSet which is not a ScatterChartDataSet", terminator: "\n")
}
else
{
let size = scatterDataSet!.scatterShapeSize
if (size > max)
{
max = size
}
}
}
return max
}
}
| apache-2.0 | 32cfbd6a79b4c23a826fbeb73d089784 | 23.152542 | 111 | 0.541754 | 4.846939 | false | false | false | false |
nodes-vapor/ironman | App/Services/YoutubeVideoRetriever.swift | 1 | 2368 | import Vapor
import JSON
class YoutubeVideoRetriever {
let drop: Droplet
init(drop: Droplet) {
self.drop = drop
}
func retrieve(race: Race) throws -> [Node] {
if(race.youtubeChannel.isEmpty){
throw Abort.custom(status: .badRequest, message: "Race passed does not have a youtube channel")
}
return try retrieve(youtubeChannel: race.youtubeChannel)
}
func retrieve(youtubeChannel: String) throws -> [Node] {
let url = "https://www.googleapis.com/youtube/v3/search"
let response = try drop.client.get(url, headers:[
"Accept":"application/json"
], query: [
"key": "AIzaSyAEhtTAYnHPA30TIym6U8HHDJFs2dZLmHY",
"channelId": youtubeChannel,
"part": "snippet,id",
"order": "date",
"maxResults": 20
])
if(response.status != .ok) {
throw Abort.custom(status: .badRequest, message: "Youtube api failed")
}
guard let data = response.json?["items"] else {
throw Abort.custom(status: .badRequest, message: "Data could not be parsed")}
var array: [Node] = [];
data.makeNode().pathIndexableArray?.forEach({
let item = $0;
do {
let thumbnail: [String:String] = [
"hqDefault" : try item.extract("snippet", "thumbnails", "high", "url"),
"sqDefault" : try item.extract("snippet", "thumbnails", "medium", "url")
]
let id: String = try item.extract("id", "videoId")
let videoUrl: String = "https://m.youtube.com/watch?v='" + id
array.append(try Node([
"id": id.makeNode(),
"title": item.extract("snippet", "title"),
"description": item.extract("snippet", "description"),
"thumbnail": thumbnail.makeNode(),
"player": [
"mobile": videoUrl.makeNode()
]
]))
} catch
{
drop.console.error("Could not parse entry")
}
})
return array
}
}
| mit | 7e7e747eee4e726bdb4bfe8793ff6588 | 32.828571 | 107 | 0.47973 | 4.726547 | false | false | false | false |
ollieatkinson/Expectation | Tests/Source/Matchers/Expectation+RespondTo_Spec.swift | 1 | 1306 | //
// Expectation+RespondTo_Spec.swift
// Expectation
//
// Created by Atkinson, Oliver (Developer) on 23/02/2016.
// Copyright ยฉ 2016 Oliver. All rights reserved.
//
import XCTest
@testable import Expectation
class Expectation_RespondTo_Spec: XCTestCase {
override func tearDown() {
super.tearDown()
ExpectationAssertFunctions.assertTrue = ExpectationAssertFunctions.ExpectationAssertTrue
ExpectationAssertFunctions.assertFalse = ExpectationAssertFunctions.ExpectationAssertFalse
ExpectationAssertFunctions.assertNil = ExpectationAssertFunctions.ExpectationAssertNil
ExpectationAssertFunctions.assertNotNil = ExpectationAssertFunctions.ExpectationAssertNotNil
ExpectationAssertFunctions.fail = ExpectationAssertFunctions.ExpectationFail
}
func testRespondToPass() {
assertTrueValidate(True) {
expect(NSObject()).to.respondTo(#selector(NSObject.doesNotRecognizeSelector(_:)))
}
}
func testRespondToFail() {
assertTrueValidate(False) {
expect(NSObject()).to.respondTo(#selector(NSData.base64EncodedData(options:)))
}
assertTrueValidate(False) {
let object: NSObject? = nil
expect(object).to.respondTo(#selector(NSObject.doesNotRecognizeSelector(_:)))
}
}
}
| mit | f5479ecc0aa546a54d5211eaaccafbb2 | 27.369565 | 96 | 0.731801 | 5.326531 | false | true | false | false |
PD-Jell/Swift_study | SwiftStudy/RxMoya-Github/RxMoyaGithubViewController.swift | 1 | 3354 | //
// RxMoyaGithubViewController.swift
// SwiftStudy
//
// Created by Jell PD on 2020/08/02.
// Copyright ยฉ 2020 Jell PD. All rights reserved.
//
import UIKit
import Foundation
import RxCocoa
import Moya
import RxSwift
// MARK: - User struct.
struct RxMoyaGithubUser: Codable {
let login: String
let avatarUrl: String
let reposUrl: String
private enum CodingKeys: String, CodingKey {
case login
case avatarUrl = "avatar_url"
case reposUrl = "repos_url"
}
}
// MARK: - Provider
enum provider {
case userInfo(name: String)
}
extension provider: TargetType {
var headers: [String: String]? {
return nil
}
var baseURL: URL {
return URL(string: "https://api.github.com")!
}
var path: String {
switch self {
case .userInfo(let name): // enum์ ์ํฅ์ ๋ฐ์.
return "/users/\(name)"
}
}
var method: Moya.Method {
return .get
}
var sampleData: Data {
return "".data(using: .utf8)!
}
var parameters: [String: Any]? {
return nil
}
var task: Task {
return .requestPlain
}
}
class RxMoyaGithubViewController: UIViewController {
@IBOutlet weak var userTextField: UITextField!
@IBOutlet weak var getButton: UIButton!
let name: BehaviorSubject<String> = BehaviorSubject(value: "")
let nameValid: BehaviorSubject<Bool> = BehaviorSubject(value: false)
let bag: DisposeBag = DisposeBag()
override func viewDidLoad() {
super.viewDidLoad()
bindEvent()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
}
@IBAction func getButtonClicked(_ sender: Any) {
if let name = try? name.value() {
userInfo(name: name)
}
}
// MARK: - Original Moya
// func userInfo(name: String) {
// let provider = MoyaProvider<provider>()
// provider.request(.userInfo(name: name)) { result in
// switch result {
// case .success(let response):
// guard let user = try? JSONDecoder().decode(RxMoyaGithubUser.self, from: response.data) else { return }
// print(user.login)
// case .failure(let error):
// print(error)
// }
// }
// }
// MARK: - RxMoya
func userInfo(name: String) {
let provider = MoyaProvider<provider>()
provider.rx.request(.userInfo(name: name))
.map(RxMoyaGithubUser.self)
.asObservable()
.subscribe(onNext: {user in
print(user.login)
print(user.avatarUrl)
print(user.reposUrl)
}, onError: {error in
print(error)
}).disposed(by: bag)
}
func bindEvent() {
userTextField.rx.text.orEmpty
.bind(to: name)
.disposed(by: bag)
name.map(validName)
.bind(to: nameValid)
.disposed(by: bag)
nameValid.subscribe(onNext: {[weak self] valid in
self?.getButton.isEnabled = valid
}).disposed(by: bag)
}
func validName(name: String) -> Bool {
return !name.contains(" ")
}
}
| mit | d7c59b2fb03ee549329bd91d6fd4a2b3 | 23.210145 | 120 | 0.555522 | 4.277849 | false | false | false | false |
hsusmita/SHRichTextEditorTools | SHRichTextEditorTools/Source/Core/RichTextEditor.swift | 1 | 1109 | //
// RichTextEditor.swift
// SHRichTextEditorTools
//
// Created by Susmita Horrow on 27/09/18.
// Copyright ยฉ 2018 hsusmita. All rights reserved.
//
import UIKit
protocol RichTextEditor {
var textView: UITextView { get }
var textViewDelegate: TextViewDelegate { get }
var toolBar: UIToolbar { get }
var toolBarItems: [ToolBarItem] { get }
}
extension RichTextEditor {
func configure(tintColor: UIColor) {
self.textView.touchEnabled = true
self.textView.delegate = self.textViewDelegate
self.toolBar.translatesAutoresizingMaskIntoConstraints = false
self.toolBar.items = self.toolBarItems.map { $0.barButtonItem }
self.toolBar.tintColor = tintColor
self.textView.inputAccessoryView = self.toolBar
self.textViewDelegate.registerDidTapChange { textView in
if let index = textView.currentTappedIndex {
if !textView.attributedText.imagePresent(at: index) {
textView.inputView = nil
textView.reloadInputViews()
}
}
}
}
}
| mit | 45195f550248bd45fa231a23e49064a9 | 30.657143 | 71 | 0.652527 | 4.578512 | false | false | false | false |
swizzlr/Moya | Demo/DemoTests/RACSignal+MoyaSpec.swift | 2 | 7300 | import Quick
import Moya
import ReactiveCocoa
import Nimble
// Necessary since UIImage(named:) doesn't work correctly in the test bundle
private extension UIImage {
class func testPNGImage(named name: String) -> UIImage {
class TestClass { }
let bundle = NSBundle(forClass: TestClass().dynamicType)
let path = bundle.pathForResource(name, ofType: "png")
return UIImage(contentsOfFile: path!)!
}
}
private func signalSendingData(data: NSData, statusCode: Int = 200) -> RACSignal {
return RACSignal.createSignal { (subscriber) -> RACDisposable! in
subscriber.sendNext(MoyaResponse(statusCode: statusCode, data: data, response: nil))
subscriber.sendCompleted()
return nil
}
}
class RACSignalMoyaSpec: QuickSpec {
override func spec() {
describe("status codes filtering") {
it("filters out unrequested status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 10)
var errored = false
signal.filterStatusCodes(0...9).subscribeNext({ (object) -> Void in
XCTFail("called on non-correct status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("filters out non-successful status codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusCodes().subscribeNext({ (object) -> Void in
XCTFail("called on non-success status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("filters out non-successful status and redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 404)
var errored = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext({ (object) -> Void in
XCTFail("called on non-success status code: \(object)")
}, error: { (error) -> Void in
errored = true
})
expect(errored).to(beTruthy())
}
it("passes through correct status codes") {
let data = NSData()
let signal = signalSendingData(data)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
it("passes through correct redirect codes") {
let data = NSData()
let signal = signalSendingData(data, statusCode: 304)
var called = false
signal.filterSuccessfulStatusAndRedirectCodes().subscribeNext { (object) -> Void in
called = true
}
expect(called).to(beTruthy())
}
}
describe("image maping") {
it("maps data representing an image to an image") {
let image = Image.testPNGImage(named: "testImage")
let data = UIImageJPEGRepresentation(image, 0.75)
let signal = signalSendingData(data!)
var size: CGSize?
signal.mapImage().subscribeNext { (image) -> Void in
size = image.size
}
expect(size).to(equal(image.size))
}
it("ignores invalid data") {
let data = NSData()
let signal = signalSendingData(data)
var receivedError: NSError?
signal.mapImage().subscribeNext({ (object) -> Void in
XCTFail("next called for invalid data")
}, error: { (error) -> Void in
receivedError = error
})
expect(receivedError?.code).to(equal(MoyaErrorCode.ImageMapping.rawValue))
}
}
describe("JSON mapping") {
it("maps data representing some JSON to that JSON") {
let json = ["name": "John Crighton", "occupation": "Astronaut"]
let data = try! NSJSONSerialization.dataWithJSONObject(json, options: .PrettyPrinted)
let signal = signalSendingData(data)
var receivedJSON: [String: String]?
signal.mapJSON().subscribeNext { (json) -> Void in
if let json = json as? [String: String] {
receivedJSON = json
}
}
expect(receivedJSON?["name"]).to(equal(json["name"]))
expect(receivedJSON?["occupation"]).to(equal(json["occupation"]))
}
it("returns a Cocoa error domain for invalid JSON") {
let json = "{ \"name\": \"john }"
let data = json.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedError: NSError?
signal.mapJSON().subscribeNext({ (object) -> Void in
XCTFail("next called for invalid data")
}, error: { (error) -> Void in
receivedError = error
})
expect(receivedError).toNot(beNil())
expect(receivedError?.domain).to(equal("\(NSCocoaErrorDomain)"))
}
}
describe("string mapping") {
it("maps data representing a string to a string") {
let string = "You have the rights to the remains of a silent attorney."
let data = string.dataUsingEncoding(NSUTF8StringEncoding)
let signal = signalSendingData(data!)
var receivedString: String?
signal.mapString().subscribeNext { (string) -> Void in
receivedString = string as? String
return
}
expect(receivedString).to(equal(string))
}
}
}
}
| mit | 422f13f8e686747db6ff4c9dd17e406c | 38.247312 | 101 | 0.482192 | 6.181202 | false | false | false | false |
wuleijun/Zeus | Zeus/ViewControllers/ๆดปๅจ/CheckListVC.swift | 1 | 1768 | //
// CheckListVC.swift
// Zeus
//
// Created by ๅด่พๅ on 16/5/9.
// Copyright ยฉ 2016ๅนด rayjuneWu. All rights reserved.
//
import UIKit
/// ๅๅๆฅ็
class CheckListVC: BaseViewController {
let clientInviteCellId = "ClientInviteCell"
@IBOutlet weak var tableView: UITableView!{
didSet{
tableView.registerNib(UINib(nibName: clientInviteCellId, bundle: nil), forCellReuseIdentifier: clientInviteCellId)
tableView.rowHeight = ClientInviteCell.heightOfCell()
}
}
@IBOutlet weak var progressHeightConstraint: NSLayoutConstraint!
@IBOutlet weak var progressView: UIProgressView!
@IBOutlet weak var topView: UIView! {
didSet{
topView.backgroundColor = UIColor.zeusNavigationBarTintColor()
}
}
override func viewDidLoad() {
super.viewDidLoad()
hideNavigationBarShadow()
progressHeightConstraint.constant = ZeusConfig.CommonUI.progressViewHeight
// Do any additional setup after loading the view.
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
UIView.animateWithDuration(1.0) {
self.progressView.progress = 0.5
self.progressView.layoutIfNeeded()
}
}
}
// MARK: TableView DataSource
extension CheckListVC : UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return 20
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let clientInviteCell = tableView.dequeueReusableCellWithIdentifier(clientInviteCellId) as! ClientInviteCell
return clientInviteCell
}
}
| mit | b5ad68b4888b0a1b79a4c54e4c1840ca | 28.677966 | 126 | 0.684752 | 5.017192 | false | false | false | false |
shorlander/firefox-ios | Storage/SQL/SQLiteLogins.swift | 1 | 43111 | /* 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 XCGLogger
import Deferred
private let log = Logger.syncLogger
let TableLoginsMirror = "loginsM"
let TableLoginsLocal = "loginsL"
let IndexLoginsOverrideHostname = "idx_loginsM_is_overridden_hostname"
let IndexLoginsDeletedHostname = "idx_loginsL_is_deleted_hostname"
let AllLoginTables: [String] = [TableLoginsMirror, TableLoginsLocal]
private let OverriddenHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsOverrideHostname) ON \(TableLoginsMirror) (is_overridden, hostname)"
private let DeletedHostnameIndexQuery =
"CREATE INDEX IF NOT EXISTS \(IndexLoginsDeletedHostname) ON \(TableLoginsLocal) (is_deleted, hostname)"
private class LoginsTable: Table {
var name: String { return "LOGINS" }
var version: Int { return 3 }
func run(_ db: SQLiteDBConnection, sql: String, args: Args? = nil) -> Bool {
let err = db.executeChange(sql, withArgs: args)
if err != nil {
log.error("Error running SQL in LoginsTable: \(err?.localizedDescription ?? "nil")")
log.error("SQL was \(sql)")
}
return err == nil
}
// TODO: transaction.
func run(_ db: SQLiteDBConnection, queries: [String]) -> Bool {
for sql in queries {
if !run(db, sql: sql, args: nil) {
return false
}
}
return true
}
func create(_ db: SQLiteDBConnection) -> Bool {
let common =
"id INTEGER PRIMARY KEY AUTOINCREMENT" +
", hostname TEXT NOT NULL" +
", httpRealm TEXT" +
", formSubmitURL TEXT" +
", usernameField TEXT" +
", passwordField TEXT" +
", timesUsed INTEGER NOT NULL DEFAULT 0" +
", timeCreated INTEGER NOT NULL" +
", timeLastUsed INTEGER" +
", timePasswordChanged INTEGER NOT NULL" +
", username TEXT" +
", password TEXT NOT NULL"
let mirror = "CREATE TABLE IF NOT EXISTS \(TableLoginsMirror) (" +
common +
", guid TEXT NOT NULL UNIQUE" +
", server_modified INTEGER NOT NULL" + // Integer milliseconds.
", is_overridden TINYINT NOT NULL DEFAULT 0" +
")"
let local = "CREATE TABLE IF NOT EXISTS \(TableLoginsLocal) (" +
common +
", guid TEXT NOT NULL UNIQUE " + // Typically overlaps one in the mirror unless locally new.
", local_modified INTEGER" + // Can be null. Client clock. In extremis only.
", is_deleted TINYINT NOT NULL DEFAULT 0" + // Boolean. Locally deleted.
", sync_status TINYINT " + // SyncStatus enum. Set when changed or created.
"NOT NULL DEFAULT \(SyncStatus.synced.rawValue)" +
")"
return self.run(db, queries: [mirror, local, OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
func updateTable(_ db: SQLiteDBConnection, from: Int) -> Bool {
let to = self.version
if from == to {
log.debug("Skipping update from \(from) to \(to).")
return true
}
if from == 0 {
// This is likely an upgrade from before Bug 1160399.
log.debug("Updating logins tables from zero. Assuming drop and recreate.")
return drop(db) && create(db)
}
if from < 3 && to >= 3 {
log.debug("Updating logins tables to include version 3 indices")
return self.run(db, queries: [OverriddenHostnameIndexQuery, DeletedHostnameIndexQuery])
}
// TODO: real update!
log.debug("Updating logins table from \(from) to \(to).")
return drop(db) && create(db)
}
func exists(_ db: SQLiteDBConnection) -> Bool {
return db.tablesExist(AllLoginTables)
}
func drop(_ db: SQLiteDBConnection) -> Bool {
log.debug("Dropping logins table.")
let err = db.executeChange("DROP TABLE IF EXISTS \(name)")
return err == nil
}
}
open class SQLiteLogins: BrowserLogins {
fileprivate let db: BrowserDB
fileprivate static let MainColumns: String = "guid, username, password, hostname, httpRealm, formSubmitURL, usernameField, passwordField"
fileprivate static let MainWithLastUsedColumns: String = MainColumns + ", timeLastUsed, timesUsed"
fileprivate static let LoginColumns: String = MainColumns + ", timeCreated, timeLastUsed, timePasswordChanged, timesUsed"
public init(db: BrowserDB) {
self.db = db
_ = db.createOrUpdate(LoginsTable())
}
fileprivate class func populateLogin(_ login: Login, row: SDRow) {
login.formSubmitURL = row["formSubmitURL"] as? String
login.usernameField = row["usernameField"] as? String
login.passwordField = row["passwordField"] as? String
login.guid = row["guid"] as! String
if let timeCreated = row.getTimestamp("timeCreated"),
let timeLastUsed = row.getTimestamp("timeLastUsed"),
let timePasswordChanged = row.getTimestamp("timePasswordChanged"),
let timesUsed = row["timesUsed"] as? Int {
login.timeCreated = timeCreated
login.timeLastUsed = timeLastUsed
login.timePasswordChanged = timePasswordChanged
login.timesUsed = timesUsed
}
}
fileprivate class func constructLogin<T: Login>(_ row: SDRow, c: T.Type) -> T {
let credential = URLCredential(user: row["username"] as? String ?? "",
password: row["password"] as! String,
persistence: URLCredential.Persistence.none)
// There was a bug in previous versions of the app where we saved only the hostname and not the
// scheme and port in the DB. To work with these scheme-less hostnames, we try to extract the scheme and
// hostname by converting to a URL first. If there is no valid hostname or scheme for the URL,
// fallback to returning the raw hostname value from the DB as the host and allow NSURLProtectionSpace
// to use the default (http) scheme. See https://bugzilla.mozilla.org/show_bug.cgi?id=1238103.
let hostnameString = (row["hostname"] as? String) ?? ""
let hostnameURL = hostnameString.asURL
let scheme = hostnameURL?.scheme
let port = hostnameURL?.port ?? 0
// Check for malformed hostname urls in the DB
let host: String
var malformedHostname = false
if let h = hostnameURL?.host {
host = h
} else {
host = hostnameString
malformedHostname = true
}
let protectionSpace = URLProtectionSpace(host: host,
port: port,
protocol: scheme,
realm: row["httpRealm"] as? String,
authenticationMethod: nil)
let login = T(credential: credential, protectionSpace: protectionSpace)
self.populateLogin(login, row: row)
login.hasMalformedHostname = malformedHostname
return login
}
class func LocalLoginFactory(_ row: SDRow) -> LocalLogin {
let login = self.constructLogin(row, c: LocalLogin.self)
login.localModified = row.getTimestamp("local_modified")!
login.isDeleted = row.getBoolean("is_deleted")
login.syncStatus = SyncStatus(rawValue: row["sync_status"] as! Int)!
return login
}
class func MirrorLoginFactory(_ row: SDRow) -> MirrorLogin {
let login = self.constructLogin(row, c: MirrorLogin.self)
login.serverModified = row.getTimestamp("server_modified")!
login.isOverridden = row.getBoolean("is_overridden")
return login
}
fileprivate class func LoginFactory(_ row: SDRow) -> Login {
return self.constructLogin(row, c: Login.self)
}
fileprivate class func LoginDataFactory(_ row: SDRow) -> LoginData {
return LoginFactory(row) as LoginData
}
fileprivate class func LoginUsageDataFactory(_ row: SDRow) -> LoginUsageData {
return LoginFactory(row) as LoginUsageData
}
func notifyLoginDidChange() {
log.debug("Notifying login did change.")
// For now we don't care about the contents.
// This posts immediately to the shared notification center.
NotificationCenter.default.post(name: NotificationDataLoginDidChange, object: nil)
}
open func getUsageDataForLoginByGUID(_ guid: GUID) -> Deferred<Maybe<LoginUsageData>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND guid = ? " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginUsageDataFactory)
>>== { value in
deferMaybe(value[0]!)
}
}
open func getLoginDataForGUID(_ guid: GUID) -> Deferred<Maybe<Login>> {
let projection = SQLiteLogins.LoginColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND guid = ? " +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overriden IS NOT 1 AND guid = ? " +
"ORDER BY hostname ASC " +
"LIMIT 1"
let args: Args = [guid, guid]
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
>>== { value in
if let login = value[0] {
return deferMaybe(login)
} else {
return deferMaybe(LoginDataError(description: "Login not found for GUID \(guid)"))
}
}
}
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
// Since we store hostnames as the full scheme/protocol + host, combine the two to look up in our DB.
// In the case of https://bugzilla.mozilla.org/show_bug.cgi?id=1238103, there may be hostnames without
// a scheme. Check for these as well.
let args: Args = [
protectionSpace.urlString(),
protectionSpace.host,
protectionSpace.urlString(),
protectionSpace.host,
]
if Logger.logPII {
log.debug("Looking for login: \(protectionSpace.urlString()) && \(protectionSpace.host)")
}
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
// username is really Either<String, NULL>; we explicitly match no username.
open func getLoginsForProtectionSpace(_ protectionSpace: URLProtectionSpace, withUsername username: String?) -> Deferred<Maybe<Cursor<LoginData>>> {
let projection = SQLiteLogins.MainWithLastUsedColumns
let args: Args
let usernameMatch: String
if let username = username {
args = [
protectionSpace.urlString(), username, protectionSpace.host,
protectionSpace.urlString(), username, protectionSpace.host
]
usernameMatch = "username = ?"
} else {
args = [
protectionSpace.urlString(), protectionSpace.host,
protectionSpace.urlString(), protectionSpace.host
]
usernameMatch = "username IS NULL"
}
if Logger.logPII {
log.debug("Looking for login with username: \(username ?? "nil"), first arg: \(args[0] ?? "nil")")
}
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 AND hostname IS ? AND \(usernameMatch) OR hostname IS ?" +
"ORDER BY timeLastUsed DESC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginDataFactory)
}
open func getAllLogins() -> Deferred<Maybe<Cursor<Login>>> {
return searchLoginsWithQuery(nil)
}
open func searchLoginsWithQuery(_ query: String?) -> Deferred<Maybe<Cursor<Login>>> {
let projection = SQLiteLogins.LoginColumns
var searchClauses = [String]()
var args: Args? = nil
if let query = query, !query.isEmpty {
// Add wildcards to change query to 'contains in' and add them to args. We need 6 args because
// we include the where clause twice: Once for the local table and another for the remote.
args = (0..<6).map { _ in
return "%\(query)%" as String?
}
searchClauses.append("username LIKE ? ")
searchClauses.append(" password LIKE ? ")
searchClauses.append(" hostname LIKE ?")
}
let whereSearchClause = searchClauses.count > 0 ? "AND (" + searchClauses.joined(separator: "OR") + ") " : ""
let sql =
"SELECT \(projection) FROM " +
"\(TableLoginsLocal) WHERE is_deleted = 0 " + whereSearchClause +
"UNION ALL " +
"SELECT \(projection) FROM " +
"\(TableLoginsMirror) WHERE is_overridden = 0 " + whereSearchClause +
"ORDER BY hostname ASC"
return db.runQuery(sql, args: args, factory: SQLiteLogins.LoginFactory)
}
open func addLogin(_ login: LoginData) -> Success {
if let error = login.isValid.failureValue {
return deferMaybe(error)
}
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
login.hostname,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.username,
login.password,
login.guid,
dateMicro, // timeCreated
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
dateMilli, // localModified
]
let sql =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
// Shared fields.
"( hostname" +
", httpRealm" +
", formSubmitURL" +
", usernameField" +
", passwordField" +
", timesUsed" +
", username" +
", password " +
// Local metadata.
", guid " +
", timeCreated" +
", timeLastUsed" +
", timePasswordChanged" +
", local_modified " +
", is_deleted " +
", sync_status " +
") " +
"VALUES (?,?,?,?,?,1,?,?,?,?,?, " +
"?, ?, 0, \(SyncStatus.new.rawValue)" + // Metadata.
")"
return db.run(sql, withArgs: args)
>>> effect(self.notifyLoginDidChange)
}
fileprivate func cloneMirrorToOverlay(whereClause: String?, args: Args?) -> Deferred<Maybe<Int>> {
let shared = "guid, hostname, httpRealm, formSubmitURL, usernameField, passwordField, timeCreated, timeLastUsed, timePasswordChanged, timesUsed, username, password "
let local = ", local_modified, is_deleted, sync_status "
let sql = "INSERT OR IGNORE INTO \(TableLoginsLocal) (\(shared)\(local)) SELECT \(shared), NULL AS local_modified, 0 AS is_deleted, 0 AS sync_status FROM \(TableLoginsMirror) \(whereClause ?? "")"
return self.db.write(sql, withArgs: args)
}
/**
* Returns success if either a local row already existed, or
* one could be copied from the mirror.
*/
fileprivate func ensureLocalOverlayExistsForGUID(_ guid: GUID) -> Success {
let sql = "SELECT guid FROM \(TableLoginsLocal) WHERE guid = ?"
let args: Args = [guid]
let c = db.runQuery(sql, args: args, factory: { _ in 1 })
return c >>== { rows in
if rows.count > 0 {
return succeed()
}
log.debug("No overlay; cloning one for GUID \(guid).")
return self.cloneMirrorToOverlay(guid)
>>== { count in
if count > 0 {
return succeed()
}
log.warning("Failed to create local overlay for GUID \(guid).")
return deferMaybe(NoSuchRecordError(guid: guid))
}
}
}
fileprivate func cloneMirrorToOverlay(_ guid: GUID) -> Deferred<Maybe<Int>> {
let whereClause = "WHERE guid = ?"
let args: Args = [guid]
return self.cloneMirrorToOverlay(whereClause: whereClause, args: args)
}
fileprivate func markMirrorAsOverridden(_ guid: GUID) -> Success {
let args: Args = [guid]
let sql =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Replace the local DB row with the provided GUID.
* If no local overlay exists, one is first created.
*
* If `significant` is `true`, the `sync_status` of the row is bumped to at least `Changed`.
* If it's already `New`, it remains marked as `New`.
*
* This flag allows callers to make minor changes (such as incrementing a usage count)
* without triggering an upload or a conflict.
*/
open func updateLoginByGUID(_ guid: GUID, new: LoginData, significant: Bool) -> Success {
if let error = new.isValid.failureValue {
return deferMaybe(error)
}
// Right now this method is only ever called if the password changes at
// point of use, so we always set `timePasswordChanged` and `timeLastUsed`.
// We can (but don't) also assume that `significant` will always be `true`,
// at least for the time being.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let dateMicro = nowMicro
let dateMilli = nowMilli
let args: Args = [
dateMilli, // local_modified
dateMicro, // timeLastUsed
dateMicro, // timePasswordChanged
new.httpRealm,
new.formSubmitURL,
new.usernameField,
new.passwordField,
new.password,
new.hostname,
new.username,
guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?, timeLastUsed = ?, timePasswordChanged = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timesUsed = timesUsed + 1" +
", password = ?, hostname = ?, username = ?" +
// We keep rows marked as New in preference to marking them as changed. This allows us to
// delete them immediately if they don't reach the server.
(significant ? ", sync_status = max(sync_status, 1) " : "") +
" WHERE guid = ?"
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(update, withArgs: args) }
>>> effect(self.notifyLoginDidChange)
}
open func addUseOfLoginByGUID(_ guid: GUID) -> Success {
let sql =
"UPDATE \(TableLoginsLocal) SET " +
"timesUsed = timesUsed + 1, timeLastUsed = ?, local_modified = ? " +
"WHERE guid = ? AND is_deleted = 0"
// For now, mere use is not enough to flip sync_status to Changed.
let nowMicro = Date.nowMicroseconds()
let nowMilli = nowMicro / 1000
let args: Args = [nowMicro, nowMilli, guid]
return self.ensureLocalOverlayExistsForGUID(guid)
>>> { self.markMirrorAsOverridden(guid) }
>>> { self.db.run(sql, withArgs: args) }
}
open func removeLoginByGUID(_ guid: GUID) -> Success {
return removeLoginsWithGUIDs([guid])
}
fileprivate func getDeletionStatementsForGUIDs(_ guids: ArraySlice<GUID>, nowMillis: Timestamp) -> [(sql: String, args: Args?)] {
let inClause = BrowserDB.varlist(guids.count)
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause) AND sync_status = \(SyncStatus.new.rawValue)"
// Otherwise, mark it as changed.
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = \(nowMillis)" +
", sync_status = \(SyncStatus.changed.rawValue)" +
", is_deleted = 1" +
", password = ''" +
", hostname = ''" +
", username = ''" +
" WHERE guid IN \(inClause)"
let markMirrorAsOverridden =
"UPDATE \(TableLoginsMirror) SET " +
"is_overridden = 1 " +
"WHERE guid IN \(inClause)"
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) " +
"(guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let args: Args = guids.map { $0 }
return [ (delete, args), (update, args), (markMirrorAsOverridden, args), (insert, args)]
}
open func removeLoginsWithGUIDs(_ guids: [GUID]) -> Success {
let timestamp = Date.now()
return db.run(chunk(guids, by: BrowserDB.MaxVariableNumber).flatMap {
self.getDeletionStatementsForGUIDs($0, nowMillis: timestamp)
}) >>> effect(self.notifyLoginDidChange)
}
open func removeAll() -> Success {
// Immediately delete anything that's marked as new -- i.e., it's never reached
// the server. If Sync isn't set up, this will be everything.
let delete =
"DELETE FROM \(TableLoginsLocal) WHERE sync_status = \(SyncStatus.new.rawValue)"
let nowMillis = Date.now()
// Mark anything we haven't already deleted.
let update =
"UPDATE \(TableLoginsLocal) SET local_modified = \(nowMillis), sync_status = \(SyncStatus.changed.rawValue), is_deleted = 1, password = '', hostname = '', username = '' WHERE is_deleted = 0"
// Copy all the remaining rows from our mirror, marking them as locally deleted. The
// OR IGNORE will cause conflicts due to non-unique guids to be dropped, preserving
// anything we already deleted.
let insert =
"INSERT OR IGNORE INTO \(TableLoginsLocal) (guid, local_modified, is_deleted, sync_status, hostname, timeCreated, timePasswordChanged, password, username) " +
"SELECT guid, \(nowMillis), 1, \(SyncStatus.changed.rawValue), '', timeCreated, \(nowMillis)000, '', '' FROM \(TableLoginsMirror)"
// After that, we mark all of the mirror rows as overridden.
return self.db.run(delete)
>>> { self.db.run(update) }
>>> { self.db.run("UPDATE \(TableLoginsMirror) SET is_overridden = 1") }
>>> { self.db.run(insert) }
>>> effect(self.notifyLoginDidChange)
}
}
// When a server change is detected (e.g., syncID changes), we should consider shifting the contents
// of the mirror into the local overlay, allowing a content-based reconciliation to occur on the next
// full sync. Or we could flag the mirror as to-clear, download the server records and un-clear, and
// resolve the remainder on completion. This assumes that a fresh start will typically end up with
// the exact same records, so we might as well keep the shared parents around and double-check.
extension SQLiteLogins: SyncableLogins {
/**
* Delete the login with the provided GUID. Succeeds if the GUID is unknown.
*/
public func deleteByGUID(_ guid: GUID, deletedAt: Timestamp) -> Success {
// Simply ignore the possibility of a conflicting local change for now.
let local = "DELETE FROM \(TableLoginsLocal) WHERE guid = ?"
let remote = "DELETE FROM \(TableLoginsMirror) WHERE guid = ?"
let args: Args = [guid]
return self.db.run(local, withArgs: args) >>> { self.db.run(remote, withArgs: args) }
}
func getExistingMirrorRecordByGUID(_ guid: GUID) -> Deferred<Maybe<MirrorLogin?>> {
let sql = "SELECT * FROM \(TableLoginsMirror) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.MirrorLoginFactory) >>== { deferMaybe($0[0]) }
}
func getExistingLocalRecordByGUID(_ guid: GUID) -> Deferred<Maybe<LocalLogin?>> {
let sql = "SELECT * FROM \(TableLoginsLocal) WHERE guid = ? LIMIT 1"
let args: Args = [guid]
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory) >>== { deferMaybe($0[0]) }
}
fileprivate func storeReconciledLogin(_ login: Login) -> Success {
let dateMilli = Date.now()
let args: Args = [
dateMilli, // local_modified
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timeLastUsed,
login.timePasswordChanged,
login.timesUsed,
login.password,
login.hostname,
login.username,
login.guid,
]
let update =
"UPDATE \(TableLoginsLocal) SET " +
" local_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?, timeLastUsed = ?, timePasswordChanged = ?, timesUsed = ?" +
", password = ?" +
", hostname = ?, username = ?" +
", sync_status = \(SyncStatus.changed.rawValue) " +
" WHERE guid = ?"
return self.db.run(update, withArgs: args)
}
public func applyChangedLogin(_ upstream: ServerLogin) -> Success {
// Our login storage tracks the shared parent from the last sync (the "mirror").
// This allows us to conclusively determine what changed in the case of conflict.
//
// Our first step is to determine whether the record is changed or new: i.e., whether
// or not it's present in the mirror.
//
// TODO: these steps can be done in a single query. Make it work, make it right, make it fast.
// TODO: if there's no mirror record, all incoming records can be applied in one go; the only
// reason we need to fetch first is to establish the shared parent. That would be nice.
let guid = upstream.guid
return self.getExistingMirrorRecordByGUID(guid) >>== { mirror in
return self.getExistingLocalRecordByGUID(guid) >>== { local in
return self.applyChangedLogin(upstream, local: local, mirror: mirror)
}
}
}
fileprivate func applyChangedLogin(_ upstream: ServerLogin, local: LocalLogin?, mirror: MirrorLogin?) -> Success {
// Once we have the server record, the mirror record (if any), and the local overlay (if any),
// we can always know which state a record is in.
// If it's present in the mirror, then we can proceed directly to handling the change;
// we assume that once a record makes it into the mirror, that the local record association
// has already taken place, and we're tracking local changes correctly.
if let mirror = mirror {
log.debug("Mirror record found for changed record \(mirror.guid).")
if let local = local {
log.debug("Changed local overlay found for \(local.guid). Resolving conflict with 3WM.")
// * Changed remotely and locally (conflict). Resolve the conflict using a three-way merge: the
// local mirror is the shared parent of both the local overlay and the new remote record.
// Apply results as in the co-creation case.
return self.resolveConflictBetween(local: local, upstream: upstream, shared: mirror)
}
log.debug("No local overlay found. Updating mirror to upstream.")
// * Changed remotely but not locally. Apply the remote changes to the mirror.
// There is no local overlay to discard or resolve against.
return self.updateMirrorToLogin(upstream, fromPrevious: mirror)
}
// * New both locally and remotely with no shared parent (cocreation).
// Or we matched the GUID, and we're assuming we just forgot the mirror.
//
// Merge and apply the results remotely, writing the result into the mirror and discarding the overlay
// if the upload succeeded. (Doing it in this order allows us to safely replay on failure.)
//
// If the local and remote record are the same, this is trivial.
// At this point we also switch our local GUID to match the remote.
if let local = local {
// We might have randomly computed the same GUID on two devices connected
// to the same Sync account.
// With our 9-byte GUIDs, the chance of that happening is very small, so we
// assume that this device has previously connected to this account, and we
// go right ahead with a merge.
log.debug("Local record with GUID \(local.guid) but no mirror. This is unusual; assuming disconnect-reconnect scenario. Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// If it's not present, we must first check whether we have a local record that's substantially
// the same -- the co-creation or re-sync case.
//
// In this case, we apply the server record to the mirror, change the local record's GUID,
// and proceed to reconcile the change on a content basis.
return self.findLocalRecordByContent(upstream) >>== { local in
if let local = local {
log.debug("Local record \(local.guid) content-matches new remote record \(upstream.guid). Smushing.")
return self.resolveConflictWithoutParentBetween(local: local, upstream: upstream)
}
// * New upstream only; no local overlay, content-based merge,
// or shared parent in the mirror. Insert it in the mirror.
log.debug("Never seen remote record \(upstream.guid). Mirroring.")
return self.insertNewMirror(upstream)
}
}
// N.B., the final guid is sometimes a WHERE and sometimes inserted.
fileprivate func mirrorArgs(_ login: ServerLogin) -> Args {
let args: Args = [
login.serverModified,
login.httpRealm,
login.formSubmitURL,
login.usernameField,
login.passwordField,
login.timesUsed,
login.timeLastUsed,
login.timePasswordChanged,
login.timeCreated,
login.password,
login.hostname,
login.username,
login.guid,
]
return args
}
/**
* Called when we have a changed upstream record and no local changes.
* There's no need to flip the is_overridden flag.
*/
fileprivate func updateMirrorToLogin(_ login: ServerLogin, fromPrevious previous: Login) -> Success {
let args = self.mirrorArgs(login)
let sql =
"UPDATE \(TableLoginsMirror) SET " +
" server_modified = ?" +
", httpRealm = ?, formSubmitURL = ?, usernameField = ?" +
", passwordField = ?" +
// These we need to coalesce, because we might be supplying zeroes if the remote has
// been overwritten by an older client. In this case, preserve the old value in the
// mirror.
", timesUsed = coalesce(nullif(?, 0), timesUsed)" +
", timeLastUsed = coalesce(nullif(?, 0), timeLastUsed)" +
", timePasswordChanged = coalesce(nullif(?, 0), timePasswordChanged)" +
", timeCreated = coalesce(nullif(?, 0), timeCreated)" +
", password = ?, hostname = ?, username = ?" +
" WHERE guid = ?"
return self.db.run(sql, withArgs: args)
}
/**
* Called when we have a completely new record. Naturally the new record
* is marked as non-overridden.
*/
fileprivate func insertNewMirror(_ login: ServerLogin, isOverridden: Int = 0) -> Success {
let args = self.mirrorArgs(login)
let sql =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") VALUES (\(isOverridden), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"
return self.db.run(sql, withArgs: args)
}
/**
* We assume a local record matches if it has the same username (password can differ),
* hostname, httpRealm. We also check that the formSubmitURLs are either blank or have the
* same host and port.
*
* This is roughly the same as desktop's .matches():
* <https://mxr.mozilla.org/mozilla-central/source/toolkit/components/passwordmgr/nsLoginInfo.js#41>
*/
fileprivate func findLocalRecordByContent(_ login: Login) -> Deferred<Maybe<LocalLogin?>> {
let primary =
"SELECT * FROM \(TableLoginsLocal) WHERE " +
"hostname IS ? AND httpRealm IS ? AND username IS ?"
var args: Args = [login.hostname, login.httpRealm, login.username]
let sql: String
if login.formSubmitURL == nil {
sql = primary + " AND formSubmitURL IS NULL"
} else if login.formSubmitURL!.isEmpty {
sql = primary
} else {
if let hostPort = login.formSubmitURL?.asURL?.hostPort {
// Substring check will suffice for now. TODO: proper host/port check after fetching the cursor.
sql = primary + " AND (formSubmitURL = '' OR (instr(formSubmitURL, ?) > 0))"
args.append(hostPort)
} else {
log.warning("Incoming formSubmitURL is non-empty but is not a valid URL with a host. Not matching local.")
return deferMaybe(nil)
}
}
return self.db.runQuery(sql, args: args, factory: SQLiteLogins.LocalLoginFactory)
>>== { cursor in
switch cursor.count {
case 0:
return deferMaybe(nil)
case 1:
// Great!
return deferMaybe(cursor[0])
default:
// TODO: join against the mirror table to exclude local logins that
// already match a server record.
// Right now just take the first.
log.warning("Got \(cursor.count) local logins with matching details! This is most unexpected.")
return deferMaybe(cursor[0])
}
}
}
fileprivate func resolveConflictBetween(local: LocalLogin, upstream: ServerLogin, shared: Login) -> Success {
// Attempt to compute two delta sets by comparing each new record to the shared record.
// Then we can merge the two delta sets -- either perfectly or by picking a winner in the case
// of a true conflict -- and produce a resultant record.
let localDeltas = (local.localModified, local.deltas(from: shared))
let upstreamDeltas = (upstream.serverModified, upstream.deltas(from: shared))
let mergedDeltas = Login.mergeDeltas(a: localDeltas, b: upstreamDeltas)
// Not all Sync clients handle the optional timestamp fields introduced in Bug 555755.
// We might get a server record with no timestamps, and it will differ from the original
// mirror!
// We solve that by refusing to generate deltas that discard information. We'll preserve
// the local values -- either from the local record or from the last shared parent that
// still included them -- and propagate them back to the server.
// It's OK for us to reconcile and reupload; it causes extra work for every client, but
// should not cause looping.
let resultant = shared.applyDeltas(mergedDeltas)
// We can immediately write the downloaded upstream record -- the old one -- to
// the mirror store.
// We then apply this record to the local store, and mark it as needing upload.
// When the reconciled record is uploaded, it'll be flushed into the mirror
// with the correct modified time.
return self.updateMirrorToLogin(upstream, fromPrevious: shared)
>>> { self.storeReconciledLogin(resultant) }
}
fileprivate func resolveConflictWithoutParentBetween(local: LocalLogin, upstream: ServerLogin) -> Success {
// Do the best we can. Either the local wins and will be
// uploaded, or the remote wins and we delete our overlay.
if local.timePasswordChanged > upstream.timePasswordChanged {
log.debug("Conflicting records with no shared parent. Using newer local record.")
return self.insertNewMirror(upstream, isOverridden: 1)
}
log.debug("Conflicting records with no shared parent. Using newer remote record.")
let args: Args = [local.guid]
return self.insertNewMirror(upstream, isOverridden: 0)
>>> { self.db.run("DELETE FROM \(TableLoginsLocal) WHERE guid = ?", withArgs: args) }
}
public func getModifiedLoginsToUpload() -> Deferred<Maybe<[Login]>> {
let sql =
"SELECT * FROM \(TableLoginsLocal) " +
"WHERE sync_status IS NOT \(SyncStatus.synced.rawValue) AND is_deleted = 0"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: SQLiteLogins.LoginFactory)
>>== { deferMaybe($0.asArray()) }
}
public func getDeletedLoginsToUpload() -> Deferred<Maybe<[GUID]>> {
// There are no logins that are marked as deleted that were not originally synced --
// others are deleted immediately.
let sql =
"SELECT guid FROM \(TableLoginsLocal) " +
"WHERE is_deleted = 1"
// Swift 2.0: use Cursor.asArray directly.
return self.db.runQuery(sql, args: nil, factory: { return $0["guid"] as! GUID })
>>== { deferMaybe($0.asArray()) }
}
/**
* Chains through the provided timestamp.
*/
public func markAsSynchronized<T: Collection>(_ guids: T, modified: Timestamp) -> Deferred<Maybe<Timestamp>> where T.Iterator.Element == GUID {
// Update the mirror from the local record that we just uploaded.
// sqlite doesn't support UPDATE FROM, so instead of running 10 subqueries * n GUIDs,
// we issue a single DELETE and a single INSERT on the mirror, then throw away the
// local overlay that we just uploaded with another DELETE.
log.debug("Marking \(guids.count) GUIDs as synchronized.")
let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let inClause = BrowserDB.varlist(args.count)
let delMirror = "DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)"
let insMirror =
"INSERT OR IGNORE INTO \(TableLoginsMirror) (" +
" is_overridden, server_modified" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid" +
") SELECT 0, \(modified)" +
", httpRealm, formSubmitURL, usernameField" +
", passwordField, timesUsed, timeLastUsed, timePasswordChanged, timeCreated" +
", password, hostname, username, guid " +
"FROM \(TableLoginsLocal) " +
"WHERE guid IN \(inClause)"
let delLocal = "DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)"
return [(delMirror, args),
(insMirror, args),
(delLocal, args)]
}
return self.db.run(queries)
>>> always(modified)
}
public func markAsDeleted<T: Collection>(_ guids: T) -> Success where T.Iterator.Element == GUID {
log.debug("Marking \(guids.count) GUIDs as deleted.")
let queries: [(String, Args?)] = chunkCollection(guids, by: BrowserDB.MaxVariableNumber) { guids in
let args: Args = guids.map { $0 }
let inClause = BrowserDB.varlist(args.count)
return [("DELETE FROM \(TableLoginsMirror) WHERE guid IN \(inClause)", args),
("DELETE FROM \(TableLoginsLocal) WHERE guid IN \(inClause)", args)]
}
return self.db.run(queries)
}
public func hasSyncedLogins() -> Deferred<Maybe<Bool>> {
let checkLoginsMirror = "SELECT 1 FROM \(TableLoginsMirror)"
let checkLoginsLocal = "SELECT 1 FROM \(TableLoginsLocal) WHERE sync_status IS NOT \(SyncStatus.new.rawValue)"
let sql = "\(checkLoginsMirror) UNION ALL \(checkLoginsLocal)"
return self.db.queryReturnsResults(sql)
}
}
extension SQLiteLogins: ResettableSyncStorage {
/**
* Clean up any metadata.
* TODO: is this safe for a regular reset? It forces a content-based merge.
*/
public func resetClient() -> Success {
// Clone all the mirrors so we don't lose data.
return self.cloneMirrorToOverlay(whereClause: nil, args: nil)
// Drop all of the mirror data.
>>> { self.db.run("DELETE FROM \(TableLoginsMirror)") }
// Mark all of the local data as new.
>>> { self.db.run("UPDATE \(TableLoginsLocal) SET sync_status = \(SyncStatus.new.rawValue)") }
}
}
extension SQLiteLogins: AccountRemovalDelegate {
public func onRemovedAccount() -> Success {
return self.resetClient()
}
}
| mpl-2.0 | aefe57ca8c50581b5610f05bfd9e20a1 | 42.154154 | 204 | 0.607293 | 4.830364 | false | false | false | false |
xivol/MCS-V3-Mobile | assignments/task1/BattleShip.playground/Sources/BattleShipTracker.swift | 1 | 1364 | import Foundation
public class BattleShipPlayer: Player {
var field: BattleField
var ships: [Ship]
public let name: String
public func saveEnemyAnswer(_ xPos: Int, yPos: Int, answer: FireResult) {
switch answer {
case .misses:
field.markCellAtAs(xPos, yPos: yPos, state: .missed)
default:
field.markCellAtAs(xPos, yPos: yPos, state: .enemyCell)
}
}
public func doEnemyStep(_ xPos: Int, yPos: Int) -> FireResult {
if let shipIndex = ships.index(where: { $0.isHit(xPos, yPos: yPos)}) {
if ships[shipIndex].alive {
return .injured
}else {
ships.remove(at: shipIndex)
return .killed
}
}
return .misses
}
public func didThisStepBefore(_ position: (xPos: Int, yPos: Int)) -> Bool {
return !field.isNonTouchedPosition(position.xPos, yPos: position.yPos)
}
public var alive: Bool {
get {
return ships.count != 0
}
}
public init(name: String, _ ships: [Ship] = Array()) {
field = BattleField()
self.ships = ships
self.name = name
}
}
public class BattleShipTracker: BattleShipDelegate {
public func gameDidStartFire(_ game: FireBasedGame) {
print("===-===-===")
}
public func playerDidStartFire(_ player: Player) {
print("\(player.name) is choosing cell")
}
public init() {}
}
| mit | c565baa62955633003d80c0c6503013c | 20.3125 | 77 | 0.616569 | 3.656836 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/Comments/Views/Cells/CommentViewMoreRepliesFailedCell.swift | 1 | 2637 | import KsApi
import Library
import Prelude
import UIKit
final class CommentViewMoreRepliesFailedCell: UITableViewCell, ValueCell {
// MARK: - Properties
private lazy var bodyTextLabel: UILabel = { UILabel(frame: .zero) }()
private lazy var retryImageView = {
UIImageView(frame: .zero)
|> \.image .~ Library.image(named: "circle-back")
|> \.contentMode .~ .scaleAspectFit
}()
private lazy var retryImageViewStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var rootStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.bindStyles()
self.configureViews()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
_ = self.bodyTextLabel
|> bodyTextLabelStyle
_ = self.retryImageViewStackView
|> \.axis .~ .vertical
_ = self.rootStackView
|> rootStackViewStyle
}
// MARK: - Configuration
internal func configureWith(value _: Void) {
return
}
private func configureViews() {
_ = (self.rootStackView, self.contentView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = ([self.retryImageViewStackView, self.bodyTextLabel], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
_ = ([self.retryImageView, UIView()], self.retryImageViewStackView)
|> ksr_addArrangedSubviewsToStackView()
NSLayoutConstraint.activate([
self.retryImageView.widthAnchor.constraint(equalToConstant: Styles.grid(3))
])
}
}
// MARK: Styles
private let bodyTextLabelStyle: LabelStyle = { label in
label
|> \.font .~ UIFont.ksr_subhead()
|> \.lineBreakMode .~ .byWordWrapping
|> \.numberOfLines .~ 0
|> \.textColor .~ .ksr_celebrate_700
|> \.text .~ Strings.Couldnt_load_more_comments_Tap_to_retry()
}
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .horizontal
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.insetsLayoutMarginsFromSafeArea .~ false
|> \.layoutMargins .~ .init(
top: Styles.grid(1),
left: Styles.grid(CommentCellStyles.Content.leftIndentWidth),
bottom: Styles.grid(1),
right: Styles.grid(1)
)
|> \.spacing .~ Styles.grid(1)
}
| apache-2.0 | 5e322b2808845b41865d2f675a741eb8 | 24.852941 | 81 | 0.671976 | 4.61014 | false | false | false | false |
algolia/algoliasearch-client-swift | Sources/AlgoliaSearchClient/Models/Synonym/SynonymQuery.swift | 1 | 1956 | //
// SynonymQuery.swift
//
//
// Created by Vladislav Fitc on 11/05/2020.
//
import Foundation
public struct SynonymQuery {
/// Full text query.
/// - Engine default: ""
public var query: String?
/// The page to fetch when browsing through several pages of results. This value is zero-based.
/// - Engine default: 0
public var page: Int?
/// The number of synonyms to return for each call.
/// Engine default: 100
public var hitsPerPage: Int?
/// Restrict the search to a specific SynonymType.
/// Engine default: []
public var synonymTypes: [SynonymType]?
public init() {}
}
extension SynonymQuery: ExpressibleByStringInterpolation {
public init(stringLiteral value: String) {
self.query = value
}
}
extension SynonymQuery: Builder {}
extension SynonymQuery: Codable {
enum CodingKeys: String, CodingKey {
case query
case page
case hitsPerPage
case synonymTypes = "type"
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.query = try container.decodeIfPresent(forKey: .query)
self.page = try container.decodeIfPresent(forKey: .page)
self.hitsPerPage = try container.decodeIfPresent(forKey: .hitsPerPage)
let rawSynonymTypes: String? = try container.decodeIfPresent(forKey: .synonymTypes)
self.synonymTypes = rawSynonymTypes.flatMap { $0.split(separator: ",").map(String.init).compactMap(SynonymType.init) }
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encodeIfPresent(query, forKey: .query)
try container.encodeIfPresent(page, forKey: .page)
try container.encodeIfPresent(hitsPerPage, forKey: .hitsPerPage)
let rawSynonymTypes: String? = synonymTypes.flatMap { $0.map(\.rawValue).joined(separator: ",") }
try container.encodeIfPresent(rawSynonymTypes, forKey: .synonymTypes)
}
}
| mit | d2c940b2d725ab435bfbb3be4c8e7bcf | 27.347826 | 122 | 0.716258 | 3.967546 | false | false | false | false |
rstgroup/xcode-project-template | {{cookiecutter.app_name}}/{{cookiecutter.app_name}}/Libraries/LaurineGenerator.swift | 1 | 71010 | #!/usr/bin/env xcrun -sdk macosx swift
//
// Laurine - Storyboard Generator Script
//
// Generate swift localization file based on localizables.string
//
// Usage:
// laurine.swift Main.storyboard > Output.swift
//
// Licence: MIT
// Author: Jiลรญ Tลeฤรกk http://www.jiritrecak.com @jiritrecak
//
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - CommandLine Tool
/* NOTE *
* I am using command line tool for parsing of the input / output arguments. Since static frameworks are not yet
* supported, I just hardcoded entire project to keep it.
* For whoever is interested in the project, please check their repository. It rocks!
* I'm not an author of the code that follows. Licence kept intact.
*
* https://github.com/jatoben/CommandLine
*
*/
/*
* CommandLine.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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
/* Required for setlocale(3) */
#if os(OSX)
import Darwin
#elseif os(Linux)
import Glibc
#endif
let ShortOptionPrefix = "-"
let LongOptionPrefix = "--"
/* Stop parsing arguments when an ArgumentStopper (--) is detected. This is a GNU getopt
* convention; cf. https://www.gnu.org/prep/standards/html_node/Command_002dLine-Interfaces.html
*/
let ArgumentStopper = "--"
/* Allow arguments to be attached to flags when separated by this character.
* --flag=argument is equivalent to --flag argument
*/
let ArgumentAttacher: Character = "="
/* An output stream to stderr; used by CommandLine.printUsage(). */
private struct StderrOutputStream: TextOutputStream {
static let stream = StderrOutputStream()
func write(_ s: String) {
fputs(s, stderr)
}
}
/**
* The CommandLine class implements a command-line interface for your app.
*
* To use it, define one or more Options (see Option.swift) and add them to your
* CommandLine object, then invoke `parse()`. Each Option object will be populated with
* the value given by the user.
*
* If any required options are missing or if an invalid value is found, `parse()` will throw
* a `ParseError`. You can then call `printUsage()` to output an automatically-generated usage
* message.
*/
open class CommandLine {
fileprivate var _arguments: [String]
fileprivate var _options: [Option] = [Option]()
fileprivate var _maxFlagDescriptionWidth: Int = 0
fileprivate var _usedFlags: Set<String> {
var usedFlags = Set<String>(minimumCapacity: _options.count * 2)
for option in _options {
for case let flag? in [option.shortFlag, option.longFlag] {
usedFlags.insert(flag)
}
}
return usedFlags
}
/**
* After calling `parse()`, this property will contain any values that weren't captured
* by an Option. For example:
*
* ```
* let cli = CommandLine()
* let fileType = StringOption(shortFlag: "t", longFlag: "type", required: true, helpMessage: "Type of file")
*
* do {
* try cli.parse()
* print("File type is \(type), files are \(cli.unparsedArguments)")
* catch {
* cli.printUsage(error)
* exit(EX_USAGE)
* }
*
* ---
*
* $ ./readfiles --type=pdf ~/file1.pdf ~/file2.pdf
* File type is pdf, files are ["~/file1.pdf", "~/file2.pdf"]
* ```
*/
open fileprivate(set) var unparsedArguments: [String] = [String]()
/**
* If supplied, this function will be called when printing usage messages.
*
* You can use the `defaultFormat` function to get the normally-formatted
* output, either before or after modifying the provided string. For example:
*
* ```
* let cli = CommandLine()
* cli.formatOutput = { str, type in
* switch(type) {
* case .Error:
* // Make errors shouty
* return defaultFormat(str.uppercaseString, type: type)
* case .OptionHelp:
* // Don't use the default indenting
* return ">> \(s)\n"
* default:
* return defaultFormat(str, type: type)
* }
* }
* ```
*
* - note: Newlines are not appended to the result of this function. If you don't use
* `defaultFormat()`, be sure to add them before returning.
*/
open var formatOutput: ((String, OutputType) -> String)?
/**
* The maximum width of all options' `flagDescription` properties; provided for use by
* output formatters.
*
* - seealso: `defaultFormat`, `formatOutput`
*/
open var maxFlagDescriptionWidth: Int {
if _maxFlagDescriptionWidth == 0 {
_maxFlagDescriptionWidth = _options.map { $0.flagDescription.characters.count }.sorted().first ?? 0
}
return _maxFlagDescriptionWidth
}
/**
* The type of output being supplied to an output formatter.
*
* - seealso: `formatOutput`
*/
public enum OutputType {
/** About text: `Usage: command-example [options]` and the like */
case about
/** An error message: `Missing required option --extract` */
case error
/** An Option's `flagDescription`: `-h, --help:` */
case optionFlag
/** An Option's help message */
case optionHelp
}
/** A ParseError is thrown if the `parse()` method fails. */
public enum ParseError: Error, CustomStringConvertible {
/** Thrown if an unrecognized argument is passed to `parse()` in strict mode */
case InvalidArgument(String)
/** Thrown if the value for an Option is invalid (e.g. a string is passed to an IntOption) */
case InvalidValueForOption(Option, [String])
/** Thrown if an Option with required: true is missing */
case MissingRequiredOptions([Option])
public var description: String {
switch self {
case let .InvalidArgument(arg):
return "Invalid argument: \(arg)"
case let .InvalidValueForOption(opt, vals):
let vs = vals.joined(separator: ", ")
return "Invalid value(s) for option \(opt.flagDescription): \(vs)"
case let .MissingRequiredOptions(opts):
return "Missing required options: \(opts.map { return $0.flagDescription })"
}
}
}
/**
* Initializes a CommandLine object.
*
* - parameter arguments: Arguments to parse. If omitted, the arguments passed to the app
* on the command line will automatically be used.
*
* - returns: An initalized CommandLine object.
*/
public init(arguments: [String] = Swift.CommandLine.arguments) {
self._arguments = arguments
/* Initialize locale settings from the environment */
setlocale(LC_ALL, "")
}
/* Returns all argument values from flagIndex to the next flag or the end of the argument array. */
private func _getFlagValues(_ flagIndex: Int, _ attachedArg: String? = nil) -> [String] {
var args: [String] = [String]()
var skipFlagChecks = false
if let a = attachedArg {
args.append(a)
}
for i in flagIndex + 1 ..< _arguments.count {
if !skipFlagChecks {
if _arguments[i] == ArgumentStopper {
skipFlagChecks = true
continue
}
if _arguments[i].hasPrefix(ShortOptionPrefix) && Int(_arguments[i]) == nil &&
Double(_arguments[i]) == nil {
break
}
}
args.append(_arguments[i])
}
return args
}
/**
* Adds an Option to the command line.
*
* - parameter option: The option to add.
*/
public func addOption(_ option: Option) {
let uf = _usedFlags
for case let flag? in [option.shortFlag, option.longFlag] {
assert(!uf.contains(flag), "Flag '\(flag)' already in use")
}
_options.append(option)
_maxFlagDescriptionWidth = 0
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: An array containing the options to add.
*/
public func addOptions(_ options: [Option]) {
for o in options {
addOption(o)
}
}
/**
* Adds one or more Options to the command line.
*
* - parameter options: The options to add.
*/
public func addOptions(_ options: Option...) {
for o in options {
addOption(o)
}
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: An array containing the options to set.
*/
public func setOptions(_ options: [Option]) {
_options = [Option]()
addOptions(options)
}
/**
* Sets the command line Options. Any existing options will be overwritten.
*
* - parameter options: The options to set.
*/
public func setOptions(_ options: Option...) {
_options = [Option]()
addOptions(options)
}
/**
* Parses command-line arguments into their matching Option values.
*
* - parameter strict: Fail if any unrecognized flags are present (default: false).
*
* - throws: A `ParseError` if argument parsing fails:
* - `.InvalidArgument` if an unrecognized flag is present and `strict` is true
* - `.InvalidValueForOption` if the value supplied to an option is not valid (for
* example, a string is supplied for an IntOption)
* - `.MissingRequiredOptions` if a required option isn't present
*/
open func parse(strict: Bool = false) throws {
var strays = _arguments
/* Nuke executable name */
strays[0] = ""
let argumentsEnumerator = _arguments.enumerated()
for (idx, arg) in argumentsEnumerator {
if arg == ArgumentStopper {
break
}
if !arg.hasPrefix(ShortOptionPrefix) {
continue
}
let skipChars = arg.hasPrefix(LongOptionPrefix) ?
LongOptionPrefix.characters.count : ShortOptionPrefix.characters.count
let flagWithArg = arg[arg.index(arg.startIndex, offsetBy: skipChars)..<arg.endIndex]
/* The argument contained nothing but ShortOptionPrefix or LongOptionPrefix */
if flagWithArg.isEmpty {
continue
}
/* Remove attached argument from flag */
let splitFlag = flagWithArg.split(separator: ArgumentAttacher, maxSplits: 1)
let flag = String(splitFlag[0])
let attachedArg: String? = splitFlag.count == 2 ? String(splitFlag[1]) : nil
var flagMatched = false
for option in _options where option.flagMatch(flag) {
let vals = self._getFlagValues(idx, attachedArg)
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx...claimedIdx {
strays[i] = ""
}
flagMatched = true
break
}
/* Flags that do not take any arguments can be concatenated */
let flagLength = flag.characters.count
if !flagMatched && !arg.hasPrefix(LongOptionPrefix) {
let flagCharactersEnumerator = flag.characters.enumerated()
for (i, c) in flagCharactersEnumerator {
for option in _options where option.flagMatch(String(c)) {
/* Values are allowed at the end of the concatenated flags, e.g.
* -xvf <file1> <file2>
*/
let vals = (i == flagLength - 1) ? self._getFlagValues(idx, attachedArg) : [String]()
guard option.setValue(vals) else {
throw ParseError.InvalidValueForOption(option, vals)
}
var claimedIdx = idx + option.claimedValues
if attachedArg != nil { claimedIdx -= 1 }
for i in idx...claimedIdx {
strays[i] = ""
}
flagMatched = true
break
}
}
}
/* Invalid flag */
guard !strict || flagMatched else {
throw ParseError.InvalidArgument(arg)
}
}
/* Check to see if any required options were not matched */
let missingOptions = _options.filter { $0.required && !$0.wasSet }
guard missingOptions.count == 0 else {
throw ParseError.MissingRequiredOptions(missingOptions)
}
unparsedArguments = strays.filter { $0 != "" }
}
/**
* Provides the default formatting of `printUsage()` output.
*
* - parameter s: The string to format.
* - parameter type: Type of output.
*
* - returns: The formatted string.
* - seealso: `formatOutput`
*/
open func defaultFormat(_ s: String, type: OutputType) -> String {
switch type {
case .about:
return "\(s)\n"
case .error:
return "\(s)\n\n"
case .optionFlag:
return " \(s.padding(toLength: maxFlagDescriptionWidth, withPad: " ", startingAt: 0)):\n"
case .optionHelp:
return " \(s)\n"
}
}
/* printUsage() is generic for OutputStreamType because the Swift compiler crashes
* on inout protocol function parameters in Xcode 7 beta 1 (rdar://21372694).
*/
/**
* Prints a usage message.
*
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: TextOutputStream>(_ to: inout TargetStream) {
/* Nil coalescing operator (??) doesn't work on closures :( */
let format = formatOutput != nil ? formatOutput! : defaultFormat
let name = _arguments[0]
print(format("Usage: \(name) [options]", .about), terminator: "", to: &to)
for opt in _options {
print(format(opt.flagDescription, .optionFlag), terminator: "", to: &to)
print(format(opt.helpMessage, .optionHelp), terminator: "", to: &to)
}
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
* - parameter to: An OutputStreamType to write the error message to.
*/
public func printUsage<TargetStream: TextOutputStream>(_ error: Error, to: inout TargetStream) {
let format = formatOutput != nil ? formatOutput! : defaultFormat
print(format("\(error)", .error), terminator: "", to: &to)
printUsage(&to)
}
/**
* Prints a usage message.
*
* - parameter error: An error thrown from `parse()`. A description of the error
* (e.g. "Missing required option --extract") will be printed before the usage message.
*/
public func printUsage(_ error: Error) {
var out = StderrOutputStream.stream
printUsage(error, to: &out)
}
/**
* Prints a usage message.
*/
open func printUsage() {
var out = StderrOutputStream.stream
printUsage(&out)
}
}
/*
* Option.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
/**
* The base class for a command-line option.
*/
open class Option {
open let shortFlag: String?
open let longFlag: String?
open let required: Bool
open let helpMessage: String
/** True if the option was set when parsing command-line arguments */
open var wasSet: Bool {
return false
}
open var claimedValues: Int { return 0 }
open var flagDescription: String {
switch (shortFlag, longFlag) {
case let (sf?, lf?):
return "\(ShortOptionPrefix)\(sf), \(LongOptionPrefix)\(lf)"
case (nil, let lf?):
return "\(LongOptionPrefix)\(lf)"
case (let sf?, nil):
return "\(ShortOptionPrefix)\(sf)"
default:
return ""
}
}
internal init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
if let sf = shortFlag {
assert(sf.characters.count == 1, "Short flag must be a single character")
assert(Int(sf) == nil && Double(sf) == nil, "Short flag cannot be a numeric value")
}
if let lf = longFlag {
assert(Int(lf) == nil && Double(lf) == nil, "Long flag cannot be a numeric value")
}
self.shortFlag = shortFlag
self.longFlag = longFlag
self.helpMessage = helpMessage
self.required = required
}
/* The optional casts in these initalizers force them to call the private initializer. Without
* the casts, they recursively call themselves.
*/
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
func flagMatch(_ flag: String) -> Bool {
return flag == shortFlag || flag == longFlag
}
func setValue(_ values: [String]) -> Bool {
return false
}
}
/**
* A boolean option. The presence of either the short or long flag will set the value to true;
* absence of the flag(s) is equivalent to false.
*/
open class BoolOption: Option {
fileprivate var _value: Bool = false
open var value: Bool {
return _value
}
override open var wasSet: Bool {
return _value
}
override func setValue(_ values: [String]) -> Bool {
_value = true
return true
}
}
/** An option that accepts a positive or negative integer value. */
open class IntOption: Option {
fileprivate var _value: Int?
open var value: Int? {
return _value
}
override open var wasSet: Bool {
return _value != nil
}
override open var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(_ values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = Int(values[0]) {
_value = val
return true
}
return false
}
}
/**
* An option that represents an integer counter. Each time the short or long flag is found
* on the command-line, the counter will be incremented.
*/
open class CounterOption: Option {
fileprivate var _value: Int = 0
open var value: Int {
return _value
}
override open var wasSet: Bool {
return _value > 0
}
open func reset() {
_value = 0
}
override func setValue(_ values: [String]) -> Bool {
_value += 1
return true
}
}
/** An option that accepts a positive or negative floating-point value. */
open class DoubleOption: Option {
fileprivate var _value: Double?
open var value: Double? {
return _value
}
override open var wasSet: Bool {
return _value != nil
}
override open var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(_ values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let val = values[0].toDouble() {
_value = val
return true
}
return false
}
}
/** An option that accepts a string value. */
open class StringOption: Option {
fileprivate var _value: String?
open var value: String? {
return _value
}
override open var wasSet: Bool {
return _value != nil
}
override open var claimedValues: Int {
return _value != nil ? 1 : 0
}
override func setValue(_ values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values[0]
return true
}
}
/** An option that accepts one or more string values. */
open class MultiStringOption: Option {
fileprivate var _value: [String]?
open var value: [String]? {
return _value
}
override open var wasSet: Bool {
return _value != nil
}
override open var claimedValues: Int {
if let v = _value {
return v.count
}
return 0
}
override func setValue(_ values: [String]) -> Bool {
if values.count == 0 {
return false
}
_value = values
return true
}
}
/** An option that represents an enum value. */
public class EnumOption<T: RawRepresentable>: Option where T.RawValue == String {
private var _value: T?
public var value: T? {
return _value
}
override public var wasSet: Bool {
return _value != nil
}
override public var claimedValues: Int {
return _value != nil ? 1 : 0
}
/* Re-defining the intializers is necessary to make the Swift 2 compiler happy, as
* of Xcode 7 beta 2.
*/
internal override init(_ shortFlag: String?, _ longFlag: String?, _ required: Bool, _ helpMessage: String) {
super.init(shortFlag, longFlag, required, helpMessage)
}
/** Initializes a new Option that has both long and short flags. */
public convenience init(shortFlag: String, longFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, longFlag, required, helpMessage)
}
/** Initializes a new Option that has only a short flag. */
public convenience init(shortFlag: String, required: Bool = false, helpMessage: String) {
self.init(shortFlag as String?, nil, required, helpMessage)
}
/** Initializes a new Option that has only a long flag. */
public convenience init(longFlag: String, required: Bool = false, helpMessage: String) {
self.init(nil, longFlag as String?, required, helpMessage)
}
override func setValue(_ values: [String]) -> Bool {
if values.count == 0 {
return false
}
if let v = T(rawValue: values[0]) {
_value = v
return true
}
return false
}
}
/*
* StringExtensions.swift
* Copyright (c) 2014 Ben Gollmer.
*
* 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.
*/
internal extension String {
/* Retrieves locale-specified decimal separator from the environment
* using localeconv(3).
*/
fileprivate func _localDecimalPoint() -> Character {
let locale = localeconv()
if locale != nil {
if let decimalPoint = locale?.pointee.decimal_point {
return Character(UnicodeScalar(UInt32(decimalPoint.pointee))!)
}
}
return "."
}
/**
* Attempts to parse the string value into a Double.
*
* - returns: A Double if the string can be parsed, nil otherwise.
*/
func toDouble() -> Double? {
var characteristic: String = "0"
var mantissa: String = "0"
var inMantissa: Bool = false
var isNegative: Bool = false
let decimalPoint = self._localDecimalPoint()
#if swift(>=3.0)
let charactersEnumerator = self.characters.enumerated()
#else
let charactersEnumerator = self.characters.enumerated()
#endif
for (i, c) in charactersEnumerator {
if i == 0 && c == "-" {
isNegative = true
continue
}
if c == decimalPoint {
inMantissa = true
continue
}
if Int(String(c)) != nil {
if !inMantissa {
characteristic.append(c)
} else {
mantissa.append(c)
}
} else {
/* Non-numeric character found, bail */
return nil
}
}
let doubleCharacteristic = Double(Int(characteristic)!)
return (doubleCharacteristic +
Double(Int(mantissa)!) / pow(Double(10), Double(mantissa.characters.count - 1))) *
(isNegative ? -1 : 1)
}
/**
* Splits a string into an array of string components.
*
* - parameter by: The character to split on.
* - parameter maxSplits: The maximum number of splits to perform. If 0, all possible splits are made.
*
* - returns: An array of string components.
*/
func split(by: Character, maxSplits: Int = 0) -> [String] {
var s = [String]()
var numSplits = 0
var curIdx = self.startIndex
for i in self.characters.indices {
let c = self[i]
if c == by && (maxSplits == 0 || numSplits < maxSplits) {
s.append(String(self[curIdx..<i]))
curIdx = self.index(after: i)
numSplits += 1
}
}
if curIdx != self.endIndex {
s.append(String(self[curIdx..<self.endIndex]))
}
return s
}
/**
* Pads a string to the specified width.
*
* - parameter toWidth: The width to pad the string to.
* - parameter by: The character to use for padding.
*
* - returns: A new string, padded to the given width.
*/
func padded(toWidth width: Int, with padChar: Character = " ") -> String {
var s = self
var currentLength = self.characters.count
while currentLength < width {
s.append(padChar)
currentLength += 1
}
return s
}
/**
* Wraps a string to the specified width.
*
* This just does simple greedy word-packing, it doesn't go full Knuth-Plass.
* If a single word is longer than the line width, it will be placed (unsplit)
* on a line by itself.
*
* - parameter atWidth: The maximum length of a line.
* - parameter wrapBy: The line break character to use.
* - parameter splitBy: The character to use when splitting the string into words.
*
* - returns: A new string, wrapped at the given width.
*/
func wrapped(atWidth width: Int, wrapBy: Character = "\n", splitBy: Character = " ") -> String {
var s = ""
var currentLineWidth = 0
for word in self.split(by: splitBy) {
let wordLength = word.characters.count
if currentLineWidth + wordLength + 1 > width {
/* Word length is greater than line length, can't wrap */
if wordLength >= width {
s += word
}
s.append(wrapBy)
currentLineWidth = 0
}
currentLineWidth += wordLength + 1
s += word
s.append(splitBy)
}
return s
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Import
import Foundation
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Definitions
private var BASE_CLASS_NAME: String = "Localizations"
private let OBJC_CLASS_PREFIX: String = "_"
private var OBJC_CUSTOM_SUPERCLASS: String?
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Extensions
private extension String {
func alphanumericString(exceptionCharactersFromString: String = "") -> String {
// removes diacritic marks
var copy = self.folding(options: .diacriticInsensitive, locale: NSLocale.current)
// removes all non alphanumeric characters
var characterSet = CharacterSet.alphanumerics.inverted
// don't remove the characters that are given
characterSet.remove(charactersIn: exceptionCharactersFromString)
copy = copy.components(separatedBy: characterSet).reduce("") { $0 + $1 }
return copy
}
func replacedNonAlphaNumericCharacters(replacement: UnicodeScalar) -> String {
return String(describing: UnicodeScalarView(self.unicodeScalars.map { CharacterSet.alphanumerics.contains(($0)) ? $0 : replacement }))
}
}
private extension NSCharacterSet {
// thanks to http://stackoverflow.com/a/27698155/354018
func containsCharacter(c: Character) -> Bool {
let s = String(c)
let ix = s.startIndex
let ix2 = s.endIndex
let result = s.rangeOfCharacter(from: self as CharacterSet, options: [], range: ix..<ix2)
return result != nil
}
}
private extension NSMutableDictionary {
func setObject(object: AnyObject!, forKeyPath: String, delimiter: String = ".") {
self.setObject(object: object, onObject : self, forKeyPath: forKeyPath, createIntermediates: true, replaceIntermediates: true, delimiter: delimiter)
}
func setObject(object: AnyObject, onObject: AnyObject, forKeyPath keyPath: String, createIntermediates: Bool, replaceIntermediates: Bool, delimiter: String) {
// Make keypath mutable
var primaryKeypath = keyPath
// Replace delimiter with dot delimiter - otherwise key value observing does not work properly
let baseDelimiter = "."
primaryKeypath = primaryKeypath.replacingOccurrences(of: delimiter, with: baseDelimiter, options: NSString.CompareOptions.literal, range: nil)
// Create path components separated by delimiter (. by default) and get key for root object
// filter empty path components, these can be caused by delimiter at beginning/end, or multiple consecutive delimiters in the middle
let pathComponents: Array<String> = primaryKeypath.components(separatedBy: baseDelimiter).filter({ $0.characters.count > 0 })
primaryKeypath = pathComponents.joined(separator: baseDelimiter)
let rootKey: String = pathComponents[0]
if pathComponents.count == 1 {
onObject.set(object, forKey: rootKey)
}
let replacementDictionary: NSMutableDictionary = NSMutableDictionary()
// Store current state for further replacement
var previousObject: AnyObject? = onObject
var previousReplacement: NSMutableDictionary = replacementDictionary
var reachedDictionaryLeaf: Bool = false
// Traverse through path from root to deepest level
for path: String in pathComponents {
let currentObject: AnyObject? = reachedDictionaryLeaf ? nil : previousObject?.object(forKey: path) as AnyObject?
// Check if object already exists. If not, create new level, if allowed, or end
if currentObject == nil {
reachedDictionaryLeaf = true
if createIntermediates {
let newNode: NSMutableDictionary = NSMutableDictionary()
previousReplacement.setObject(newNode, forKey: path as NSString)
previousReplacement = newNode
} else {
return
}
// If it does and it is dictionary, create mutable copy and assign new node there
} else if currentObject is NSDictionary {
let newNode: NSMutableDictionary = NSMutableDictionary(dictionary: currentObject as! [NSObject : AnyObject])
previousReplacement.setObject(newNode, forKey: path as NSString)
previousReplacement = newNode
// It exists but it is not NSDictionary, so we replace it, if allowed, or end
} else {
reachedDictionaryLeaf = true
if replaceIntermediates {
let newNode: NSMutableDictionary = NSMutableDictionary()
previousReplacement.setObject(newNode, forKey: path as NSString)
previousReplacement = newNode
} else {
return
}
}
// Replace previous object with the new one
previousObject = currentObject
}
// Replace root object with newly created n-level dictionary
replacementDictionary.setValue(object, forKeyPath: primaryKeypath)
onObject.set(replacementDictionary.object(forKey: rootKey), forKey: rootKey)
}
}
private extension FileManager {
func isDirectoryAtPath(path: String) -> Bool {
let manager = FileManager.default
do {
let attribs: [FileAttributeKey : Any]? = try manager.attributesOfItem(atPath: path)
if let attributes = attribs {
let type = attributes[FileAttributeKey.type] as? String
return type == FileAttributeType.typeDirectory.rawValue
}
} catch _ {
return false
}
}
}
private extension String {
var camelCasedString: String {
let inputArray = self.components(separatedBy: (CharacterSet.alphanumerics.inverted))
return inputArray.reduce("", {$0 + $1.capitalized})
}
var nolineString: String {
let set = CharacterSet.newlines
let components = self.components(separatedBy: set)
return components.joined(separator: " ")
}
func isFirstLetterDigit() -> Bool {
guard let c: Character = self.characters.first else {
return false
}
let s = String(c).unicodeScalars
let uni = s[s.startIndex]
return (uni.value >= 48 && uni.value <= 57)
// return String(describing: UnicodeScalarView(self.unicodeScalars.map { CharacterSet.alphanumerics.contains(($0)) ? $0 : replacement }))
}
func isReservedKeyword(lang: Runtime.ExportLanguage) -> Bool {
// Define keywords for each language
var keywords: [String] = []
if lang == .ObjC {
keywords = ["auto", "break", "case", "char", "const", "continue", "default", "do", "double", "else", "enum", "extern", "float", "for", "goto", "if", "inline", "int", "long",
"register", "restrict", "return", "short", "signed", "sizeof", "static", "struct", "swift", "typedef", "union", "unsigned", "void", "volatile", "while",
"BOOL", "Class", "bycopy", "byref", "id", "IMP", "in", "inout", "nil", "NO", "NULL", "oneway", "out", "Protocol", "SEL", "self", "super", "YES"]
} else if lang == .Swift {
keywords = ["class", "deinit", "enum", "extension", "func", "import", "init", "inout", "internal", "let", "operator", "private", "protocol", "public", "static", "struct", "subscript", "typealias", "var", "break", "case", "continue", "default", "defer", "do", "else", "fallthrough", "for", "guard", "if", "in", "repeat", "return", "switch", "where", "while", "as", "catch", "dynamicType", "false", "is", "nil", "rethrows", "super", "self", "Self", "throw", "throws", "true", "try", "type", "__COLUMN__", "__FILE__", "__FUNCTION__", "__LINE__"]
}
// Check if it contains that keyword
return keywords.index(of: self) != nil
}
}
private enum SpecialCharacter {
case String
case Double
case Int
case Int64
case UInt
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Localization Class implementation
class Localization {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
var flatStructure = NSDictionary()
var objectStructure = NSMutableDictionary()
var autocapitalize: Bool = true
var table: String?
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Setup
convenience init(inputFile: URL, delimiter: String, autocapitalize: Bool, table: String? = nil) {
self.init()
self.table = table
// Load localization file
self.processInputFromFile(file: inputFile, delimiter: delimiter, autocapitalize: autocapitalize)
}
func processInputFromFile(file: URL, delimiter: String, autocapitalize: Bool) {
guard let dictionary = NSDictionary(contentsOfFile: file.path) else {
// TODO: Better error handling
print("Bad format of input file")
exit(EX_IOERR)
}
self.flatStructure = dictionary
self.autocapitalize = autocapitalize
self.expandFlatStructure(flatStructure: dictionary, delimiter: delimiter)
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func writerWithSwiftImplementation() -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName(name: "Imports")
writer.writeSwiftImports()
// Generate actual localization structures
writer.writeMarkWithName(name: "Localizations")
writer.writeCodeStructure(structure: self.swiftStructWithContent(content: self.codifySwift(expandedStructure: self.objectStructure), structName: BASE_CLASS_NAME, contentLevel: 0))
return writer
}
func writerWithObjCImplementationWithFilename(filename: String) -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName(name: "Imports")
writer.writeObjCImportsWithFileName(name: filename)
// Generate actual localization structures
writer.writeMarkWithName(name: "Header")
writer.writeCodeStructure(structure: self.codifyObjC(expandedStructure: self.objectStructure, baseClass: BASE_CLASS_NAME, header: false))
return writer
}
func writerWithObjCHeader() -> StreamWriter {
let writer = StreamWriter()
// Generate header
writer.writeHeader()
// Imports
writer.writeMarkWithName(name: "Imports")
writer.writeObjCHeaderImports()
// Generate actual localization structures
writer.writeMarkWithName(name: "Header")
writer.writeCodeStructure(structure: self.codifyObjC(expandedStructure: self.objectStructure, baseClass: BASE_CLASS_NAME, header: true))
// Generate macros
writer.writeMarkWithName(name: "Macros")
writer.writeObjCHeaderMacros()
return writer
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func expandFlatStructure(flatStructure: NSDictionary, delimiter: String) {
// Writes values to dictionary and also
for (key, _) in flatStructure {
guard let key = key as? String else { continue }
objectStructure.setObject(object: key as NSString, forKeyPath: key, delimiter: delimiter)
}
}
private func codifySwift(expandedStructure: NSDictionary, contentLevel: Int = 0) -> String {
// Increase content level
let contentLevel = contentLevel + 1
// Prepare output structure
var outputStructure: [String] = []
// First iterate through properties
for (key, value) in expandedStructure {
if let value = value as? String {
let comment = (self.flatStructure.object(forKey: value) as! String).nolineString
let methodParams = self.methodParamsForString(string: comment)
let staticString: String
if methodParams.count > 0 {
staticString = self.swiftLocalizationFuncFromLocalizationKey(key: value, methodName: key as! String, baseTranslation: comment, methodSpecification: methodParams, contentLevel: contentLevel)
} else {
staticString = self.swiftLocalizationStaticVarFromLocalizationKey(key: value, variableName: key as! String, baseTranslation: comment, contentLevel: contentLevel)
}
outputStructure.append(staticString)
}
}
// Then iterate through nested structures
for (key, value) in expandedStructure {
if let value = value as? NSDictionary {
outputStructure.append(self.swiftStructWithContent(content: self.codifySwift(expandedStructure: value, contentLevel: contentLevel), structName: key as! String, contentLevel: contentLevel))
}
}
// At the end, return everything merged together
return outputStructure.joined(separator: "\n")
}
private func codifyObjC(expandedStructure: NSDictionary, baseClass: String, header: Bool) -> String {
// Prepare output structure
var outputStructure: [String] = []
var contentStructure: [String] = []
// First iterate through properties
for (key, value) in expandedStructure {
if let value = value as? String {
let comment = (self.flatStructure.object(forKey: value) as! String).nolineString
let methodParams = self.methodParamsForString(string: comment)
let staticString: String
if methodParams.count > 0 {
staticString = self.objcLocalizationFuncFromLocalizationKey(key: value, methodName: self.variableName(string: key as! String, lang: .ObjC), baseTranslation: comment, methodSpecification: methodParams, header: header)
} else {
staticString = self.objcLocalizationStaticVarFromLocalizationKey(key: value, variableName: self.variableName(string: key as! String, lang: .ObjC), baseTranslation: comment, header: header)
}
contentStructure.append(staticString)
}
}
// Then iterate through nested structures
for (key, value) in expandedStructure {
if let value = value as? NSDictionary {
outputStructure.append(self.codifyObjC(expandedStructure: value, baseClass : baseClass + self.variableName(string: key as! String, lang: .ObjC), header: header))
contentStructure.insert(self.objcClassVarWithName(name: self.variableName(string: key as! String, lang: .ObjC), className: baseClass + self.variableName(string: key as! String, lang: .ObjC), header: header), at: 0)
}
}
if baseClass == BASE_CLASS_NAME {
if header {
contentStructure.append(TemplateFactory.templateForObjCBaseClassHeader(name: OBJC_CLASS_PREFIX + BASE_CLASS_NAME))
} else {
contentStructure.append(TemplateFactory.templateForObjCBaseClassImplementation(name: OBJC_CLASS_PREFIX + BASE_CLASS_NAME))
}
}
// Generate class code for current class
outputStructure.append(self.objcClassWithContent(content: contentStructure.joined(separator: "\n"), className: OBJC_CLASS_PREFIX + baseClass, header: header))
// At the end, return everything merged together
return outputStructure.joined(separator: "\n")
}
private func methodParamsForString(string: String) -> [SpecialCharacter] {
// Split the string into pieces by %
let matches = self.matchesForRegexInText(regex: "%([0-9]*.[0-9]*(d|i|u|f|ld)|(\\d\\$)?@|d|i|u|f|ld)", text: string)
var characters: [SpecialCharacter] = []
for match in matches {
characters.append(self.propertyTypeForMatch(string: match))
}
return characters
}
private func propertyTypeForMatch(string: String) -> SpecialCharacter {
if string.contains("ld") {
return .Int64
} else if string.contains("d") || string.contains("i") {
return .Int
} else if string.contains("u") {
return .UInt
} else if string.contains("f") {
return .Double
} else {
return .String
}
}
private func variableName(string: String, lang: Runtime.ExportLanguage) -> String {
// . is not allowed, nested structure expanding must take place before calling this function
let legalCharacterString = string.replacedNonAlphaNumericCharacters(replacement: "_")
if self.autocapitalize {
return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang: lang) ? "_" + legalCharacterString.camelCasedString : legalCharacterString.camelCasedString)
} else {
return (legalCharacterString.isFirstLetterDigit() || legalCharacterString.isReservedKeyword(lang: lang) ? "_" + string : legalCharacterString)
}
}
private func matchesForRegexInText(regex: String!, text: String!) -> [String] {
do {
let regex = try NSRegularExpression(pattern: regex, options: [])
let nsString = text as NSString
let results = regex.matches(in: text, options: [], range: NSMakeRange(0, nsString.length))
return results.map { nsString.substring(with: $0.range)}
} catch let error as NSError {
print("invalid regex: \(error.localizedDescription)")
return []
}
}
private func dataTypeFromSpecialCharacter(char: SpecialCharacter, language: Runtime.ExportLanguage) -> String {
switch char {
case .String: return language == .Swift ? "String" : "NSString *"
case .Double: return language == .Swift ? "Double" : "double"
case .Int: return language == .Swift ? "Int" : "int"
case .Int64: return language == .Swift ? "Int64" : "long"
case .UInt: return language == .Swift ? "UInt" : "unsigned int"
}
}
private func swiftStructWithContent(content: String, structName: String, contentLevel: Int = 0) -> String {
return TemplateFactory.templateForSwiftStructWithName(name: self.variableName(string: structName, lang: .Swift), content: content, contentLevel: contentLevel)
}
private func swiftLocalizationStaticVarFromLocalizationKey(key: String, variableName: String, baseTranslation: String, contentLevel: Int = 0) -> String {
return TemplateFactory.templateForSwiftStaticVarWithName(name: self.variableName(string: variableName, lang: .Swift), key: key, table: table, baseTranslation : baseTranslation, contentLevel: contentLevel)
}
private func swiftLocalizationFuncFromLocalizationKey(key: String, methodName: String, baseTranslation: String, methodSpecification: [SpecialCharacter], contentLevel: Int = 0) -> String {
var counter = 0
var methodHeaderParams = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), _ value\(counter) : \(self.dataTypeFromSpecialCharacter(char: character, language: .Swift))"
}
var methodParams: [String] = []
for (index, _) in methodSpecification.enumerated() {
methodParams.append("value\(index + 1)")
}
let methodParamsString = methodParams.joined(separator: ", ")
methodHeaderParams = methodHeaderParams.trimmingCharacters(in: CharacterSet(charactersIn: ", "))
return TemplateFactory.templateForSwiftFuncWithName(name: self.variableName(string: methodName, lang: .Swift), key: key, table: table, baseTranslation : baseTranslation, methodHeader: methodHeaderParams, params: methodParamsString, contentLevel: contentLevel)
}
private func objcClassWithContent(content: String, className: String, header: Bool, contentLevel: Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCClassHeaderWithName(name: className, content: content, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCClassImplementationWithName(name: className, content: content, contentLevel: contentLevel)
}
}
private func objcClassVarWithName(name: String, className: String, header: Bool, contentLevel: Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCClassVarHeaderWithName(name: name, className: className, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCClassVarImplementationWithName(name: name, className: className, contentLevel: contentLevel)
}
}
private func objcLocalizationStaticVarFromLocalizationKey(key: String, variableName: String, baseTranslation: String, header: Bool, contentLevel: Int = 0) -> String {
if header {
return TemplateFactory.templateForObjCStaticVarHeaderWithName(name: variableName, key: key, baseTranslation : baseTranslation, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCStaticVarImplementationWithName(name: variableName, key: key, table: table, baseTranslation : baseTranslation, contentLevel: contentLevel)
}
}
private func objcLocalizationFuncFromLocalizationKey(key: String, methodName: String, baseTranslation: String, methodSpecification: [SpecialCharacter], header: Bool, contentLevel: Int = 0) -> String {
var counter = 0
var methodHeader = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), \(self.dataTypeFromSpecialCharacter(char: character, language: .ObjC))"
}
counter = 0
var blockHeader = methodSpecification.reduce("") { (string, character) -> String in
counter += 1
return "\(string), \(self.dataTypeFromSpecialCharacter(char: character, language: .ObjC)) value\(counter) "
}
var blockParamComponent: [String] = []
for (index, _) in methodSpecification.enumerated() {
blockParamComponent.append("value\(index + 1)")
}
let blockParams = blockParamComponent.joined(separator: ", ")
methodHeader = methodHeader.trimmingCharacters(in: CharacterSet(charactersIn: ", "))
blockHeader = blockHeader.trimmingCharacters(in: CharacterSet(charactersIn: ", "))
if header {
return TemplateFactory.templateForObjCMethodHeaderWithName(name: methodName, key: key, baseTranslation: baseTranslation, methodHeader: methodHeader, contentLevel: contentLevel)
} else {
return TemplateFactory.templateForObjCMethodImplementationWithName(name: methodName, key: key, table: table, baseTranslation: baseTranslation, methodHeader: methodHeader, blockHeader: blockHeader, blockParams: blockParams, contentLevel: contentLevel)
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Runtime Class implementation
class Runtime {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
enum ExportLanguage: String {
case Swift = "swift"
case ObjC = "objc"
}
enum ExportStream: String {
case Standard = "stdout"
case File = "file"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Properties
var localizationFilePathToRead: URL!
var localizationFilePathToWriteTo: URL!
var localizationFileHeaderPathToWriteTo: URL?
var localizationDelimiter = "."
var localizationDebug = false
var localizationCore: Localization!
var localizationExportLanguage: ExportLanguage = .Swift
var localizationExportStream: ExportStream = .File
var localizationAutocapitalize = false
var localizationStringsTable: String?
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func run() {
// Initialize command line tool
if self.checkCLI() {
// Process files
if self.checkIO() {
// Generate input -> output based on user configuration
self.processOutput()
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func checkCLI() -> Bool {
// Define CLI options
let inputFilePath = StringOption(shortFlag: "i", longFlag: "input", required: true,
helpMessage: "Required | String | Path to the localization file")
let outputFilePath = StringOption(shortFlag: "o", longFlag: "output", required: false,
helpMessage: "Optional | String | Path to output file (.swift or .m, depending on your configuration. If you are using ObjC, header will be created on that location. If ommited, output will be sent to stdout instead.")
let outputLanguage = StringOption(shortFlag: "l", longFlag: "language", required: false,
helpMessage: "Optional | String | [swift | objc] | Specifies language of generated output files | Defaults to [swift]")
let delimiter = StringOption(shortFlag: "d", longFlag: "delimiter", required: false,
helpMessage: "Optional | String | String delimiter to separate segments of each string | Defaults to [.]")
let autocapitalize = BoolOption(shortFlag: "c", longFlag: "capitalize", required: false,
helpMessage: "Optional | Bool | When enabled, name of all structures / methods / properties are automatically CamelCased | Defaults to false")
let baseClassName = StringOption(shortFlag: "b", longFlag: "baseClassName", required: false,
helpMessage: "Optional | String | Name of the base class | Defaults to \"Localizations\"")
let stringsTableName = StringOption(shortFlag: "t", longFlag: "stringsTableName", required: false,
helpMessage: "Optional | String | Name of strings table | Defaults to nil")
let customSuperclass = StringOption(shortFlag: "s", longFlag: "customSuperclass", required: false,
helpMessage: "Optional | String | A custom superclass name | Defaults to NSObject (only applicable in ObjC)")
let cli = CommandLine()
cli.addOptions(inputFilePath, outputFilePath, outputLanguage, delimiter, autocapitalize, baseClassName, stringsTableName, customSuperclass)
// TODO: make output file path NOT optional when print output stream is selected
do {
// Parse user input
try cli.parse(strict: true)
// It passed, now process input
self.localizationFilePathToRead = URL(fileURLWithPath: inputFilePath.value!)
if let value = delimiter.value { self.localizationDelimiter = value }
self.localizationAutocapitalize = autocapitalize.wasSet ? true : false
if let value = outputLanguage.value, let type = ExportLanguage(rawValue: value) { self.localizationExportLanguage = type }
if let value = outputFilePath.value {
self.localizationFilePathToWriteTo = URL(fileURLWithPath: value)
self.localizationExportStream = .File
} else {
self.localizationExportStream = .Standard
}
if let bcn = baseClassName.value {
BASE_CLASS_NAME = bcn
}
self.localizationStringsTable = stringsTableName.value
OBJC_CUSTOM_SUPERCLASS = customSuperclass.value
return true
} catch {
cli.printUsage(error)
exit(EX_USAGE)
}
return false
}
private func checkIO() -> Bool {
// Check if we have input file
if !FileManager.default.fileExists(atPath: self.localizationFilePathToRead.path) {
// TODO: Better error handling
exit(EX_IOERR)
}
// Handle output file checks only if we are writing to file
if self.localizationExportStream == .File {
// Remove output file first
_ = try? FileManager.default.removeItem(atPath: self.localizationFilePathToWriteTo.path)
if !FileManager.default.createFile(atPath: self.localizationFilePathToWriteTo.path, contents: Data(), attributes: nil) {
// TODO: Better error handling
exit(EX_IOERR)
}
// ObjC - we also need header file for ObjC code
if self.localizationExportLanguage == .ObjC {
// Create header file name
self.localizationFileHeaderPathToWriteTo = self.localizationFilePathToWriteTo.deletingPathExtension().appendingPathExtension("h")
// Remove file at path and replace it with new one
_ = try? FileManager.default.removeItem(atPath: self.localizationFileHeaderPathToWriteTo!.path)
if !FileManager.default.createFile(atPath: self.localizationFileHeaderPathToWriteTo!.path, contents: Data(), attributes: nil) {
// TODO: Better error handling
exit(EX_IOERR)
}
}
}
return true
}
private func processOutput() {
// Create translation core which will process all required data
self.localizationCore = Localization(inputFile: self.localizationFilePathToRead, delimiter: self.localizationDelimiter, autocapitalize: self.localizationAutocapitalize, table: self.localizationStringsTable)
// Write output for swift
if self.localizationExportLanguage == .Swift {
let implementation = self.localizationCore.writerWithSwiftImplementation()
// Write swift file
if self.localizationExportStream == .Standard {
implementation.writeToSTD(clearBuffer: true)
} else if self.localizationExportStream == .File {
implementation.writeToOutputFileAtPath(path: self.localizationFilePathToWriteTo)
}
// or write output for objc, based on user configuration
} else if self.localizationExportLanguage == .ObjC {
let implementation = self.localizationCore.writerWithObjCImplementationWithFilename(filename: self.localizationFilePathToWriteTo.deletingPathExtension().lastPathComponent)
let header = self.localizationCore.writerWithObjCHeader()
// Write .h and .m file
if self.localizationExportStream == .Standard {
header.writeToSTD(clearBuffer: true)
implementation.writeToSTD(clearBuffer: true)
} else if self.localizationExportStream == .File {
implementation.writeToOutputFileAtPath(path: self.localizationFilePathToWriteTo)
header.writeToOutputFileAtPath(path: self.localizationFileHeaderPathToWriteTo!)
}
}
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - LocalizationPrinter Class implementation
class StreamWriter {
var outputBuffer: String = ""
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public
func writeHeader() {
// let formatter = NSDateFormatter()
// formatter.dateFormat = "yyyy-MM-dd 'at' h:mm a"
self.store(string: "//\n")
self.store(string: "// Autogenerated by Laurine - by Jiri Trecak ( http://jiritrecak.com, @jiritrecak )\n")
self.store(string: "// Do not change this file manually!\n")
self.store(string: "//\n")
// self.store("// \(formatter.stringFromDate(NSDate()))\n")
// self.store("//\n")
}
func writeMarkWithName(name: String, contentLevel: Int = 0) {
self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n")
self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n")
self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---\n")
self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "// MARK: - \(name)\n")
self.store(string: TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "\n")
}
func writeSwiftImports() {
self.store(string: "import Foundation\n")
}
func writeObjCImportsWithFileName(name: String) {
self.store(string: "#import \"\(name).h\"\n")
}
func writeObjCHeaderImports() {
self.store(string: "@import Foundation;\n")
if let csc = OBJC_CUSTOM_SUPERCLASS {
self.store(string: "#import \"\(csc).h\"\n")
}
}
func writeObjCHeaderMacros() {
self.store(string: "// Make localization to be easily accessible\n")
self.store(string: "#define \(BASE_CLASS_NAME) [\(OBJC_CLASS_PREFIX)\(BASE_CLASS_NAME) sharedInstance]\n")
}
func writeCodeStructure(structure: String) {
self.store(string: structure)
}
func writeToOutputFileAtPath(path: URL, clearBuffer: Bool = true) {
_ = try? self.outputBuffer.write(toFile: path.path, atomically: true, encoding: String.Encoding.utf8)
if clearBuffer {
self.outputBuffer = ""
}
}
func writeToSTD(clearBuffer: Bool = true) {
print(self.outputBuffer)
if clearBuffer {
self.outputBuffer = ""
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Private
private func store(string: String) {
self.outputBuffer += string
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - TemplateFactory Class implementation
class TemplateFactory {
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - Swift Templates
class func templateForSwiftStructWithName(name: String, content: String, contentLevel: Int) -> String {
return "\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public struct \(name) {\n"
+ "\n"
+ "\(content)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "}"
}
class func templateForSwiftStaticVarWithName(name: String, key: String, table: String?, baseTranslation: String, contentLevel: Int) -> String {
let tableName: String
if let table = table {
tableName = "tableName: \"\(table)\", "
} else {
tableName = ""
}
return TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "/// Base translation: \(baseTranslation)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public static var \(name) : String = NSLocalizedString(\"\(key)\", \(tableName)comment: \"\")\n"
}
class func templateForSwiftFuncWithName(name: String, key: String, table: String?, baseTranslation: String, methodHeader: String, params: String, contentLevel: Int) -> String {
let tableName: String
if let table = table {
tableName = "tableName: \"\(table)\", "
} else {
tableName = ""
}
return TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "/// Base translation: \(baseTranslation)\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "public static func \(name)(\(methodHeader)) -> String {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel + 1) + "return String(format: NSLocalizedString(\"\(key)\", \(tableName)comment: \"\"), \(params))\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: contentLevel) + "}\n"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - ObjC templates
class func templateForObjCClassImplementationWithName(name: String, content: String, contentLevel: Int) -> String {
return "@implementation \(name)\n\n"
+ "\(content)\n"
+ "@end\n\n"
}
class func templateForObjCStaticVarImplementationWithName(name: String, key: String, table: String?, baseTranslation: String, contentLevel: Int) -> String {
let tableName = table != nil ? "@\"\(table!)\"" : "nil"
return "- (NSString *)\(name) {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return NSLocalizedStringFromTable(@\"\(key)\", \(tableName), nil);\n"
+ "}\n"
}
class func templateForObjCClassVarImplementationWithName(name: String, className: String, contentLevel: Int) -> String {
return "- (_\(className) *)\(name) {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return [\(OBJC_CLASS_PREFIX)\(className) new];\n"
+ "}\n"
}
class func templateForObjCMethodImplementationWithName(name: String, key: String, table: String?, baseTranslation: String, methodHeader: String, blockHeader: String, blockParams: String, contentLevel: Int) -> String {
let tableName = table != nil ? "@\"\(table!)\"" : "nil"
return "- (NSString *(^)(\(methodHeader)))\(name) {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return ^(\(blockHeader)) {\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 2) + "return [NSString stringWithFormat: NSLocalizedStringFromTable(@\"\(key)\", \(tableName), nil), \(blockParams)];\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "};\n"
+ "}\n"
}
class func templateForObjCClassHeaderWithName(name: String, content: String, contentLevel: Int) -> String {
return "@interface \(name) : \(OBJC_CUSTOM_SUPERCLASS ?? "NSObject")\n\n"
+ "\(content)\n"
+ "@end\n"
}
class func templateForObjCStaticVarHeaderWithName(name: String, key: String, baseTranslation: String, contentLevel: Int) -> String {
return "/// Base translation: \(baseTranslation)\n"
+ "- (NSString *)\(name);\n"
}
class func templateForObjCClassVarHeaderWithName(name: String, className: String, contentLevel: Int) -> String {
return "- (_\(className) *)\(name);\n"
}
class func templateForObjCMethodHeaderWithName(name: String, key: String, baseTranslation: String, methodHeader: String, contentLevel: Int) -> String {
return "/// Base translation: \(baseTranslation)\n"
+ "- (NSString *(^)(\(methodHeader)))\(name);"
}
class func templateForObjCBaseClassHeader(name: String) -> String {
return "+ (\(name) *)sharedInstance;\n"
}
class func templateForObjCBaseClassImplementation(name: String) -> String {
return "+ (\(name) *)sharedInstance {\n"
+ "\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "static dispatch_once_t once;\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "static \(name) *instance;\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "dispatch_once(&once, ^{\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 2) + "instance = [[\(name) alloc] init];\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "});\n"
+ TemplateFactory.contentIndentForLevel(contentLevel: 1) + "return instance;\n"
+ "}"
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Public - Helpers
class func contentIndentForLevel(contentLevel: Int) -> String {
var outputString = ""
for _ in 0 ..< contentLevel {
outputString += " "
}
return outputString
}
}
// --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- --- ---
// MARK: - Actual processing
let runtime = Runtime()
runtime.run()
| mit | 2541160d837fb79ecee659a107cd89cf | 36.272966 | 554 | 0.596873 | 4.791807 | false | false | false | false |
milseman/swift | test/SourceKit/CodeComplete/complete_import_module_flag.swift | 12 | 1185 | // XFAIL: broken_std_regex
// RUN: %empty-directory(%t)
// RUN: %swift -Xcc -I%S/Inputs -emit-module -o %t/auxiliary_file.swiftmodule %S/Inputs/auxiliary_file.swift
// RUN: %complete-test -group=none -hide-none -raw -tok=TOP_LEVEL_0 %s -- -import-module auxiliary_file -I %t -I %S/Inputs | %FileCheck %s
// RUN: %complete-test -group=none -tok=TOP_LEVEL_0 %s -- -import-module auxiliary_file -I %t -I %S/Inputs | %FileCheck %s -check-prefix=WITH_HIDING
func fromMainModule() {}
func test() {
#^TOP_LEVEL_0^#
}
// Score for fromAuxFile() ties fromMainModule(), so it goes first
// alphabetically.
// CHECK-LABEL: key.name: "fromAuxFile()
// CHECK-NOT: context
// CHECK: key.context: source.codecompletion.context.othermodule
// CHECK-NEXT: key.moduleimportdepth: 0
// CHECK-LABEL: key.name: "fromMainModule()
// CHECK-NOT: context
// CHECK: key.context: source.codecompletion.context.thismodule
// CHECK-LABEL: key.name: "fromImportedByAuxFile()
// CHECK-NOT: context
// CHECK: key.context: source.codecompletion.context.othermodule
// CHECK-NEXT: key.moduleimportdepth: 1
// WITH_HIDING: fromAuxFile()
// WITH_HIDING: fromMainModule()
// WITH_HIDING-NOT: fromImportedByAuxFile
| apache-2.0 | 281452e66174a7e767d96c1861977257 | 39.862069 | 149 | 0.718143 | 3.015267 | false | true | false | false |
ApplePride/PIDOR | Examples/Swift/PIDOR/Object.swift | 1 | 524 | //
// Pidor.swift
// PIDOR
//
// Created by Alexander on 3/1/17.
// Copyright ยฉ 2017 ApplePride. All rights reserved.
//
import Foundation
import UIKit
class Question {
init(text: String? = nil, imageNames: [String]) {
self.text = text
self.imageNames = imageNames
}
let text: String?
let imageNames: [String]
}
class Pidor {
init(questions: [Question]) {
self.questions = questions
}
let questions: [Question]
var answers = [Bool]()
}
| mit | 2e0506bafddc405628e6873dd2f9bc54 | 13.942857 | 53 | 0.586998 | 3.70922 | false | false | false | false |
kcome/SwiftIB | SwiftIB/EReader.swift | 1 | 48030 | //
// EReader.swift
// SwiftIB
//
// Created by Harry Li on 3/01/2015.
// Copyright (c) 2014-2019 Hanfei Li. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
// of the Software, and to permit persons to whom the Software is furnished to
// do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import Foundation
class EReader: Thread {
// incoming msg id's
enum MsgIdEnum: Int {
case tick_PRICE = 1
case tick_SIZE = 2
case order_STATUS = 3
case err_MSG = 4
case open_ORDER = 5
case acct_VALUE = 6
case portfolio_VALUE = 7
case acct_UPDATE_TIME = 8
case next_VALID_ID = 9
case contract_DATA = 10
case execution_DATA = 11
case market_DEPTH = 12
case market_DEPTH_L2 = 13
case news_BULLETINS = 14
case managed_ACCTS = 15
case receive_FA = 16
case historical_DATA = 17
case bond_CONTRACT_DATA = 18
case scanner_PARAMETERS = 19
case scanner_DATA = 20
case tick_OPTION_COMPUTATION = 21
case tick_GENERIC = 45
case tick_STRING = 46
case tick_EFP = 47
case current_TIME = 49
case real_TIME_BARS = 50
case fundamental_DATA = 51
case contract_DATA_END = 52
case open_ORDER_END = 53
case acct_DOWNLOAD_END = 54
case execution_DATA_END = 55
case delta_NEUTRAL_VALIDATION = 56
case tick_SNAPSHOT_END = 57
case market_DATA_TYPE = 58
case commission_REPORT = 59
case position = 61
case position_END = 62
case account_SUMMARY = 63
case account_SUMMARY_END = 64
case verify_MESSAGE_API = 65
case verify_COMPLETED = 66
case display_GROUP_LIST = 67
case display_GROUP_UPDATED = 68
}
var _parent: EClientSocket
var dis: InputStream
var parent: EClientSocket {
return _parent
}
var eWrapper: EWrapper {
return _parent.eWrapper()
}
convenience init(parent: EClientSocket, dis: InputStream) {
self.init(p_name:"", p_parent:parent, p_dis:dis)
}
init(p_name: String, p_parent: EClientSocket, p_dis: InputStream) {
_parent = p_parent
dis = p_dis
super.init()
self.name = p_name
}
override func main() {
// loop until thread is terminated
while (self.isExecuting && processMsg(readInt())) {
}
if (_parent.isConnected()) {
_parent.close()
}
dis.close()
}
func readStr() -> String {
var buf = ""
var bytes = Array<UInt8>(repeating: 0, count: 1)
while (true) {
let read = dis.read(&bytes, maxLength: 1)
if read == 0 || bytes[0] == 0 { break }
if let s = String(bytes: bytes, encoding: String.Encoding.utf8) {
buf += s
}
if dis.hasBytesAvailable == false { break }
}
return buf
}
func readBoolFromInt() -> Bool {
let str = readStr()
return str.utf16.count == 0 ? false : (Int(str) != 0)
}
func readInt() -> Int {
let str = readStr()
if str.utf16.count == 0 {return 0}
else if let i = Int(str) { return i }
else {return 0}
}
func readIntMax() -> Int {
let str = readStr()
if str.utf16.count == 0 {return Int.max}
else if let i = Int(str) { return i }
else {return Int.max}
}
func readLong() -> Int64 {
let str = readStr()
if str.utf16.count == 0 {return 0}
let ni = NSString(string: str)
return ni.longLongValue
}
func readDouble() -> Double {
let str = readStr()
if str.utf16.count == 0 {return 0}
let ni = NSString(string: str)
return ni.doubleValue
}
func readDoubleMax() -> Double {
let str = readStr()
if str.utf16.count == 0 {return Double.nan}
let ni = NSString(string: str)
return ni.doubleValue
}
func processMsg(_ msgId: Int) -> Bool {
if msgId == -1 {return false}
if let msg = MsgIdEnum(rawValue: msgId) {
switch (msg) {
case .tick_PRICE:
let version = readInt()
let tickerId = readInt()
let tickType = readInt()
let price = readDouble()
var size = 0
if (version >= 2) {
size = readInt()
}
var canAutoExecute = 0
if (version >= 3) {
canAutoExecute = readInt()
}
self.eWrapper.tickPrice(tickerId, field: tickType, price: price, canAutoExecute: canAutoExecute)
if (version >= 2) {
var sizeTickType = -1 // not a tick
switch (tickType) {
case 1: // BID
sizeTickType = 0 // BID_SIZE
case 2: // ASK
sizeTickType = 3 // ASK_SIZE
case 4: // LAST
sizeTickType = 5 // LAST_SIZE
default:
sizeTickType = -1 // not a tick
}
if (sizeTickType != -1) {
self.eWrapper.tickSize(tickerId, field: sizeTickType, size: size)
}
}
case .tick_SIZE:
_ = readInt()
let tickerId = readInt()
let tickType = readInt()
let size = readInt()
self.eWrapper.tickSize(tickerId, field: tickType, size: size)
case .position:
let version = readInt()
let account = readStr()
let contract = Contract()
contract.conId = readInt()
contract.symbol = readStr()
contract.secType = readStr()
contract.expiry = readStr()
contract.strike = readDouble()
contract.right = readStr()
contract.multiplier = readStr()
contract.exchange = readStr()
contract.currency = readStr()
contract.localSymbol = readStr()
if (version >= 2) {
contract.tradingClass = readStr()
}
let pos = readInt()
var avgCost = 0.0
if (version >= 3) {
avgCost = readDouble()
}
self.eWrapper.position(account, contract: contract, pos: pos, avgCost: avgCost)
case .position_END:
_ = readInt()
self.eWrapper.positionEnd()
case .account_SUMMARY:
_ = readInt()
let reqId = readInt()
let account = readStr()
let tag = readStr()
let value = readStr()
let currency = readStr()
self.eWrapper.accountSummary(reqId, account: account, tag: tag, value: value, currency: currency)
case .account_SUMMARY_END:
_ = readInt()
let reqId = readInt()
self.eWrapper.accountSummaryEnd(reqId)
case .tick_OPTION_COMPUTATION:
let version = readInt()
let tickerId = readInt()
let tickType = readInt()
var impliedVol = readDouble()
if (impliedVol < 0) { // -1 is the "not yet computed" indicator
impliedVol = Double.nan
}
var delta = readDouble()
if (abs(delta) > 1) { // -2 is the "not yet computed" indicator
delta = Double.nan
}
var optPrice = Double.nan
var pvDividend = Double.nan
var gamma = Double.nan
var vega = Double.nan
var theta = Double.nan
var undPrice = Double.nan
if (version >= 6 || TickType.TickTypeEnum(rawValue: tickType)! == .model_OPTION) { // introduced in version == 5
optPrice = readDouble()
if (optPrice < 0) { // -1 is the "not yet computed" indicator
optPrice = Double.nan
}
pvDividend = readDouble()
if (pvDividend < 0) { // -1 is the "not yet computed" indicator
pvDividend = Double.nan
}
}
if (version >= 6) {
gamma = readDouble()
if (abs(gamma) > 1) { // -2 is the "not yet computed" indicator
gamma = Double.nan
}
vega = readDouble()
if (abs(vega) > 1) { // -2 is the "not yet computed" indicator
vega = Double.nan
}
theta = readDouble()
if (abs(theta) > 1) { // -2 is the "not yet computed" indicator
theta = Double.nan
}
undPrice = readDouble()
if (undPrice < 0) { // -1 is the "not yet computed" indicator
undPrice = Double.nan
}
}
self.eWrapper.tickOptionComputation(tickerId, field: tickType, impliedVol: impliedVol, delta: delta, optPrice: optPrice, pvDividend:pvDividend, gamma: gamma, vega: vega, theta: theta, undPrice: undPrice)
case .tick_GENERIC:
_ = readInt()
let tickerId = readInt()
let tickType = readInt()
let value = readDouble()
self.eWrapper.tickGeneric(tickerId, tickType: tickType, value: value)
case .tick_STRING:
_ = readInt()
let tickerId = readInt()
let tickType = readInt()
let value = readStr()
self.eWrapper.tickString(tickerId, tickType: tickType, value: value)
case .tick_EFP:
let _ = readInt()
let tickerId = readInt()
let tickType = readInt()
let basisPoints = readDouble()
let formattedBasisPoints = readStr()
let impliedFuturesPrice = readDouble()
let holdDays = readInt()
let futureExpiry = readStr()
let dividendImpact = readDouble()
let dividendsToExpiry = readDouble()
self.eWrapper.tickEFP(tickerId, tickType: tickType, basisPoints: basisPoints, formattedBasisPoints: formattedBasisPoints,
impliedFuture: impliedFuturesPrice, holdDays: holdDays, futureExpiry: futureExpiry, dividendImpact: dividendImpact, dividendsToExpiry: dividendsToExpiry)
case .order_STATUS:
let version = readInt()
let id = readInt()
let status = readStr()
let filled = readInt()
let remaining = readInt()
let avgFillPrice = readDouble()
var permId = 0
if( version >= 2) {
permId = readInt()
}
var parentId = 0
if( version >= 3) {
parentId = readInt()
}
var lastFillPrice = 0.0
if( version >= 4) {
lastFillPrice = readDouble()
}
var clientId = 0
if( version >= 5) {
clientId = readInt()
}
var whyHeld = ""
if( version >= 6) {
whyHeld = readStr()
}
self.eWrapper.orderStatus(id, status: status, filled: filled, remaining: remaining, avgFillPrice: avgFillPrice,
permId: permId, parentId: parentId, lastFillPrice: lastFillPrice, clientId: clientId, whyHeld: whyHeld)
case .acct_VALUE:
let version = readInt()
let key = readStr()
let val = readStr()
let cur = readStr()
var accountName = ""
if( version >= 2) {
accountName = readStr()
}
self.eWrapper.updateAccountValue(key, value: val, currency: cur, accountName: accountName)
case .portfolio_VALUE:
let version = readInt()
let contract = Contract()
if (version >= 6) {
contract.conId = readInt()
}
contract.symbol = readStr()
contract.secType = readStr()
contract.expiry = readStr()
contract.strike = readDouble()
contract.right = readStr()
if (version >= 7) {
contract.multiplier = readStr()
contract.primaryExch = readStr()
}
contract.currency = readStr()
if (version >= 2 ) {
contract.localSymbol = readStr()
}
if (version >= 8) {
contract.tradingClass = readStr()
}
let position = readInt()
let marketPrice = readDouble()
let marketValue = readDouble()
var averageCost = 0.0
var unrealizedPNL = 0.0
var realizedPNL = 0.0
if version >= 3 {
averageCost = readDouble()
unrealizedPNL = readDouble()
realizedPNL = readDouble()
}
var accountName = ""
if( version >= 4) {
accountName = readStr()
}
if(version == 6 && _parent.serverVersion() == 39) {
contract.primaryExch = readStr()
}
self.eWrapper.updatePortfolio(contract, position: position, marketPrice: marketPrice, marketValue: marketValue,
averageCost: averageCost, unrealizedPNL: unrealizedPNL, realizedPNL: realizedPNL, accountName: accountName)
case .acct_UPDATE_TIME:
_ = readInt()
let timeStamp = readStr()
self.eWrapper.updateAccountTime(timeStamp)
case .err_MSG:
let version = readInt()
if(version < 2) {
let msg = readStr()
_parent.error(-1, errorCode: -1, errorMsg: msg)
} else {
let id = readInt()
let errorCode = readInt()
let errorMsg = readStr()
_parent.error(id, errorCode: errorCode, errorMsg: errorMsg)
}
case .open_ORDER:
// read version
let version = readInt()
// read order id
let order = Order()
order.orderId = readInt()
// read contract fields
let contract = Contract()
if (version >= 17) {
contract.conId = readInt()
}
contract.symbol = readStr()
contract.secType = readStr()
contract.expiry = readStr()
contract.strike = readDouble()
contract.right = readStr()
if (version >= 32) {
contract.multiplier = readStr()
}
contract.exchange = readStr()
contract.currency = readStr()
if (version >= 2 ) {
contract.localSymbol = readStr()
}
if (version >= 32) {
contract.tradingClass = readStr()
}
// read order fields
order.action = readStr()
order.totalQuantity = readInt()
order.orderType = readStr()
if (version < 29) {
order.lmtPrice = readDouble()
}
else {
order.lmtPrice = readDoubleMax()
}
if (version < 30) {
order.auxPrice = readDouble()
}
else {
order.auxPrice = readDoubleMax()
}
order.tif = readStr()
order.ocaGroup = readStr()
order.account = readStr()
order.openClose = readStr()
order.origin = readInt()
order.orderRef = readStr()
if(version >= 3) {
order.clientId = readInt()
}
if( version >= 4 ) {
order.permId = readInt()
if (version < 18) {
// will never happen
let _ = readBoolFromInt()
}
else {
order.outsideRth = readBoolFromInt()
}
order.hidden = readInt() == 1
order.discretionaryAmt = readDouble()
}
if (version >= 5 ) {
order.goodAfterTime = readStr()
}
if (version >= 6 ) {
// skip deprecated sharesAllocation field
let _ = readStr()
}
if (version >= 7 ) {
order.faGroup = readStr()
order.faMethod = readStr()
order.faPercentage = readStr()
order.faProfile = readStr()
}
if (version >= 8 ) {
order.goodTillDate = readStr()
}
if (version >= 9) {
order.rule80A = readStr()
order.percentOffset = readDoubleMax()
order.settlingFirm = readStr()
order.shortSaleSlot = readInt()
order.designatedLocation = readStr()
if (_parent.serverVersion() == 51) {
let _ = readInt() // exemptCode
}
else if (version >= 23) {
order.exemptCode = readInt()
}
order.auctionStrategy = readInt()
order.startingPrice = readDoubleMax()
order.stockRefPrice = readDoubleMax()
order.delta = readDoubleMax()
order.stockRangeLower = readDoubleMax()
order.stockRangeUpper = readDoubleMax()
order.displaySize = readInt()
if (version < 18) {
// will never happen
let _ = readBoolFromInt()
}
order.blockOrder = readBoolFromInt()
order.sweepToFill = readBoolFromInt()
order.allOrNone = readBoolFromInt()
order.minQty = readIntMax()
order.ocaType = readInt()
order.eTradeOnly = readBoolFromInt()
order.firmQuoteOnly = readBoolFromInt()
order.nbboPriceCap = readDoubleMax()
}
if (version >= 10) {
order.parentId = readInt()
order.triggerMethod = readInt()
}
if (version >= 11) {
order.volatility = readDoubleMax()
order.volatilityType = readInt()
if (version == 11) {
let receivedInt = readInt()
order.deltaNeutralOrderType = ((receivedInt == 0) ? "NONE" : "MKT" )
} else { // version 12 and up
order.deltaNeutralOrderType = readStr()
order.deltaNeutralAuxPrice = readDoubleMax()
if (version >= 27 && !order.deltaNeutralOrderType.isEmpty) {
order.deltaNeutralConId = readInt()
order.deltaNeutralSettlingFirm = readStr()
order.deltaNeutralClearingAccount = readStr()
order.deltaNeutralClearingIntent = readStr()
}
if (version >= 31 && !order.deltaNeutralOrderType.isEmpty) {
order.deltaNeutralOpenClose = readStr()
order.deltaNeutralShortSale = readBoolFromInt()
order.deltaNeutralShortSaleSlot = readInt()
order.deltaNeutralDesignatedLocation = readStr()
}
}
order.continuousUpdate = readInt()
if (_parent.serverVersion() == 26) {
order.stockRangeLower = readDouble()
order.stockRangeUpper = readDouble()
}
order.referencePriceType = readInt()
}
if (version >= 13) {
order.trailStopPrice = readDoubleMax()
}
if (version >= 30) {
order.trailingPercent = readDoubleMax()
}
if (version >= 14) {
order.basisPoints = readDoubleMax()
order.basisPointsType = readIntMax()
contract.comboLegsDescrip = readStr()
}
if (version >= 29) {
let comboLegsCount = readInt()
if (comboLegsCount > 0) {
contract.comboLegs = [ComboLeg]()
for _ in 1...comboLegsCount {
let conId = readInt()
let ratio = readInt()
let action = readStr()
let exchange = readStr()
let openClose = readInt()
let shortSaleSlot = readInt()
let designatedLocation = readStr()
let exemptCode = readInt()
let comboLeg = ComboLeg(p_conId: conId, p_ratio: ratio, p_action: action, p_exchange: exchange, p_openClose: openClose, p_shortSaleSlot: shortSaleSlot, p_designatedLocation: designatedLocation, p_exemptCode: exemptCode)
contract.comboLegs.append(comboLeg)
}
}
let orderComboLegsCount = readInt()
if (orderComboLegsCount > 0) {
order.orderComboLegs = [OrderComboLeg]()
for _ in 1...orderComboLegsCount {
let price = readDoubleMax()
let orderComboLeg = OrderComboLeg(p_price: price)
order.orderComboLegs.append(orderComboLeg)
}
}
}
if (version >= 26) {
let smartComboRoutingParamsCount = readInt()
if (smartComboRoutingParamsCount > 0) {
order.smartComboRoutingParams = [TagValue]()
for _ in 1...smartComboRoutingParamsCount {
let tagValue = TagValue()
tagValue.tag = readStr()
tagValue.value = readStr()
order.smartComboRoutingParams.append(tagValue)
}
}
}
if (version >= 15) {
if (version >= 20) {
order.scaleInitLevelSize = readIntMax()
order.scaleSubsLevelSize = readIntMax()
}
else {
_ = readIntMax()
order.scaleInitLevelSize = readIntMax()
}
order.scalePriceIncrement = readDoubleMax()
}
if (version >= 28 && order.scalePriceIncrement > 0.0 && order.scalePriceIncrement != Double.nan) {
order.scalePriceAdjustValue = readDoubleMax()
order.scalePriceAdjustInterval = readIntMax()
order.scaleProfitOffset = readDoubleMax()
order.scaleAutoReset = readBoolFromInt()
order.scaleInitPosition = readIntMax()
order.scaleInitFillQty = readIntMax()
order.scaleRandomPercent = readBoolFromInt()
}
if (version >= 24) {
order.hedgeType = readStr()
if (!order.hedgeType.isEmpty) {
order.hedgeParam = readStr()
}
}
if (version >= 25) {
order.optOutSmartRouting = readBoolFromInt()
}
if (version >= 19) {
order.clearingAccount = readStr()
order.clearingIntent = readStr()
}
if (version >= 22) {
order.notHeld = readBoolFromInt()
}
if (version >= 20) {
if (readBoolFromInt()) {
let underComp = UnderComp()
underComp.conId = readInt()
underComp.delta = readDouble()
underComp.price = readDouble()
contract.underComp = underComp
}
}
if (version >= 21) {
order.algoStrategy = readStr()
if (!order.algoStrategy.isEmpty) {
let algoParamsCount = readInt()
if (algoParamsCount > 0) {
order.algoParams = [TagValue]()
for _ in 1...algoParamsCount {
let tagValue = TagValue()
tagValue.tag = readStr()
tagValue.value = readStr()
order.algoParams.append(tagValue)
}
}
}
}
let orderState = OrderState(p_status: "", p_initMargin: "", p_maintMargin: "", p_equityWithLoan: "", p_commission: 0, p_minCommission: 0, p_maxCommission: 0, p_commissionCurrency: "", p_warningText: "")
if (version >= 16) {
order.whatIf = readBoolFromInt()
orderState.status = readStr()
orderState.initMargin = readStr()
orderState.maintMargin = readStr()
orderState.equityWithLoan = readStr()
orderState.commission = readDoubleMax()
orderState.minCommission = readDoubleMax()
orderState.maxCommission = readDoubleMax()
orderState.commissionCurrency = readStr()
orderState.warningText = readStr()
}
self.eWrapper.openOrder( order.orderId, contract: contract, order: order, orderState: orderState)
case .next_VALID_ID:
_ = readInt()
let orderId = readInt()
self.eWrapper.nextValidId( orderId)
case .scanner_DATA:
let contract = ContractDetails(p_summary: Contract(), p_marketName: "", p_minTick: 0, p_orderTypes: "", p_validExchanges: "", p_underConId: 0, p_longName: "", p_contractMonth: "", p_industry: "", p_category: "", p_subcategory: "", p_timeZoneId: "", p_tradingHours: "", p_liquidHours: "", p_evRule: "", p_evMultiplier: 0)
let version = readInt()
let tickerId = readInt()
let numberOfElements = readInt()
for _ in 1...numberOfElements {
let rank = readInt()
if (version >= 3) {
contract.summary.conId = readInt()
}
contract.summary.symbol = readStr()
contract.summary.secType = readStr()
contract.summary.expiry = readStr()
contract.summary.strike = readDouble()
contract.summary.right = readStr()
contract.summary.exchange = readStr()
contract.summary.currency = readStr()
contract.summary.localSymbol = readStr()
contract.marketName = readStr()
contract.summary.tradingClass = readStr()
let distance = readStr()
let benchmark = readStr()
let projection = readStr()
var legsStr = ""
if (version >= 2) {
legsStr = readStr()
}
self.eWrapper.scannerData(tickerId, rank: rank, contractDetails: contract, distance: distance,
benchmark: benchmark, projection: projection, legsStr: legsStr)
}
self.eWrapper.scannerDataEnd(tickerId)
case .contract_DATA:
let version = readInt()
var reqId = -1
if (version >= 3) {
reqId = readInt()
}
let contract = ContractDetails(p_summary: Contract(), p_marketName: "", p_minTick: 0, p_orderTypes: "", p_validExchanges: "", p_underConId: 0, p_longName: "", p_contractMonth: "", p_industry: "", p_category: "", p_subcategory: "", p_timeZoneId: "", p_tradingHours: "", p_liquidHours: "", p_evRule: "", p_evMultiplier: 0)
contract.summary.symbol = readStr()
contract.summary.secType = readStr()
contract.summary.expiry = readStr()
contract.summary.strike = readDouble()
contract.summary.right = readStr()
contract.summary.exchange = readStr()
contract.summary.currency = readStr()
contract.summary.localSymbol = readStr()
contract.marketName = readStr()
contract.summary.tradingClass = readStr()
contract.summary.conId = readInt()
contract.minTick = readDouble()
contract.summary.multiplier = readStr()
contract.orderTypes = readStr()
contract.validExchanges = readStr()
if (version >= 2) {
contract.priceMagnifier = readInt()
}
if (version >= 4) {
contract.underConId = readInt()
}
if( version >= 5) {
contract.longName = readStr()
contract.summary.primaryExch = readStr()
}
if( version >= 6) {
contract.contractMonth = readStr()
contract.industry = readStr()
contract.category = readStr()
contract.subcategory = readStr()
contract.timeZoneId = readStr()
contract.tradingHours = readStr()
contract.liquidHours = readStr()
}
if (version >= 8) {
contract.evRule = readStr()
contract.evMultiplier = readDouble()
}
if (version >= 7) {
let secIdListCount = readInt()
if (secIdListCount > 0) {
contract.secIdList = [TagValue]()
for _ in 1...secIdListCount {
let tagValue = TagValue()
tagValue.tag = readStr()
tagValue.value = readStr()
contract.secIdList?.append(tagValue)
}
}
}
self.eWrapper.contractDetails(reqId, contractDetails: contract)
case .bond_CONTRACT_DATA:
let version = readInt()
var reqId = -1
if (version >= 3) {
reqId = readInt()
}
let contract = ContractDetails(p_summary: Contract(), p_marketName: "", p_minTick: 0, p_orderTypes: "", p_validExchanges: "", p_underConId: 0, p_longName: "", p_contractMonth: "", p_industry: "", p_category: "", p_subcategory: "", p_timeZoneId: "", p_tradingHours: "", p_liquidHours: "", p_evRule: "", p_evMultiplier: 0)
contract.summary.symbol = readStr()
contract.summary.secType = readStr()
contract.cusip = readStr()
contract.coupon = readDouble()
contract.maturity = readStr()
contract.issueDate = readStr()
contract.ratings = readStr()
contract.bondType = readStr()
contract.couponType = readStr()
contract.convertible = readBoolFromInt()
contract.callable = readBoolFromInt()
contract.putable = readBoolFromInt()
contract.descAppend = readStr()
contract.summary.exchange = readStr()
contract.summary.currency = readStr()
contract.marketName = readStr()
contract.summary.tradingClass = readStr()
contract.summary.conId = readInt()
contract.minTick = readDouble()
contract.orderTypes = readStr()
contract.validExchanges = readStr()
if (version >= 2) {
contract.nextOptionDate = readStr()
contract.nextOptionType = readStr()
contract.nextOptionPartial = readBoolFromInt()
contract.notes = readStr()
}
if( version >= 4) {
contract.longName = readStr()
}
if (version >= 6) {
contract.evRule = readStr()
contract.evMultiplier = readDouble()
}
if (version >= 5) {
let secIdListCount = readInt()
if (secIdListCount > 0) {
contract.secIdList = [TagValue]()
for _ in 1...secIdListCount {
let tagValue = TagValue()
tagValue.tag = readStr()
tagValue.value = readStr()
contract.secIdList?.append(tagValue)
}
}
}
self.eWrapper.bondContractDetails(reqId, contractDetails: contract)
case .execution_DATA:
let version = readInt()
var reqId = -1
if (version >= 7) {
reqId = readInt()
}
let orderId = readInt()
// read contract fields
let contract = Contract()
if (version >= 5) {
contract.conId = readInt()
}
contract.symbol = readStr()
contract.secType = readStr()
contract.expiry = readStr()
contract.strike = readDouble()
contract.right = readStr()
if (version >= 9) {
contract.multiplier = readStr()
}
contract.exchange = readStr()
contract.currency = readStr()
contract.localSymbol = readStr()
if (version >= 10) {
contract.tradingClass = readStr()
}
let exec = Execution(p_orderId: 0, p_clientId: 0, p_execId: "", p_time: "", p_acctNumber: "", p_exchange: "", p_side: "", p_shares: 0, p_price: 0, p_permId: 0, p_liquidation: 0, p_cumQty: 0, p_avgPrice: 0, p_orderRef: "", p_evRule: "", p_evMultiplier: 0)
exec.orderId = orderId
exec.execId = readStr()
exec.time = readStr()
exec.acctNumber = readStr()
exec.exchange = readStr()
exec.side = readStr()
exec.shares = readInt()
exec.price = readDouble()
if (version >= 2 ) {
exec.permId = readInt()
}
if (version >= 3) {
exec.clientId = readInt()
}
if (version >= 4) {
exec.liquidation = readInt()
}
if (version >= 6) {
exec.cumQty = readInt()
exec.avgPrice = readDouble()
}
if (version >= 8) {
exec.orderRef = readStr()
}
if (version >= 9) {
exec.evRule = readStr()
exec.evMultiplier = readDouble()
}
self.eWrapper.execDetails( reqId, contract: contract, execution: exec)
case .market_DEPTH:
_ = readInt()
let id = readInt()
let position = readInt()
let operation = readInt()
let side = readInt()
let price = readDouble()
let size = readInt()
self.eWrapper.updateMktDepth(id, position: position, operation: operation, side: side, price: price, size: size)
case .market_DEPTH_L2:
_ = readInt()
let id = readInt()
let position = readInt()
let marketMaker = readStr()
let operation = readInt()
let side = readInt()
let price = readDouble()
let size = readInt()
self.eWrapper.updateMktDepthL2(id, position: position, marketMaker: marketMaker, operation: operation, side: side, price: price, size: size)
case .news_BULLETINS:
_ = readInt()
let newsMsgId = readInt()
let newsMsgType = readInt()
let newsMessage = readStr()
let originatingExch = readStr()
self.eWrapper.updateNewsBulletin( newsMsgId, msgType: newsMsgType, message: newsMessage, origExchange: originatingExch)
case .managed_ACCTS:
_ = readInt()
let accountsList = readStr()
self.eWrapper.managedAccounts( accountsList)
case .receive_FA:
_ = readInt()
let faDataType = readInt()
let xml = readStr()
self.eWrapper.receiveFA(faDataType, xml: xml)
case .historical_DATA:
let version = readInt()
let reqId = readInt()
var startDateStr = ""
var endDateStr = ""
var completedIndicator = "finished"
if (version >= 2) {
startDateStr = readStr()
endDateStr = readStr()
completedIndicator += "-\(startDateStr)-\(endDateStr)"
}
let itemCount = readInt()
for _ in 1...itemCount {
let date = readStr()
let open = readDouble()
let high = readDouble()
let low = readDouble()
let close = readDouble()
let volume = readInt()
let WAP = readDouble()
let hasGaps = caseInsensitiveEqual(readStr(), "true")
var barCount = -1
if (version >= 3) {
barCount = readInt()
}
self.eWrapper.historicalData(reqId, date: date, open: open, high: high, low: low,
close: close, volume: volume, count: barCount, WAP: WAP, hasGaps: hasGaps)
}
// send end of dataset marker
self.eWrapper.historicalData(reqId, date: completedIndicator, open: -1, high: -1, low: -1, close: -1, volume: -1, count: -1, WAP: -1, hasGaps: false)
case .scanner_PARAMETERS:
let _ = readInt()
let xml = readStr()
self.eWrapper.scannerParameters(xml)
case .current_TIME:
let _ = readInt()
let time = readLong()
self.eWrapper.currentTime(time)
case .real_TIME_BARS:
let _ = readInt()
let reqId = readInt()
let time = readLong()
let open = readDouble()
let high = readDouble()
let low = readDouble()
let close = readDouble()
let volume = readLong()
let wap = readDouble()
let count = readInt()
self.eWrapper.realtimeBar(reqId, time: time, open: open, high: high, low: low, close: close, volume: volume, wap: wap, count: count)
case .fundamental_DATA:
let _ = readInt()
let reqId = readInt()
let data = readStr()
self.eWrapper.fundamentalData(reqId, data: data)
case .contract_DATA_END:
let _ = readInt()
let reqId = readInt()
self.eWrapper.contractDetailsEnd(reqId)
case .open_ORDER_END:
let _ = readInt()
self.eWrapper.openOrderEnd()
case .acct_DOWNLOAD_END:
let _ = readInt()
let accountName = readStr()
self.eWrapper.accountDownloadEnd( accountName)
case .execution_DATA_END:
let _ = readInt()
let reqId = readInt()
self.eWrapper.execDetailsEnd( reqId)
case .delta_NEUTRAL_VALIDATION:
let _ = readInt()
let reqId = readInt()
let underComp = UnderComp()
underComp.conId = readInt()
underComp.delta = readDouble()
underComp.price = readDouble()
self.eWrapper.deltaNeutralValidation(reqId, underComp: underComp)
case .tick_SNAPSHOT_END:
let _ = readInt()
let reqId = readInt()
self.eWrapper.tickSnapshotEnd( reqId)
case .market_DATA_TYPE:
let _ = readInt()
let reqId = readInt()
let marketDataType = readInt()
self.eWrapper.marketDataType( reqId, marketDataType: marketDataType)
case .commission_REPORT:
let _ = readInt()
let commissionReport = CommissionReport()
commissionReport.execId = readStr()
commissionReport.commission = readDouble()
commissionReport.currency = readStr()
commissionReport.realizedPNL = readDouble()
commissionReport.yield = readDouble()
commissionReport.yieldRedemptionDate = readInt()
self.eWrapper.commissionReport(commissionReport)
case .verify_MESSAGE_API:
let _ = readInt()
let apiData = readStr()
self.eWrapper.verifyMessageAPI(apiData)
case .verify_COMPLETED:
let _ = readInt()
let isSuccessfulStr = readStr()
let isSuccessful = "true" == isSuccessfulStr
let errorText = readStr()
if (isSuccessful) {
_parent.startAPI()
}
self.eWrapper.verifyCompleted(isSuccessful, errorText: errorText)
case .display_GROUP_LIST:
let _ = readInt()
let reqId = readInt()
let groups = readStr()
self.eWrapper.displayGroupList(reqId, groups: groups)
case .display_GROUP_UPDATED:
let _ = readInt()
let reqId = readInt()
let contractInfo = readStr()
self.eWrapper.displayGroupUpdated(reqId, contractInfo: contractInfo)
}
} else { return false}
return true
}
}
| mit | c32d508fca103ffdac4147fe8fa1d580 | 40.910995 | 336 | 0.44595 | 5.300154 | false | false | false | false |
darrarski/SharedShopping-iOS | SharedShoppingApp/UI/Helpers/UIViewController_Embedding.swift | 1 | 955 | import UIKit
extension UIViewController {
func embed(_ viewController: UIViewController, in view: UIView) {
addChildViewController(viewController)
view.addSubview(viewController.view)
viewController.view.translatesAutoresizingMaskIntoConstraints = false
viewController.view.topAnchor.constraint(equalTo: view.topAnchor).isActive = true
viewController.view.leftAnchor.constraint(equalTo: view.leftAnchor).isActive = true
viewController.view.rightAnchor.constraint(equalTo: view.rightAnchor).isActive = true
viewController.view.bottomAnchor.constraint(equalTo: view.bottomAnchor).isActive = true
viewController.didMove(toParentViewController: self)
}
func unembed(_ viewController: UIViewController) {
viewController.willMove(toParentViewController: nil)
viewController.view.removeFromSuperview()
viewController.removeFromParentViewController()
}
}
| mit | 2d6b0bb9cac87bea4d508ae235260ea9 | 42.409091 | 95 | 0.757068 | 5.858896 | false | false | false | false |
Davidde94/StemCode_iOS | StemCode/StemCode/Code/Providers/ProjectProvider.swift | 1 | 1774 | //
// ProjectProvider.swift
// StemCode
//
// Created by David Evans on 31/08/2018.
// Copyright ยฉ 2018 BlackPoint LTD. All rights reserved.
//
import Foundation
import StemProjectKit
class ProjectProvider {
static let shared = ProjectProvider()
private init() { }
func loadAll(in directory: String = FileManager.default.sharedDocumentsDirectory) -> [Stem] {
guard let contents = try? FileManager.default.contentsOfDirectory(atPath: directory) else {
NSLog("Unable to get directory contents")
return []
}
let projects: [Stem] = contents.compactMap { item in
let dirPath = "\(directory)/\(item)"
var isFolder: ObjCBool = false
FileManager.default.fileExists(atPath: dirPath, isDirectory: &isFolder)
if isFolder.boolValue {
for subItem in try! FileManager.default.contentsOfDirectory(atPath: dirPath) {
let subItemPath = "\(dirPath)/\(subItem)"
var isFolder: ObjCBool = false
FileManager.default.fileExists(atPath: subItemPath, isDirectory: &isFolder)
let predicate = try! NSRegularExpression(pattern: "(.*)\\.stem", options: .init(rawValue: 0))
let validName = predicate.matches(in: subItem, options: .init(rawValue: 0), range: NSRange(location: 0, length: subItem.count))
if !isFolder.boolValue && validName.count == 1 {
do {
let data = try Data(contentsOf: URL(fileURLWithPath: subItemPath))
let stem = try JSONDecoder().decode(Stem.self, from: data)
stem.projectFolder = dirPath
stem.projectFileName = subItem
return stem
} catch {
NSLog("Error loading project: %s", error.localizedDescription)
return nil
}
}
}
}
return nil
}
return projects.sorted { $0.name.compare($1.name) == .orderedAscending }
}
}
| mit | bb2eeb7ec9a0e4ab8d6ea10788ae85ac | 27.596774 | 132 | 0.682459 | 3.845987 | false | false | false | false |
dexjkim/SwiftSampleContacts | SwiftSampleContacts/RandomUser/User.swift | 1 | 4695 | //
// User.swift
// SwiftSampleContacts
//
// Created by Dexter Kim on 2014-12-22.
// Copyright (c) 2014 DexMobile. All rights reserved.
//
import Foundation
import Alamofire
// To get the respons data as a collection type
@objc public protocol ResponseCollectionSerializable {
class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [Self]
}
// Generic Response Collection Serialization
extension Alamofire.Request {
public func responseCollection<T: ResponseCollectionSerializable>(completionHandler: (NSURLRequest, NSHTTPURLResponse?, [T]?, NSError?) -> Void) -> Self {
let serializer: Serializer = { (request, response, data) in
let JSONSerializer = Request.JSONResponseSerializer(options: .AllowFragments)
let (JSON: AnyObject?, serializationError) = JSONSerializer(request, response, data)
if response != nil && JSON != nil {
return (T.collection(response: response!, representation: JSON!), nil)
} else {
return (nil, serializationError)
}
}
return response(serializer: serializer, completionHandler: { (request, response, object, error) in
completionHandler(request, response, object as? [T], error)
})
}
}
// User Object, which is from Random User as Json type
final class User: ResponseCollectionSerializable {
let name: UserName
let SSN: String
let phone: String
let cell: String
let dob: String
let email: String
let gender: String
let location: UserLocation
let username: String
let password: String
let salt: String
let md5: String
let sha1: String
let sha256: String
let registered: String
let picture: UserPic
let version: String
struct UserName {
var title: String
var first: String
var last: String
}
struct UserLocation {
var street: String
var city: String
var state: String
var zip: String
}
struct UserPic {
var large: String
var medium: String
var thumbnail: String
}
init(JSON: AnyObject) {
let title = JSON.valueForKeyPath("name.title") as String
// all characters are lowercase. So, should be captialized for the first character
let first = (JSON.valueForKeyPath("name.first") as String).capitalizedString
let last = (JSON.valueForKeyPath("name.last") as String).capitalizedString
name = UserName(title: title, first: first, last: last)
SSN = JSON.valueForKeyPath("SSN") as String
phone = JSON.valueForKeyPath("phone") as String
cell = JSON.valueForKeyPath("cell") as String
dob = JSON.valueForKeyPath("dob") as String
email = JSON.valueForKeyPath("email") as String
gender = JSON.valueForKeyPath("gender") as String
let street = JSON.valueForKeyPath("location.street") as String
let city = JSON.valueForKeyPath("location.city") as String
let state = JSON.valueForKeyPath("location.state") as String
let zip = JSON.valueForKeyPath("location.zip") as String
location = UserLocation(street: street, city: city, state: state, zip: zip)
username = JSON.valueForKeyPath("username") as String
password = JSON.valueForKeyPath("password") as String
salt = JSON.valueForKeyPath("salt") as String
md5 = JSON.valueForKeyPath("md5") as String
sha1 = JSON.valueForKeyPath("sha1") as String
sha256 = JSON.valueForKeyPath("sha256") as String
registered = JSON.valueForKeyPath("registered") as String
let large = JSON.valueForKeyPath("picture.large") as String
let medium = JSON.valueForKeyPath("picture.medium") as String
let thumbnail = JSON.valueForKeyPath("picture.thumbnail") as String
picture = UserPic(large: large, medium: medium, thumbnail: thumbnail)
version = JSON.valueForKeyPath("version") as String
}
// protocol function for ResponseCollectionSerializable
class func collection(#response: NSHTTPURLResponse, representation: AnyObject) -> [User] {
var users = [User]()
let results = representation.valueForKeyPath("results") as [NSDictionary]
var index = 0
for user in results {
let userDetail = user.valueForKeyPath("user") as NSDictionary
users.append(User(JSON: userDetail))
}
// Sorting by First name
users.sort({$0.name.first < $1.name.first})
return users
}
} | gpl-2.0 | c0da82c254a528b4e1a697a5b604396e | 35.403101 | 158 | 0.643876 | 4.926548 | false | false | false | false |
doncl/shortness-of-pants | BBPTable/BBPTable/BBPTableLayout.swift | 1 | 5386 | //
// BBPTableLayout.swift
// BBPTable
//
// Created by Don Clore on 8/3/15.
// Copyright (c) 2015 Beer Barrel Poker Studios. All rights reserved.
//
import UIKit
class BBPTableLayout: UICollectionViewLayout {
//MARK: static constants
// TODO: These possibly should be exposed as properties on the object, with a default
// value that works for most cases.
static let cellVerticalPadding: Double = 15.0
static let cellHorizontalPadding: Double = 15.0
//MARK: Instance data
var columnWidths: Array<CGFloat> = []
var rowHeight: CGFloat?
var tableHeight: CGFloat?
var tableWidth: CGFloat?
var rows: Int?
var columns: Int?
//MARK: UICollectionViewLayout implementation.
override func layoutAttributesForItem(at indexPath: IndexPath) ->
UICollectionViewLayoutAttributes? {
let attrs = UICollectionViewLayoutAttributes(forCellWith: indexPath)
attrs.frame = frameForItemAtIndexPath(indexPath)
return attrs
}
override func layoutAttributesForElements(in rect: CGRect) -> [UICollectionViewLayoutAttributes]? {
var attrsArray: [UICollectionViewLayoutAttributes] = []
guard let columns = columns, let rows = rows else {
return attrsArray
}
for i in 0..<columns {
for j in 0..<rows {
let cellRect = getCellRect(i, row: j)
if (cellRect.intersects(rect)) {
let indexPath = IndexPath(item:i, section:j)
let attrs = layoutAttributesForItem(at: indexPath)
attrsArray.append(attrs!)
}
}
}
return attrsArray
}
override var collectionViewContentSize : CGSize {
return CGSize(width: tableWidth!, height: tableHeight!)
}
fileprivate func frameForItemAtIndexPath(_ indexPath:IndexPath) -> CGRect {
// section is row, row is column.
return getCellRect(indexPath.row, row: indexPath.section)
}
fileprivate func getCellRect(_ column: Int, row: Int) -> CGRect {
var x = CGFloat(0.0)
let y = CGFloat(row) * rowHeight!
let height = rowHeight!
// The column widths are variable values, so they have to be added up.
for i in 0..<column {
x += columnWidths[i]
}
let width = columnWidths[column]
return CGRect(x:x, y:y, width:width, height:height)
}
//MARK: CalculateCellSizes implementation.
func calculateCellSizes(_ model: BBPTableModel) {
tableWidth = 0.0
columns = model.numberOfColumns
rows = model.numberOfRows
rowHeight = 0.0
guard let columns = columns else {
return
}
for i in 0..<columns {
let columnSize = calculateColumnSize(model, columnIndex: i, rowCount: rows!)
columnWidths.append(columnSize.width)
assert(rowHeight != nil)
if columnSize.height > rowHeight! {
rowHeight = columnSize.height
}
tableWidth! += columnSize.width
}
tableHeight = rowHeight! * CGFloat(rows!)
}
fileprivate func calculateColumnSize(
_ model: BBPTableModel,
columnIndex: Int,
rowCount: Int) -> CGSize {
var largestWidth = CGFloat(0.0)
var largestHeight = CGFloat(0.0)
for i in 0..<rowCount {
let cellData = model.dataAtLocation(i, column: columnIndex)
let type = model.getCellType(i)
let cellInfo = BBPTableCell.getCellInfoForTypeOfCell(type)
let font = UIFont(name: cellInfo.fontName, size: cellInfo.fontSize)
// The Interwebs suggests we'll get better and more accurate required lengths for
// strings by replacing the spaces with a capital letter glyph.
let newString = cellData.replacingOccurrences(of: " ", with: "X")
let attributes = [convertFromNSAttributedStringKey(NSAttributedString.Key.font) : font!]
let rect = NSString(string: newString).boundingRect(
with: CGSize(width: CGFloat.greatestFiniteMagnitude, height:CGFloat.greatestFiniteMagnitude),
options:NSStringDrawingOptions.usesLineFragmentOrigin,
attributes:convertToOptionalNSAttributedStringKeyDictionary(attributes),
context:nil)
if rect.size.height > largestHeight {
largestHeight = rect.size.height
}
if rect.size.width > largestWidth {
largestWidth = rect.size.width
}
}
return CGSize(
width:largestWidth + CGFloat((BBPTableLayout.cellHorizontalPadding * 2.0)),
height:largestHeight + CGFloat((BBPTableLayout.cellVerticalPadding * 2.0)))
}
}
fileprivate func convertFromNSAttributedStringKey(_ input: NSAttributedString.Key) -> String {
return input.rawValue
}
fileprivate func convertToOptionalNSAttributedStringKeyDictionary(_ input: [String: Any]?) -> [NSAttributedString.Key: Any]? {
guard let input = input else { return nil }
return Dictionary(uniqueKeysWithValues: input.map { key, value in (NSAttributedString.Key(rawValue: key), value)})
}
| mit | 125b09f5c603abb681cb26f9926e0440 | 36.144828 | 126 | 0.618455 | 5.038354 | false | false | false | false |
domenicosolazzo/practice-swift | AR/ARVision/ARVision/Logic.swift | 1 | 2795 | //
// Scene.swift
// ARVision
//
// Created by Domenico Solazzo on 8/24/17.
// Copyright ยฉ 2017 Domenico Solazzo. All rights reserved.
//
import SpriteKit
import ARKit
import Vision
class Scene: SKScene {
override func didMove(to view: SKView) {
// Setup your scene here
}
override func update(_ currentTime: TimeInterval) {
// Called before each frame is rendered
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
guard let sceneView = self.view as? ARSKView else {
return
}
// Create anchor using the camera's current position
if let currentFrame = sceneView.session.currentFrame {
DispatchQueue.global(qos: .background).async {
do {
// Let's create a new instance of the Inception V3 model
let model = try VNCoreMLModel(for: Inceptionv3().model)
// Create a VNCoreMLRequest with a completion handler
let request = VNCoreMLRequest(model: model, completionHandler: { (request, error) in
// Jump onto the main thread
DispatchQueue.main.async {
// Access the first result in the array after casting the array as a VNClassificationObservation array
guard let results = request.results as? [VNClassificationObservation], let result = results.first else {
print ("No results?")
return
}
// Create a transform with a translation of 0.2 meters in front of the camera
var translation = matrix_identity_float4x4
translation.columns.3.z = -0.4
let transform = simd_mul(currentFrame.camera.transform, translation)
// Add a new anchor to the session
let anchor = ARAnchor(transform: transform)
// Set the identifier
ARBridge.shared.anchorsToIdentifiers[anchor] = result.identifier
sceneView.session.add(anchor: anchor)
}
})
// Create a VNImageRequestHandler
let handler = VNImageRequestHandler(cvPixelBuffer: currentFrame.capturedImage, options: [:])
try handler.perform([request])
}catch{
}
}
}
}
}
| mit | a06b75e6a5e0ad2fdcc504006b7cc5b3 | 39.492754 | 132 | 0.499642 | 5.982869 | false | false | false | false |
onevcat/Kingfisher | Demo/Demo/Kingfisher-Demo/ViewControllers/ProcessorCollectionViewController.swift | 1 | 4739 | //
// ProcessorCollectionViewController.swift
// Kingfisher
//
// Created by onevcat on 2018/11/19.
//
// Copyright (c) 2019 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
import Kingfisher
private let reuseIdentifier = "ProcessorCell"
class ProcessorCollectionViewController: UICollectionViewController {
var currentProcessor: ImageProcessor = DefaultImageProcessor.default {
didSet {
collectionView.reloadData()
}
}
var processors: [(ImageProcessor, String)] = [
(DefaultImageProcessor.default, "Default"),
(ResizingImageProcessor(referenceSize: CGSize(width: 50, height: 50)), "Resizing"),
(RoundCornerImageProcessor(radius: .point(20)), "Round Corner"),
(RoundCornerImageProcessor(radius: .widthFraction(0.5), roundingCorners: [.topLeft, .bottomRight]), "Round Corner Partial"),
(BorderImageProcessor(border: .init(color: .systemBlue, lineWidth: 8)), "Border"),
(RoundCornerImageProcessor(radius: .widthFraction(0.2)) |> BorderImageProcessor(border: .init(color: UIColor.systemBlue.withAlphaComponent(0.7), lineWidth: 12, radius: .widthFraction(0.2))), "Round Border"),
(BlendImageProcessor(blendMode: .lighten, alpha: 1.0, backgroundColor: .red), "Blend"),
(BlurImageProcessor(blurRadius: 5), "Blur"),
(OverlayImageProcessor(overlay: .red, fraction: 0.5), "Overlay"),
(TintImageProcessor(tint: UIColor.red.withAlphaComponent(0.5)), "Tint"),
(ColorControlsProcessor(brightness: 0.0, contrast: 1.1, saturation: 1.1, inputEV: 1.0), "Vibrancy"),
(BlackWhiteProcessor(), "B&W"),
(CroppingImageProcessor(size: CGSize(width: 100, height: 100)), "Cropping"),
(DownsamplingImageProcessor(size: CGSize(width: 25, height: 25)), "Downsampling"),
(BlurImageProcessor(blurRadius: 5) |> RoundCornerImageProcessor(cornerRadius: 20), "Blur + Round Corner")
]
override func viewDidLoad() {
super.viewDidLoad()
title = "Processor"
setupOperationNavigationBar()
}
override func numberOfSections(in collectionView: UICollectionView) -> Int {
return 1
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return ImageLoader.sampleImageURLs.count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! ImageCollectionViewCell
let url = ImageLoader.sampleImageURLs[indexPath.row]
KF.url(url)
.setProcessor(currentProcessor)
.serialize(as: .PNG)
.onSuccess { print($0) }
.onFailure { print($0) }
.set(to: cell.cellImageView)
return cell
}
override func alertPopup(_ sender: Any) -> UIAlertController {
let alert = super.alertPopup(sender)
alert.addAction(UIAlertAction(title: "Processor", style: .default, handler: { _ in
let alert = UIAlertController(title: "Processor", message: nil, preferredStyle: .actionSheet)
for item in self.processors {
alert.addAction(UIAlertAction(title: item.1, style: .default) { _ in self.currentProcessor = item.0 })
}
alert.addAction(UIAlertAction(title: "Cancel", style: .cancel))
alert.popoverPresentationController?.barButtonItem = sender as? UIBarButtonItem
self.present(alert, animated: true)
}))
return alert
}
}
| mit | 56eb3a0b6ab34a5404eb253a128e289b | 46.868687 | 215 | 0.691496 | 4.682806 | false | false | false | false |
sbaik/SwiftAnyPic | SwiftAnyPic/Reachability.swift | 6 | 13132 | /*
Copyright (c) 2014, Ashley Mills
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.
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 SystemConfiguration
import Foundation
public let ReachabilityChangedNotification = "ReachabilityChangedNotification"
func callback(reachability:SCNetworkReachability, flags: SCNetworkReachabilityFlags, info: UnsafeMutablePointer<Void>) {
let reachability = Unmanaged<Reachability>.fromOpaque(COpaquePointer(info)).takeUnretainedValue()
dispatch_async(dispatch_get_main_queue()) {
reachability.reachabilityChanged(flags)
}
}
public class Reachability: NSObject {
public typealias NetworkReachable = (Reachability) -> ()
public typealias NetworkUneachable = (Reachability) -> ()
public enum NetworkStatus: CustomStringConvertible {
case NotReachable, ReachableViaWiFi, ReachableViaWWAN
public var description: String {
switch self {
case .ReachableViaWWAN:
return "Cellular"
case .ReachableViaWiFi:
return "WiFi"
case .NotReachable:
return "No Connection"
}
}
}
// MARK: - *** Public properties ***
public var whenReachable: NetworkReachable?
public var whenUnreachable: NetworkUneachable?
public var reachableOnWWAN: Bool
public var notificationCenter = NSNotificationCenter.defaultCenter()
public var currentReachabilityStatus: NetworkStatus {
if isReachable() {
if isReachableViaWiFi() {
return .ReachableViaWiFi
}
if isRunningOnDevice {
return .ReachableViaWWAN
}
}
return .NotReachable
}
public var currentReachabilityString: String {
return "\(currentReachabilityStatus)"
}
// MARK: - *** Initialisation methods ***
required public init?(reachabilityRef: SCNetworkReachability?) {
reachableOnWWAN = true
self.reachabilityRef = reachabilityRef
}
public convenience init?(hostname: String) {
let nodename = (hostname as NSString).UTF8String
let ref = SCNetworkReachabilityCreateWithName(nil, nodename)
self.init(reachabilityRef: ref)
}
public class func reachabilityForInternetConnection() -> Reachability? {
var zeroAddress = sockaddr_in()
zeroAddress.sin_len = UInt8(sizeofValue(zeroAddress))
zeroAddress.sin_family = sa_family_t(AF_INET)
let ref = withUnsafePointer(&zeroAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
return Reachability(reachabilityRef: ref)
}
public class func reachabilityForLocalWiFi() -> Reachability? {
var localWifiAddress: sockaddr_in = sockaddr_in(sin_len: __uint8_t(0), sin_family: sa_family_t(0), sin_port: in_port_t(0), sin_addr: in_addr(s_addr: 0), sin_zero: (0, 0, 0, 0, 0, 0, 0, 0))
localWifiAddress.sin_len = UInt8(sizeofValue(localWifiAddress))
localWifiAddress.sin_family = sa_family_t(AF_INET)
// IN_LINKLOCALNETNUM is defined in <netinet/in.h> as 169.254.0.0
let address: Int64 = 0xA9FE0000
localWifiAddress.sin_addr.s_addr = in_addr_t(address.bigEndian)
let ref = withUnsafePointer(&localWifiAddress) {
SCNetworkReachabilityCreateWithAddress(nil, UnsafePointer($0))
}
return Reachability(reachabilityRef: ref)
}
// MARK: - *** Notifier methods ***
public func startNotifier() -> Bool {
if notifierRunning { return true }
var context = SCNetworkReachabilityContext(version: 0, info: nil, retain: nil, release: nil, copyDescription: nil)
context.info = UnsafeMutablePointer(Unmanaged.passUnretained(self).toOpaque())
if SCNetworkReachabilitySetCallback(reachabilityRef!, callback, &context) {
if SCNetworkReachabilitySetDispatchQueue(reachabilityRef!, reachabilitySerialQueue) {
notifierRunning = true
return true
}
}
stopNotifier()
return false
}
public func stopNotifier() {
if let reachabilityRef = reachabilityRef {
SCNetworkReachabilitySetCallback(reachabilityRef, nil, nil)
}
reachabilityRef = nil
}
// MARK: - *** Connection test methods ***
public func isReachable() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isReachableWithFlags(flags)
})
}
public func isReachableViaWWAN() -> Bool {
if isRunningOnDevice {
return isReachableWithTest() { flags -> Bool in
// Check we're REACHABLE
if self.isReachable(flags) {
// Now, check we're on WWAN
if self.isOnWWAN(flags) {
return true
}
}
return false
}
}
return false
}
public func isReachableViaWiFi() -> Bool {
return isReachableWithTest() { flags -> Bool in
// Check we're reachable
if self.isReachable(flags) {
if self.isRunningOnDevice {
// Check we're NOT on WWAN
if self.isOnWWAN(flags) {
return false
}
}
return true
}
return false
}
}
// MARK: - *** Private methods ***
private var isRunningOnDevice: Bool = {
#if (arch(i386) || arch(x86_64)) && os(iOS)
return false
#else
return true
#endif
}()
private var notifierRunning = false
private var reachabilityRef: SCNetworkReachability?
private let reachabilitySerialQueue = dispatch_queue_create("uk.co.ashleymills.reachability", DISPATCH_QUEUE_SERIAL)
private func reachabilityChanged(flags: SCNetworkReachabilityFlags) {
if isReachableWithFlags(flags) {
if let block = whenReachable {
block(self)
}
} else {
if let block = whenUnreachable {
block(self)
}
}
notificationCenter.postNotificationName(ReachabilityChangedNotification, object:self)
}
private func isReachableWithFlags(flags: SCNetworkReachabilityFlags) -> Bool {
let reachable = isReachable(flags)
if !reachable {
return false
}
if isConnectionRequiredOrTransient(flags) {
return false
}
if isRunningOnDevice {
if isOnWWAN(flags) && !reachableOnWWAN {
// We don't want to connect when on 3G.
return false
}
}
return true
}
private func isReachableWithTest(test: (SCNetworkReachabilityFlags) -> (Bool)) -> Bool {
if let reachabilityRef = reachabilityRef {
var flags = SCNetworkReachabilityFlags(rawValue: 0)
let gotFlags: Bool = withUnsafeMutablePointer(&flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return test(flags)
}
}
return false
}
// WWAN may be available, but not active until a connection has been established.
// WiFi may require a connection for VPN on Demand.
private func isConnectionRequired() -> Bool {
return connectionRequired()
}
private func connectionRequired() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags)
})
}
// Dynamic, on demand connection?
private func isConnectionOnDemand() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags) && self.isConnectionOnTrafficOrDemand(flags)
})
}
// Is user intervention required?
private func isInterventionRequired() -> Bool {
return isReachableWithTest({ (flags: SCNetworkReachabilityFlags) -> (Bool) in
return self.isConnectionRequired(flags) && self.isInterventionRequired(flags)
})
}
private func isOnWWAN(flags: SCNetworkReachabilityFlags) -> Bool {
#if os(iOS)
return flags.contains(.IsWWAN)
#else
return false
#endif
}
private func isReachable(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.Reachable)
}
private func isConnectionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionRequired)
}
private func isInterventionRequired(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.InterventionRequired)
}
private func isConnectionOnTraffic(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionOnTraffic)
}
private func isConnectionOnDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.ConnectionOnDemand)
}
func isConnectionOnTrafficOrDemand(flags: SCNetworkReachabilityFlags) -> Bool {
return !flags.intersect([.ConnectionOnTraffic, .ConnectionOnDemand]).isEmpty
}
private func isTransientConnection(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.TransientConnection)
}
private func isLocalAddress(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.IsLocalAddress)
}
private func isDirect(flags: SCNetworkReachabilityFlags) -> Bool {
return flags.contains(.IsDirect)
}
private func isConnectionRequiredOrTransient(flags: SCNetworkReachabilityFlags) -> Bool {
let testcase:SCNetworkReachabilityFlags = [.ConnectionRequired, .TransientConnection]
return flags.intersect(testcase) == testcase
}
private var reachabilityFlags: SCNetworkReachabilityFlags {
if let reachabilityRef = reachabilityRef {
var flags = SCNetworkReachabilityFlags(rawValue: 0)
let gotFlags: Bool = withUnsafeMutablePointer(&flags) {
SCNetworkReachabilityGetFlags(reachabilityRef, UnsafeMutablePointer($0))
}
if gotFlags {
return flags
}
}
return []
}
override public var description: String {
var W: String
if isRunningOnDevice {
W = isOnWWAN(reachabilityFlags) ? "W" : "-"
} else {
W = "X"
}
let R = isReachable(reachabilityFlags) ? "R" : "-"
let c = isConnectionRequired(reachabilityFlags) ? "c" : "-"
let t = isTransientConnection(reachabilityFlags) ? "t" : "-"
let i = isInterventionRequired(reachabilityFlags) ? "i" : "-"
let C = isConnectionOnTraffic(reachabilityFlags) ? "C" : "-"
let D = isConnectionOnDemand(reachabilityFlags) ? "D" : "-"
let l = isLocalAddress(reachabilityFlags) ? "l" : "-"
let d = isDirect(reachabilityFlags) ? "d" : "-"
return "\(W)\(R) \(c)\(t)\(i)\(C)\(D)\(l)\(d)"
}
deinit {
stopNotifier()
reachabilityRef = nil
whenReachable = nil
whenUnreachable = nil
}
}
| cc0-1.0 | 051e7ca6bf1c84e068d1044cfe882d14 | 33.832891 | 196 | 0.615595 | 5.752081 | false | false | false | false |
pennlabs/penn-mobile-ios | PennMobile/GSR-Booking/Views/GSRGroups/GroupSettingsCell.swift | 1 | 3791 | //
// GroupSettingsCell.swift
// PennMobile
//
// Created by Rehaan Furniturewala on 10/20/19.
// Copyright ยฉ 2019 PennLabs. All rights reserved.
//
import UIKit
class GroupSettingsCell: UITableViewCell {
static let cellHeight: CGFloat = 100
static let identifier = "gsrGroupSettingsCell"
fileprivate var titleLabel: UILabel!
fileprivate var descriptionLabel: UILabel!
fileprivate var isEnabledSwitch: UISwitch!
fileprivate var holderView: UIView!
var delegate: GSRGroupIndividualSettingDelegate?
var userSetting: GSRGroupIndividualSetting!
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func setupCell(with userSetting: GSRGroupIndividualSetting) {
self.userSetting = userSetting
if titleLabel == nil || descriptionLabel == nil || isEnabledSwitch == nil {
prepareUI()
}
titleLabel.text = userSetting.title
descriptionLabel.text = userSetting.descr
isEnabledSwitch.setOn(userSetting.isEnabled, animated: false)
}
@objc fileprivate func switchValueChanged() {
if let delegate = delegate {
userSetting.isEnabled = isEnabledSwitch.isOn
delegate.updateSetting(setting: userSetting)
}
}
}
// MARK: - Setup UI
extension GroupSettingsCell {
fileprivate func prepareUI() {
self.heightAnchor.constraint(equalToConstant: GroupSettingsCell.cellHeight).isActive = true
prepareHolderView()
prepareTitleLabel()
prepareDescriptionLabel()
prepareIsEnabledSwitch()
titleLabel.rightAnchor.constraint(equalTo: rightAnchor, constant: -100).isActive = true
// backgroundColor = .uiBackgroundSecondary
}
fileprivate func prepareHolderView() {
holderView = UIView()
addSubview(holderView)
let inset: CGFloat = 14.0
_ = holderView.anchor(topAnchor, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: inset, leftConstant: inset, bottomConstant: inset, rightConstant: inset, widthConstant: 0, heightConstant: 0)
}
fileprivate func prepareTitleLabel() {
titleLabel = UILabel()
holderView.addSubview(titleLabel)
_ = titleLabel.anchor(holderView.topAnchor, left: holderView.leftAnchor, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 30)
titleLabel.font = UIFont.systemFont(ofSize: 17.0, weight: .regular)
}
fileprivate func prepareDescriptionLabel() {
descriptionLabel = UILabel()
holderView.addSubview(descriptionLabel)
_ = descriptionLabel.anchor(titleLabel.bottomAnchor, left: titleLabel.leftAnchor, bottom: holderView.bottomAnchor, right: titleLabel.rightAnchor, topConstant: 5, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: 0)
descriptionLabel.numberOfLines = 3
descriptionLabel.textColor = UIColor.init(r: 153, g: 153, b: 153)
descriptionLabel.font = UIFont.systemFont(ofSize: 14.0, weight: .light)
}
fileprivate func prepareIsEnabledSwitch() {
isEnabledSwitch = UISwitch()
holderView.addSubview(isEnabledSwitch)
_ = isEnabledSwitch.anchor(titleLabel.topAnchor, left: nil, bottom: nil, right: holderView.rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 51, heightConstant: 0)
isEnabledSwitch.addTarget(self, action: #selector(switchValueChanged), for: .valueChanged)
}
}
| mit | ec04a857e1816db15dd4fdaa06a07853 | 38.479167 | 260 | 0.708443 | 4.877735 | false | false | false | false |
practicalswift/swift | test/attr/accessibility_proto.swift | 23 | 5720 | // RUN: %target-typecheck-verify-swift
// RUN: %target-swift-frontend -typecheck -disable-access-control %s
public protocol ProtoWithReqs {
associatedtype Assoc
func foo()
}
public struct Adopter<T> : ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
extension Adopter {
typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }}
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public struct Adopter2<T> : ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public extension Adopter2 {
internal typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-12=}}
fileprivate func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-15=}}
}
public struct Adopter3<T> : ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
internal extension Adopter3 {
typealias Assoc = Int
// expected-note@-1 {{move the type alias to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
func foo() {}
// expected-note@-1 {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
}
public class AnotherAdopterBase {
typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-3=public }}
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public class AnotherAdopterSub : AnotherAdopterBase, ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public class AnotherAdopterBase2 {}
public extension AnotherAdopterBase2 {
internal typealias Assoc = Int
// expected-note@-1 {{mark the type alias as 'public' to satisfy the requirement}} {{3-12=}}
fileprivate func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-15=}}
}
public class AnotherAdopterSub2 : AnotherAdopterBase2, ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public class AnotherAdopterBase3 {}
internal extension AnotherAdopterBase3 {
typealias Assoc = Int
// expected-note@-1 {{move the type alias to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
func foo() {}
// expected-note@-1 {{move the instance method to another extension where it can be declared 'public' to satisfy the requirement}} {{none}}
}
public class AnotherAdopterSub3 : AnotherAdopterBase3, ProtoWithReqs {}
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
// expected-error@-2 {{type alias 'Assoc' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public protocol ReqProvider {}
extension ReqProvider {
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public struct AdoptViaProtocol : ProtoWithReqs, ReqProvider {
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public typealias Assoc = Int
}
public protocol ReqProvider2 {}
extension ProtoWithReqs where Self : ReqProvider2 {
func foo() {}
// expected-note@-1 {{mark the instance method as 'public' to satisfy the requirement}} {{3-3=public }}
}
public struct AdoptViaCombinedProtocol : ProtoWithReqs, ReqProvider2 {
// expected-error@-1 {{method 'foo()' must be declared public because it matches a requirement in public protocol 'ProtoWithReqs'}} {{none}}
public typealias Assoc = Int
}
public protocol PublicInitProto {
var value: Int { get }
init(value: Int)
}
public struct NonPublicInitStruct: PublicInitProto {
public var value: Int
init(value: Int) {
// expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}}
// expected-note@-2 {{mark the initializer as 'public' to satisfy the requirement}}
self.value = value
}
}
public struct NonPublicMemberwiseInitStruct: PublicInitProto {
// expected-error@-1 {{initializer 'init(value:)' must be declared public because it matches a requirement in public protocol 'PublicInitProto'}}
public var value: Int
}
| apache-2.0 | 3316be2952858e7f43d09a4018c1fd30 | 52.962264 | 147 | 0.734091 | 4.074074 | false | false | false | false |
AlexZd/SwiftUtils | Pod/Utils/UIAlertAction+Helpers.swift | 1 | 1105 | //
// UIAlertAction+Helpers.swift
// Pods
//
// Created by Alex Zdorovets on 11/14/16.
//
//
import Foundation
import UIKit
public typealias UIAlertActionHandler = (UIAlertAction) -> Swift.Void
private var handlerAssociationKey: UInt8 = 0
extension UIAlertAction {
private var omg: [String: UIAlertActionHandler] {
get { return objc_getAssociatedObject(self, &handlerAssociationKey) as? [String: UIAlertActionHandler] ?? [:] }
set { objc_setAssociatedObject(self, &handlerAssociationKey, newValue, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN) }
}
/** Action's handler */
public var actionHandler: UIAlertActionHandler? {
return self.omg["closure"]
}
/** Creates and returns an action with the specified title and behavior, helping to store handler */
public convenience init(title: String?, style: UIAlertAction.Style = .default, closure: UIAlertActionHandler? = nil) {
self.init(title: title, style: style, handler: closure)
if let closure = closure {
self.omg["closure"] = closure
}
}
}
| mit | a3cc2b70b64d86da22f32d3414c0d992 | 31.5 | 128 | 0.683258 | 4.367589 | false | false | false | false |
practicalswift/swift | test/Constraints/bridging.swift | 4 | 17723 | // RUN: %target-typecheck-verify-swift
// REQUIRES: objc_interop
import Foundation
public class BridgedClass : NSObject, NSCopying {
@objc(copyWithZone:)
public func copy(with zone: NSZone?) -> Any {
return self
}
}
public class BridgedClassSub : BridgedClass { }
// Attempt to bridge to a type from another module. We only allow this for a
// few specific types, like String.
extension LazyFilterSequence.Iterator : _ObjectiveCBridgeable { // expected-error{{conformance of 'Iterator' to '_ObjectiveCBridgeable' can only be written in module 'Swift'}}
public typealias _ObjectiveCType = BridgedClassSub
public func _bridgeToObjectiveC() -> _ObjectiveCType {
return BridgedClassSub()
}
public static func _forceBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterSequence.Iterator?
) { }
public static func _conditionallyBridgeFromObjectiveC(
_ source: _ObjectiveCType,
result: inout LazyFilterSequence.Iterator?
) -> Bool {
return true
}
public static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?)
-> LazyFilterSequence.Iterator {
let result: LazyFilterSequence.Iterator?
return result!
}
}
struct BridgedStruct : Hashable, _ObjectiveCBridgeable {
func hash(into hasher: inout Hasher) {}
func _bridgeToObjectiveC() -> BridgedClass {
return BridgedClass()
}
static func _forceBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?) {
}
static func _conditionallyBridgeFromObjectiveC(
_ x: BridgedClass,
result: inout BridgedStruct?
) -> Bool {
return true
}
static func _unconditionallyBridgeFromObjectiveC(_ source: BridgedClass?)
-> BridgedStruct {
var result: BridgedStruct?
_forceBridgeFromObjectiveC(source!, result: &result)
return result!
}
}
func ==(x: BridgedStruct, y: BridgedStruct) -> Bool { return true }
struct NotBridgedStruct : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(x: NotBridgedStruct, y: NotBridgedStruct) -> Bool { return true }
class OtherClass : Hashable {
func hash(into hasher: inout Hasher) {}
}
func ==(x: OtherClass, y: OtherClass) -> Bool { return true }
// Basic bridging
func bridgeToObjC(_ s: BridgedStruct) -> BridgedClass {
return s // expected-error{{cannot convert return expression of type 'BridgedStruct' to return type 'BridgedClass'}}
return s as BridgedClass
}
func bridgeToAnyObject(_ s: BridgedStruct) -> AnyObject {
return s // expected-error{{return expression of type 'BridgedStruct' does not conform to 'AnyObject'}}
return s as AnyObject
}
func bridgeFromObjC(_ c: BridgedClass) -> BridgedStruct {
return c // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return c as BridgedStruct
}
func bridgeFromObjCDerived(_ s: BridgedClassSub) -> BridgedStruct {
return s // expected-error{{'BridgedClassSub' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
return s as BridgedStruct
}
// Array -> NSArray
func arrayToNSArray() {
var nsa: NSArray
nsa = [AnyObject]() // expected-error {{cannot assign value of type '[AnyObject]' to type 'NSArray'}}
nsa = [BridgedClass]() // expected-error {{cannot assign value of type '[BridgedClass]' to type 'NSArray'}}
nsa = [OtherClass]() // expected-error {{cannot assign value of type '[OtherClass]' to type 'NSArray'}}
nsa = [BridgedStruct]() // expected-error {{cannot assign value of type '[BridgedStruct]' to type 'NSArray'}}
nsa = [NotBridgedStruct]() // expected-error{{cannot assign value of type '[NotBridgedStruct]' to type 'NSArray'}}
nsa = [AnyObject]() as NSArray
nsa = [BridgedClass]() as NSArray
nsa = [OtherClass]() as NSArray
nsa = [BridgedStruct]() as NSArray
nsa = [NotBridgedStruct]() as NSArray
_ = nsa
}
// NSArray -> Array
func nsArrayToArray(_ nsa: NSArray) {
var arr1: [AnyObject] = nsa // expected-error{{'NSArray' is not implicitly convertible to '[AnyObject]'; did you mean to use 'as' to explicitly convert?}} {{30-30= as [AnyObject]}}
var _: [BridgedClass] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedClass]'}} {{30-30= as! [BridgedClass]}}
var _: [OtherClass] = nsa // expected-error{{'NSArray' is not convertible to '[OtherClass]'}} {{28-28= as! [OtherClass]}}
var _: [BridgedStruct] = nsa // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'}} {{31-31= as! [BridgedStruct]}}
var _: [NotBridgedStruct] = nsa // expected-error{{use 'as!' to force downcast}}
var _: [AnyObject] = nsa as [AnyObject]
var _: [BridgedClass] = nsa as [BridgedClass] // expected-error{{'NSArray' is not convertible to '[BridgedClass]'; did you mean to use 'as!' to force downcast?}} {{31-33=as!}}
var _: [OtherClass] = nsa as [OtherClass] // expected-error{{'NSArray' is not convertible to '[OtherClass]'; did you mean to use 'as!' to force downcast?}} {{29-31=as!}}
var _: [BridgedStruct] = nsa as [BridgedStruct] // expected-error{{'NSArray' is not convertible to '[BridgedStruct]'; did you mean to use 'as!' to force downcast?}} {{32-34=as!}}
var _: [NotBridgedStruct] = nsa as [NotBridgedStruct] // expected-error{{use 'as!' to force downcast}}
var arr6: Array = nsa as Array
arr6 = arr1
arr1 = arr6
}
func dictionaryToNSDictionary() {
// FIXME: These diagnostics are awful.
var nsd: NSDictionary
nsd = [NSObject : AnyObject]() // expected-error {{cannot assign value of type '[NSObject : AnyObject]' to type 'NSDictionary'}}
nsd = [NSObject : AnyObject]() as NSDictionary
nsd = [NSObject : BridgedClass]() // expected-error {{cannot assign value of type '[NSObject : BridgedClass]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass]() as NSDictionary
nsd = [NSObject : OtherClass]() // expected-error {{cannot assign value of type '[NSObject : OtherClass]' to type 'NSDictionary'}}
nsd = [NSObject : OtherClass]() as NSDictionary
nsd = [NSObject : BridgedStruct]() // expected-error {{cannot assign value of type '[NSObject : BridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct]() as NSDictionary
nsd = [NSObject : NotBridgedStruct]() // expected-error{{cannot assign value of type '[NSObject : NotBridgedStruct]' to type 'NSDictionary'}}
nsd = [NSObject : NotBridgedStruct]() as NSDictionary
nsd = [NSObject : BridgedClass?]() // expected-error{{cannot assign value of type '[NSObject : BridgedClass?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedClass?]() as NSDictionary
nsd = [NSObject : BridgedStruct?]() // expected-error{{cannot assign value of type '[NSObject : BridgedStruct?]' to type 'NSDictionary'}}
nsd = [NSObject : BridgedStruct?]() as NSDictionary
nsd = [BridgedClass : AnyObject]() // expected-error {{cannot assign value of type '[BridgedClass : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedClass : AnyObject]() as NSDictionary
nsd = [OtherClass : AnyObject]() // expected-error {{cannot assign value of type '[OtherClass : AnyObject]' to type 'NSDictionary'}}
nsd = [OtherClass : AnyObject]() as NSDictionary
nsd = [BridgedStruct : AnyObject]() // expected-error {{cannot assign value of type '[BridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [BridgedStruct : AnyObject]() as NSDictionary
nsd = [NotBridgedStruct : AnyObject]() // expected-error{{cannot assign value of type '[NotBridgedStruct : AnyObject]' to type 'NSDictionary'}}
nsd = [NotBridgedStruct : AnyObject]() as NSDictionary
// <rdar://problem/17134986>
var bcOpt: BridgedClass?
nsd = [BridgedStruct() : bcOpt as Any]
bcOpt = nil
_ = nsd
}
// In this case, we should not implicitly convert Dictionary to NSDictionary.
struct NotEquatable {}
func notEquatableError(_ d: Dictionary<Int, NotEquatable>) -> Bool {
// FIXME: Another awful diagnostic.
return d == d // expected-error{{'<Self where Self : Equatable> (Self.Type) -> (Self, Self) -> Bool' requires that 'NotEquatable' conform to 'Equatable'}}
// expected-note @-1 {{requirement from conditional conformance of 'Dictionary<Int, NotEquatable>' to 'Equatable'}}
// expected-error @-2 {{type 'NotEquatable' does not conform to protocol 'Equatable'}}
// expected-note @-3{{requirement specified as 'NotEquatable' : 'Equatable'}}
}
// NSString -> String
var nss1 = "Some great text" as NSString
var nss2: NSString = ((nss1 as String) + ", Some more text") as NSString
// <rdar://problem/17943223>
var inferDouble = 1.0/10
let d: Double = 3.14159
inferDouble = d
// rdar://problem/17962491
_ = 1 % 3 / 3.0 // expected-error{{'%' is unavailable: For floating point numbers use truncatingRemainder instead}}
var inferDouble2 = 1 / 3 / 3.0
let d2: Double = 3.14159
inferDouble2 = d2
// rdar://problem/18269449
var i1: Int = 1.5 * 3.5 // expected-error {{cannot convert value of type 'Double' to specified type 'Int'}}
// rdar://problem/18330319
func rdar18330319(_ s: String, d: [String : AnyObject]) {
_ = d[s] as! String?
}
// rdar://problem/19551164
func rdar19551164a(_ s: String, _ a: [String]) {}
func rdar19551164b(_ s: NSString, _ a: NSArray) {
rdar19551164a(s, a) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{18-18= as String}}
// expected-error@-1{{'NSArray' is not convertible to '[String]'; did you mean to use 'as!' to force downcast?}}{{21-21= as! [String]}}
}
// rdar://problem/19695671
func takesSet<T>(_ p: Set<T>) {} // expected-note {{in call to function 'takesSet'}}
func takesDictionary<K, V>(_ p: Dictionary<K, V>) {} // expected-note {{in call to function 'takesDictionary'}}
func takesArray<T>(_ t: Array<T>) {} // expected-note {{in call to function 'takesArray'}}
func rdar19695671() {
takesSet(NSSet() as! Set) // expected-error{{generic parameter 'T' could not be inferred}}
takesDictionary(NSDictionary() as! Dictionary) // expected-error{{generic parameter 'K' could not be inferred}}
takesArray(NSArray() as! Array) // expected-error{{generic parameter 'T' could not be inferred}}
}
// This failed at one point while fixing rdar://problem/19600325.
func getArrayOfAnyObject(_: AnyObject) -> [AnyObject] { return [] }
func testCallback(_ f: (AnyObject) -> AnyObject?) {}
testCallback { return getArrayOfAnyObject($0) } // expected-error {{cannot convert value of type '[AnyObject]' to closure result type 'AnyObject?'}}
// <rdar://problem/19724719> Type checker thinks "(optionalNSString ?? nonoptionalNSString) as String" is a forced cast
func rdar19724719(_ f: (String) -> (), s1: NSString?, s2: NSString) {
f((s1 ?? s2) as String)
}
// <rdar://problem/19770981>
func rdar19770981(_ s: String, ns: NSString) {
func f(_ s: String) {}
f(ns) // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7= as String}}
f(ns as String)
// 'as' has higher precedence than '>' so no parens are necessary with the fixit:
s > ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{9-9= as String}}
_ = s > ns as String
ns > s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{5-5= as String}}
_ = ns as String > s
// 'as' has lower precedence than '+' so add parens with the fixit:
s + ns // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{7-7=(}}{{9-9= as String)}}
_ = s + (ns as String)
ns + s // expected-error{{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}{{3-3=(}}{{5-5= as String)}}
_ = (ns as String) + s
}
// <rdar://problem/19831919> Fixit offers as! conversions that are known to always fail
func rdar19831919() {
var s1 = 1 + "str"; // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and 'String'}} expected-note{{overloads for '+' exist with these partially matching parameter lists: (Int, Int), (String, String)}}
}
// <rdar://problem/19831698> Incorrect 'as' fixits offered for invalid literal expressions
func rdar19831698() {
var v70 = true + 1 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Int'}} expected-note {{expected an argument list of type '(Int, Int)'}}
var v71 = true + 1.0 // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and 'Double'}}
// expected-note@-1{{overloads for '+'}}
var v72 = true + true // expected-error{{binary operator '+' cannot be applied to two 'Bool' operands}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists:}}
var v73 = true + [] // expected-error{{binary operator '+' cannot be applied to operands of type 'Bool' and '[Any]'}}
// expected-note @-1 {{overloads for '+' exist with these partially matching parameter lists: (Array<Element>, Array<Element>), (Other, Self), (Self, Other)}}
var v75 = true + "str" // expected-error {{binary operator '+' cannot be applied to operands of type 'Bool' and 'String'}} expected-note {{expected an argument list of type '(String, String)'}}
}
// <rdar://problem/19836341> Incorrect fixit for NSString? to String? conversions
func rdar19836341(_ ns: NSString?, vns: NSString?) {
var vns = vns
let _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}}
var _: String? = ns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{22-22= as String?}}
// Important part about below diagnostic is that from-type is described as
// 'NSString?' and not '@lvalue NSString?':
let _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}}
var _: String? = vns // expected-error{{cannot convert value of type 'NSString?' to specified type 'String?'}}{{23-23= as String?}}
vns = ns
}
// <rdar://problem/20029786> Swift compiler sometimes suggests changing "as!" to "as?!"
func rdar20029786(_ ns: NSString?) {
var s: String = ns ?? "str" as String as String // expected-error{{cannot convert value of type 'NSString?' to expected argument type 'String?'}}{{21-21= as String?}}
var s2 = ns ?? "str" as String as String // expected-error {{cannot convert value of type 'String' to expected argument type 'NSString'}}{{43-43= as NSString}}
let s3: NSString? = "str" as String? // expected-error {{cannot convert value of type 'String?' to specified type 'NSString?'}}{{39-39= as NSString?}}
var s4: String = ns ?? "str" // expected-error{{cannot convert value of type 'NSString' to specified type 'String'}}{{31-31= as String}}
var s5: String = (ns ?? "str") as String // fixed version
}
// Make sure more complicated cast has correct parenthesization
func castMoreComplicated(anInt: Int?) {
let _: (NSObject & NSCopying)? = anInt // expected-error{{cannot convert value of type 'Int?' to specified type '(NSObject & NSCopying)?'}}{{41-41= as (NSObject & NSCopying)?}}
}
// <rdar://problem/19813772> QoI: Using as! instead of as in this case produces really bad diagnostic
func rdar19813772(_ nsma: NSMutableArray) {
var a1 = nsma as! Array // expected-error{{generic parameter 'Element' could not be inferred in cast to 'Array'}} expected-note {{explicitly specify the generic arguments to fix this issue}} {{26-26=<Any>}}
var a2 = nsma as! Array<AnyObject> // expected-warning{{forced cast from 'NSMutableArray' to 'Array<AnyObject>' always succeeds; did you mean to use 'as'?}} {{17-20=as}}
var a3 = nsma as Array<AnyObject>
}
func rdar28856049(_ nsma: NSMutableArray) {
_ = nsma as? [BridgedClass]
_ = nsma as? [BridgedStruct]
_ = nsma as? [BridgedClassSub]
}
// <rdar://problem/20336036> QoI: Add cast-removing fixit for "Forced cast from 'T' to 'T' always succeeds"
func force_cast_fixit(_ a : [NSString]) -> [NSString] {
return a as! [NSString] // expected-warning {{forced cast of '[NSString]' to same type has no effect}} {{12-27=}}
}
// <rdar://problem/21244068> QoI: IUO prevents specific diagnostic + fixit about non-implicitly converted bridge types
func rdar21244068(_ n: NSString!) -> String {
return n // expected-error {{'NSString' is not implicitly convertible to 'String'; did you mean to use 'as' to explicitly convert?}}
}
func forceBridgeDiag(_ obj: BridgedClass!) -> BridgedStruct {
return obj // expected-error{{'BridgedClass' is not implicitly convertible to 'BridgedStruct'; did you mean to use 'as' to explicitly convert?}}
}
struct KnownUnbridged {}
class KnownClass {}
protocol KnownClassProtocol: class {}
func forceUniversalBridgeToAnyObject<T, U: KnownClassProtocol>(a: T, b: U, c: Any, d: KnownUnbridged, e: KnownClass, f: KnownClassProtocol, g: AnyObject, h: String) {
var z: AnyObject
z = a as AnyObject
z = b as AnyObject
z = c as AnyObject
z = d as AnyObject
z = e as AnyObject
z = f as AnyObject
z = g as AnyObject
z = h as AnyObject
z = a // expected-error{{does not conform to 'AnyObject'}}
z = b
z = c // expected-error{{does not conform to 'AnyObject'}}
z = d // expected-error{{does not conform to 'AnyObject'}}
z = e
z = f
z = g
z = h // expected-error{{does not conform to 'AnyObject'}}
_ = z
}
func bridgeAnyContainerToAnyObject(x: [Any], y: [NSObject: Any]) {
var z: AnyObject
z = x as AnyObject
z = y as AnyObject
_ = z
}
func bridgeTupleToAnyObject() {
let x = (1, "two")
let y = x as AnyObject
_ = y
}
| apache-2.0 | e0e4facc1a8735490acd66b7ab3a757a | 46.387701 | 236 | 0.693506 | 4.060252 | false | false | false | false |
blockchain/My-Wallet-V3-iOS | Modules/Metadata/Sources/MetadataKit/Models/HDWallet/Mnemonic.swift | 1 | 1721 | // Copyright ยฉ Blockchain Luxembourg S.A. All rights reserved.
import Foundation
import MetadataHDWalletKit
import ToolKit
public enum MnemonicError: Error, Equatable {
case invalidLength
case invalidWords
}
struct Mnemonic {
let mnemonicString: String
let seedHex: String
let words: [String]
private init(
words: [String],
mnemonicString: String,
seedHex: String
) {
self.words = words
self.mnemonicString = mnemonicString
self.seedHex = seedHex
}
static func from(mnemonicString: String) -> Result<Self, MnemonicError> {
func words(
from mnemonicString: String
) -> Result<[String], MnemonicError> {
let words = mnemonicString
.lowercased()
.components(separatedBy: " ")
guard words.count == 12 else {
return .failure(.invalidLength)
}
// For now we only support the english wordlist
let BIP39Words = Set(MetadataHDWalletKit.WordList.english.words)
guard Set(words).isSubset(of: BIP39Words) else {
return .failure(.invalidWords)
}
return .success(words)
}
return words(from: mnemonicString)
.map { words -> Mnemonic in
let seedHex = MetadataHDWalletKit.Mnemonic
.createSeed(
mnemonic: mnemonicString
)
.hex
return Mnemonic(
words: words,
mnemonicString: mnemonicString,
seedHex: seedHex
)
}
}
}
| lgpl-3.0 | d65719458c2c46638a2d2ce6eda03370 | 24.294118 | 77 | 0.540698 | 5.134328 | false | false | false | false |
marekhac/WczasyNadBialym-iOS | WczasyNadBialym/WczasyNadBialym/Support/Helpers/LogEventHandler.swift | 1 | 874 | //
// LogEventHandler.swift
// WczasyNadBialym
//
// Created by Marek Haฤ on 26.07.2017.
// Copyright ยฉ 2017 Marek Haฤ. All rights reserved.
//
import Foundation
import SVProgressHUD
struct LogEventHandler {
static func report(_ logEventType: LogEventType = .info, _ message: String, _ description: String = "", displayWithHUD hud: Bool = false)
{
let debugMode = Bool(Environment().config(PlistKey.DebugMode)) ?? false
let logEvent = logEventType.rawValue
if (debugMode || (logEventType == .info)) {
if (description != "") {
print ("\(logEvent) \(message) --> \(description)")
} else {
print ("\(logEvent) \(message)")
}
if (hud) {
SVProgressHUD.showError(withStatus: message)
}
}
}
}
| gpl-3.0 | 12a8a70af2fa572792acd9d59845032b | 27.096774 | 141 | 0.552239 | 4.466667 | false | false | false | false |
zmian/xcore.swift | Sources/Xcore/Swift/Extensions/String/String+Formatter.swift | 1 | 5838 | //
// Xcore
// Copyright ยฉ 2017 Xcore
// MIT license, see LICENSE file for details
//
import Foundation
// MARK: - BlockFormatStyle
extension String {
/// A structure representing formatting of a string using a closure.
public struct BlockFormatStyle {
public let format: (String) -> String
/// An initializer to format given input string.
///
/// - Parameter format: A closure to format the input string.
public init(_ format: @escaping (String) -> String) {
self.format = format
}
}
/// Returns the result of given formatting style applied to `self`.
///
/// - Parameter style: The string formatting style.
public func formatted(_ style: BlockFormatStyle) -> String {
style.format(self)
}
}
// MARK: - Masked
extension String.BlockFormatStyle {
/// Automatically detects a valid email address and apply email masking.
///
/// ```swift
/// print("[email protected]".formatted(.masked))
/// // Prints "hโขโขโข@example.com"
///
/// print("[email protected]".formatted(.masked(count: .same)))
/// // Prints "hโขโขโขโข@example.com"
///
/// print("Hello World".formatted(.masked))
/// // Prints "โขโขโขโขโขโขโขโขโขโขโข"
/// ```
public static var masked: Self {
masked()
}
/// Automatically detects a valid email address and apply email masking.
///
/// ```swift
/// print("[email protected]".formatted(.masked))
/// // Prints "hโขโขโข@example.com"
///
/// print("[email protected]".formatted(.masked(count: .same)))
/// // Prints "hโขโขโขโข@example.com"
///
/// print("Hello World".formatted(.masked))
/// // Prints "โขโขโขโขโขโขโขโขโขโขโข"
/// ```
public static func masked(count: MaskCharacterCount? = nil) -> Self {
.init {
guard
$0.validate(rule: .email),
let firstIndex = $0.index(from: 1),
let lastIndex = $0.lastIndex(of: "@")
else {
let length = (count ?? .same).length(basedOn: $0.count)
return String(repeating: .mask, count: length)
}
var string = $0
let range = firstIndex..<lastIndex
let count = (count ?? .equal(3)).length(basedOn: $0.distance(from: range.lowerBound, to: range.upperBound))
string.replaceSubrange(range, with: String(repeating: .mask, count: count))
return string
}
}
/// Mask all except the first `n` characters.
///
/// ```swift
/// print("0123456789".formatted(.maskedAllExcept(first: 4))
/// // Prints "0123โขโขโขโขโขโข"
///
/// print("0123456789".formatted(.maskedAllExcept(first: 4, separator: " ")))
/// // Prints "0123 โขโขโขโขโขโข"
///
/// print("0123456789".formatted(.maskedAllExcept(first: 4, count: .equal(4), separator: " ")))
/// // Prints "0123 โขโขโขโข"
/// ```
public static func maskedAllExcept(first maxLength: Int, count: MaskCharacterCount = .same, separator: String = "") -> Self {
.init {
$0.prefix(maxLength) + count.string(count: $0.count - maxLength, separator: separator, suffix: false)
}
}
/// Mask all except the last `n` characters.
///
/// ```swift
/// print("0123456789".formatted(.maskedAllExcept(last: 4))
/// // Prints "โขโขโขโขโขโข6789"
///
/// print("0123456789".formatted(.maskedAllExcept(last: 4, separator: " ")))
/// // Prints "โขโขโขโขโขโข 6789"
///
/// print("0123456789".formatted(.maskedAllExcept(last: 4, count: .equal(4), separator: " ")))
/// // Prints "โขโขโขโข 6789"
///
/// print("0123456789".formatted(.maskedAccountNumber))
/// // Prints "โขโขโขโข 6789"
/// ```
public static func maskedAllExcept(last maxLength: Int, count: MaskCharacterCount = .same, separator: String = "") -> Self {
.init {
count.string(count: $0.count - maxLength, separator: separator, suffix: true) + $0.suffix(maxLength)
}
}
/// Masked with account number formatting.
///
/// ```swift
/// print("0123456789".formatted(.maskedAccountNumber))
/// // Prints "โขโขโขโข 6789"
/// ```
public static var maskedAccountNumber: Self {
maskedAllExcept(last: 4, count: .equal(4), separator: " ")
}
}
// MARK: - MaskCharacterCount
extension String.BlockFormatStyle {
public enum MaskCharacterCount {
/// Mask characters length is same as the input string length.
case same
/// Mask characters length is greater than or equal to `n`.
case min(Int)
/// Mask characters length is less than or equal to `n`.
case max(Int)
/// Mask characters length is equal to `n`.
case equal(Int)
fileprivate func length(basedOn count: Int) -> Int {
switch self {
case .same:
return Swift.max(0, count)
case let .min(value):
return Swift.max(value, count)
case let .max(value):
return Swift.min(value, Swift.max(0, count))
case let .equal(value):
return value
}
}
fileprivate func string(count: Int, separator: String, suffix: Bool) -> String {
let length = self.length(basedOn: count)
if case .equal = self {} else if length == 0 {
return ""
}
if suffix {
return String(repeating: .mask, count: length) + separator
} else {
return separator + String(repeating: .mask, count: length)
}
}
}
}
| mit | 7261eb15d1814fdd221c7d1db76ab6bc | 31.485714 | 129 | 0.547581 | 4.229911 | false | false | false | false |
djschilling/SOPA-iOS | SOPA/helper/LevelFileService.swift | 1 | 1124 | //
// LevelFileService.swift
// SOPA
//
// Created by Raphael Schilling on 31.10.17.
// Copyright ยฉ 2017 David Schilling. All rights reserved.
//
import Foundation
class LevelFileService {
private let LEVEL_BASE_PATH = "levels/"
let fileHandler: FileHandler
private let levelTranslator: LevelTranslator
init() {
levelTranslator = LevelTranslator()
fileHandler = FileHandler()
}
func getLevel(id: Int) -> Level{
let levelFilename: String = LEVEL_BASE_PATH + String(id) + ".lv"
return levelTranslator.fromString(levelLines: fileHandler.readFromFile(filename: levelFilename))
}
func getAvailableLevelIds() -> [Int] {
let filenamesInFolder: [String] = fileHandler.getFilenamesInFolder(folder: LEVEL_BASE_PATH);
var levelIds: [Int] = [Int]()
for i in filenamesInFolder {
if(i.contains(".lv")) {
let numberAsString : String = (i.components(separatedBy: "."))[0]
levelIds.append(Int(numberAsString)!)
}
}
return levelIds.sorted();
}
}
| apache-2.0 | c9a8058f98e9d02999314e20959098f1 | 27.794872 | 104 | 0.617988 | 4.159259 | false | false | false | false |
cscalcucci/Swift_Life | Swift_Life/BoardView.swift | 1 | 1997 | //
// BoardView.swift
// Swift_Life
//
// Created by Christopher Scalcucci on 2/14/16.
// Copyright ยฉ 2016 Christopher Scalcucci. All rights reserved.
//
import UIKit
class BoardView: UIView {
// MARK:- INIT
let board: Board
init(board: Board) {
self.board = board
super.init(frame: CGRectMake(0,0,0,0))
let tap = UITapGestureRecognizer(target: self, action: Selector("handleTap:"))
self.addGestureRecognizer(tap)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK:- DRAWING TO BOARD
override func drawRect(rect: CGRect) {
let context = UIGraphicsGetCurrentContext()
board.cellMatrix.forEach({ (_,_,cell) in
CGContextSetFillColorWithColor(context, cell.colorForCell().CGColor)
CGContextAddRect(context, frameForCell(cell))
CGContextFillPath(context)
})
}
private func cellAtPoint(point: CGPoint) -> Cell {
let x = floor(point.x / (self.bounds.width / CGFloat(board.width)))
let y = floor(point.y / (self.bounds.width / CGFloat(board.height)))
return board.cellMatrix[Int(x),Int(y)]
}
private func frameForCell(cell: Cell) -> CGRect {
func cellSize() -> CGSize {
return CGSize(width: bounds.width / CGFloat(board.width), height: bounds.height / CGFloat(board.height))
}
func cellOrigin() -> CGPoint {
return CGPoint(x: CGFloat(cell.position.x) * cellSize().width, y: CGFloat(cell.position.y) * cellSize().height)
}
return CGRect(origin: cellOrigin(), size: cellSize())
}
// MARK:- GESTURE HANDLING
internal func handleTap(sender: UITapGestureRecognizer) {
if sender.state == .Ended {
let touchLocation: CGPoint = sender.locationInView(sender.view)
cellAtPoint(touchLocation).toggleState()
self.setNeedsDisplay()
}
}
}
| mit | 56a3eb120ae82f17ad165e2e6da9f9d0 | 28.352941 | 123 | 0.624749 | 4.246809 | false | false | false | false |
king7532/TaylorSource | examples/Gallery/Pods/HanekeSwift/Haneke/DiskFetcher.swift | 48 | 2463 | //
// DiskFetcher.swift
// Haneke
//
// Created by Joan Romano on 9/16/14.
// Copyright (c) 2014 Haneke. All rights reserved.
//
import Foundation
extension HanekeGlobals {
// It'd be better to define this in the DiskFetcher class but Swift doesn't allow to declare an enum in a generic type
public struct DiskFetcher {
public enum ErrorCode : Int {
case InvalidData = -500
}
}
}
public class DiskFetcher<T : DataConvertible> : Fetcher<T> {
let path : String
var cancelled = false
public init(path : String) {
self.path = path
let key = path
super.init(key: key)
}
// MARK: Fetcher
public override func fetch(failure fail : ((NSError?) -> ()), success succeed : (T.Result) -> ()) {
self.cancelled = false
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { [weak self] in
if let strongSelf = self {
strongSelf.privateFetch(failure: fail, success: succeed)
}
})
}
public override func cancelFetch() {
self.cancelled = true
}
// MARK: Private
private func privateFetch(failure fail : ((NSError?) -> ()), success succeed : (T.Result) -> ()) {
if self.cancelled {
return
}
var error: NSError?
let data = NSData(contentsOfFile: self.path, options: NSDataReadingOptions.allZeros, error: &error)
if data == nil {
dispatch_async(dispatch_get_main_queue()) {
fail(error)
}
return
}
if self.cancelled {
return
}
let value : T.Result? = T.convertFromData(data!)
if value == nil {
let localizedFormat = NSLocalizedString("Failed to convert value from data at path %@", comment: "Error description")
let description = String(format:localizedFormat, self.path)
let error = errorWithCode(HanekeGlobals.DiskFetcher.ErrorCode.InvalidData.rawValue, description: description)
dispatch_async(dispatch_get_main_queue()) {
fail(error)
}
return
}
dispatch_async(dispatch_get_main_queue(), {
if self.cancelled {
return
}
succeed(value!)
})
}
}
| mit | 39ffaf9aadc1de2087a9a9237bee5f46 | 26.674157 | 129 | 0.548112 | 4.745665 | false | false | false | false |
tlax/GaussSquad | GaussSquad/View/Scanner/VScannerCropper.swift | 1 | 18479 | import UIKit
class VScannerCropper:UIView
{
weak var thumbTopLeft:VScannerCropperThumb!
weak var thumbTopRight:VScannerCropperThumb!
weak var thumbBottomLeft:VScannerCropperThumb!
weak var thumbBottomRight:VScannerCropperThumb!
private weak var viewMover:VScannerCropperMover!
private weak var controller:CScanner!
private weak var draggingThumb:VScannerCropperThumb?
private weak var draggingMover:VScannerCropperMover?
private let thumbSize_2:CGFloat
private let kMinMargin:CGFloat = 25
private let kThumbSize:CGFloat = 60
init(controller:CScanner)
{
thumbSize_2 = kThumbSize / 2.0
super.init(frame:CGRect.zero)
clipsToBounds = true
backgroundColor = UIColor.clear
translatesAutoresizingMaskIntoConstraints = false
self.controller = controller
let thumbTopLeft:VScannerCropperThumb = VScannerCropperThumb.topLeft()
self.thumbTopLeft = thumbTopLeft
let thumbTopRight:VScannerCropperThumb = VScannerCropperThumb.topRight()
self.thumbTopRight = thumbTopRight
let thumbBottomLeft:VScannerCropperThumb = VScannerCropperThumb.bottomLeft()
self.thumbBottomLeft = thumbBottomLeft
let thumbBottomRight:VScannerCropperThumb = VScannerCropperThumb.bottomRight()
self.thumbBottomRight = thumbBottomRight
let viewMover:VScannerCropperMover = VScannerCropperMover()
self.viewMover = viewMover
addSubview(viewMover)
addSubview(thumbTopLeft)
addSubview(thumbTopRight)
addSubview(thumbBottomLeft)
addSubview(thumbBottomRight)
thumbTopLeft.initConstraints(size:kThumbSize)
thumbTopRight.initConstraints(size:kThumbSize)
thumbBottomLeft.initConstraints(size:kThumbSize)
thumbBottomRight.initConstraints(size:kThumbSize)
}
required init?(coder:NSCoder)
{
return nil
}
override func touchesBegan(_ touches:Set<UITouch>, with event:UIEvent?)
{
if draggingThumb == nil
{
guard
let touch:UITouch = touches.first
else
{
return
}
if let draggingMover:VScannerCropperMover = touch.view as? VScannerCropperMover
{
self.draggingMover = draggingMover
let point:CGPoint = touch.location(in:self)
let pointX:CGFloat = point.x
let pointY:CGFloat = point.y
let posTop:CGFloat = thumbTopLeft.positionY
let posBottom:CGFloat = thumbBottomLeft.positionY
let posLeft:CGFloat = thumbTopLeft.positionX
let posRight:CGFloat = thumbTopRight.positionX
let deltaTop:CGFloat = pointY - posTop
let deltaBottom:CGFloat = posBottom - pointY
let deltaLeft:CGFloat = pointX - posLeft
let deltaRight:CGFloat = posRight - pointX
draggingMover.start(
deltaTop:deltaTop,
deltaBottom:deltaBottom,
deltaLeft:deltaLeft,
deltaRight:deltaRight)
}
else if let draggingThumb:VScannerCropperThumb = touch.view as? VScannerCropperThumb
{
bringSubview(toFront:draggingThumb)
draggingThumb.state(selected:true)
self.draggingThumb = draggingThumb
}
}
}
override func touchesMoved(_ touches:Set<UITouch>, with event:UIEvent?)
{
guard
let touch:UITouch = touches.first
else
{
return
}
let point:CGPoint = touch.location(in:self)
if let _:VScannerCropperMover = self.draggingMover
{
movingMover(point:point)
}
else if let draggingThumb:VScannerCropperThumb = self.draggingThumb
{
switch draggingThumb.location
{
case VScannerCropperThumb.Location.topLeft:
movingTopLeft(point:point)
break
case VScannerCropperThumb.Location.topRight:
movingTopRight(point:point)
break
case VScannerCropperThumb.Location.bottomLeft:
movingBottomLeft(point:point)
break
case VScannerCropperThumb.Location.bottomRight:
movingBottomRight(point:point)
break
}
}
}
override func touchesCancelled(_ touches:Set<UITouch>, with event:UIEvent?)
{
draggingEnded()
}
override func touchesEnded(_ touches:Set<UITouch>, with event:UIEvent?)
{
draggingEnded()
}
//MARK: private
private func draggingEnded()
{
viewMover.clear()
draggingThumb?.state(selected:false)
draggingThumb = nil
draggingMover = nil
}
private func movingMover(point:CGPoint)
{
guard
let deltaTop:CGFloat = viewMover.deltaTop,
let deltaBottom:CGFloat = viewMover.deltaBottom,
let deltaLeft:CGFloat = viewMover.deltaLeft,
let deltaRight:CGFloat = viewMover.deltaRight
else
{
return
}
let newPointX:CGFloat = point.x
let newPointY:CGFloat = point.y
let minTop:CGFloat = thumbTopLeft.originalY
let maxBottom:CGFloat = thumbBottomLeft.originalY
let minLeft:CGFloat = thumbTopLeft.originalX
let maxRight:CGFloat = thumbTopRight.originalX
var newTop:CGFloat = newPointY - deltaTop
var newBottom:CGFloat = newPointY + deltaBottom
var newLeft:CGFloat = newPointX - deltaLeft
var newRight:CGFloat = newPointX + deltaRight
if newTop < minTop
{
let delta:CGFloat = minTop - newTop
newTop = minTop
newBottom += delta
}
else if newBottom > maxBottom
{
let delta:CGFloat = newBottom - maxBottom
newBottom = maxBottom
newTop -= delta
}
if newLeft < minLeft
{
let delta:CGFloat = minLeft - newLeft
newLeft = minLeft
newRight += delta
}
else if newRight > maxRight
{
let delta:CGFloat = newRight - maxRight
newRight = maxRight
newLeft -= delta
}
thumbTopLeft.position(
positionX:newLeft,
positionY:newTop)
thumbTopRight.position(
positionX:newRight,
positionY:newTop)
thumbBottomLeft.position(
positionX:newLeft,
positionY:newBottom)
thumbBottomRight.position(
positionX:newRight,
positionY:newBottom)
}
private func movingTopLeft(point:CGPoint)
{
var pointX:CGFloat = point.x
var pointY:CGFloat = point.y
let originalX:CGFloat = thumbTopLeft.originalX
let originalY:CGFloat = thumbTopLeft.originalY
let rightX:CGFloat = thumbTopRight.positionX
let bottomY:CGFloat = thumbBottomLeft.positionY
if pointX < originalX
{
pointX = originalX
}
if pointY < originalY
{
pointY = originalY
}
var deltaX:CGFloat = rightX - pointX
var deltaY:CGFloat = bottomY - pointY
if deltaX < kMinMargin
{
deltaX = kMinMargin
}
if deltaY < kMinMargin
{
deltaY = kMinMargin
}
pointX = rightX - deltaX
pointY = bottomY - deltaY
thumbTopLeft.position(
positionX:pointX,
positionY:pointY)
thumbTopRight.position(
positionX:rightX,
positionY:pointY)
thumbBottomLeft.position(
positionX:pointX,
positionY:bottomY)
}
private func movingTopRight(point:CGPoint)
{
var pointX:CGFloat = point.x
var pointY:CGFloat = point.y
let originalX:CGFloat = thumbTopRight.originalX
let originalY:CGFloat = thumbTopRight.originalY
let leftX:CGFloat = thumbTopLeft.positionX
let bottomY:CGFloat = thumbBottomRight.positionY
if pointX > originalX
{
pointX = originalX
}
if pointY < originalY
{
pointY = originalY
}
var deltaX:CGFloat = pointX - leftX
var deltaY:CGFloat = bottomY - pointY
if deltaX < kMinMargin
{
deltaX = kMinMargin
}
if deltaY < kMinMargin
{
deltaY = kMinMargin
}
pointX = leftX + deltaX
pointY = bottomY - deltaY
thumbTopRight.position(
positionX:pointX,
positionY:pointY)
thumbTopLeft.position(
positionX:leftX,
positionY:pointY)
thumbBottomRight.position(
positionX:pointX,
positionY:bottomY)
}
private func movingBottomLeft(point:CGPoint)
{
var pointX:CGFloat = point.x
var pointY:CGFloat = point.y
let originalX:CGFloat = thumbBottomLeft.originalX
let originalY:CGFloat = thumbBottomLeft.originalY
let rightX:CGFloat = thumbBottomRight.positionX
let topY:CGFloat = thumbTopLeft.positionY
if pointX < originalX
{
pointX = originalX
}
if pointY > originalY
{
pointY = originalY
}
var deltaX:CGFloat = rightX - pointX
var deltaY:CGFloat = pointY - topY
if deltaX < kMinMargin
{
deltaX = kMinMargin
}
if deltaY < kMinMargin
{
deltaY = kMinMargin
}
pointX = rightX - deltaX
pointY = topY + deltaY
thumbBottomLeft.position(
positionX:pointX,
positionY:pointY)
thumbBottomRight.position(
positionX:rightX,
positionY:pointY)
thumbTopLeft.position(
positionX:pointX,
positionY:topY)
}
private func movingBottomRight(point:CGPoint)
{
var pointX:CGFloat = point.x
var pointY:CGFloat = point.y
let originalX:CGFloat = thumbBottomRight.originalX
let originalY:CGFloat = thumbBottomRight.originalY
let leftX:CGFloat = thumbBottomLeft.positionX
let topY:CGFloat = thumbTopRight.positionY
if pointX > originalX
{
pointX = originalX
}
if pointY > originalY
{
pointY = originalY
}
var deltaX:CGFloat = pointX - leftX
var deltaY:CGFloat = pointY - topY
if deltaX < kMinMargin
{
deltaX = kMinMargin
}
if deltaY < kMinMargin
{
deltaY = kMinMargin
}
pointX = leftX + deltaX
pointY = topY + deltaY
thumbBottomRight.position(
positionX:pointX,
positionY:pointY)
thumbBottomLeft.position(
positionX:leftX,
positionY:pointY)
thumbTopRight.position(
positionX:pointX,
positionY:topY)
}
//MARK: public
private func createShades()
{
let shadeTop:VScannerCropperShade = VScannerCropperShade.borderBottom()
let shadeBottom:VScannerCropperShade = VScannerCropperShade.borderTop()
let shadeLeft:VScannerCropperShade = VScannerCropperShade.borderRight()
let shadeRight:VScannerCropperShade = VScannerCropperShade.borderLeft()
let shadeCornerTopLeft:VScannerCropperShade = VScannerCropperShade.noBorder()
let shadeCornerTopRight:VScannerCropperShade = VScannerCropperShade.noBorder()
let shadeCornerBottomLeft:VScannerCropperShade = VScannerCropperShade.noBorder()
let shadeCornerBottomRight:VScannerCropperShade = VScannerCropperShade.noBorder()
insertSubview(shadeTop, belowSubview:viewMover)
insertSubview(shadeBottom, belowSubview:viewMover)
insertSubview(shadeLeft, belowSubview:viewMover)
insertSubview(shadeRight, belowSubview:viewMover)
insertSubview(shadeCornerTopLeft, belowSubview:viewMover)
insertSubview(shadeCornerTopRight, belowSubview:viewMover)
insertSubview(shadeCornerBottomLeft, belowSubview:viewMover)
insertSubview(shadeCornerBottomRight, belowSubview:viewMover)
NSLayoutConstraint.topToTop(
view:shadeTop,
toView:self)
NSLayoutConstraint.bottomToTop(
view:shadeTop,
toView:thumbTopLeft,
constant:thumbSize_2)
NSLayoutConstraint.leftToLeft(
view:shadeTop,
toView:thumbTopLeft,
constant:thumbSize_2)
NSLayoutConstraint.rightToRight(
view:shadeTop,
toView:thumbTopRight,
constant:-thumbSize_2)
NSLayoutConstraint.topToBottom(
view:shadeBottom,
toView:thumbBottomLeft,
constant:-thumbSize_2)
NSLayoutConstraint.bottomToBottom(
view:shadeBottom,
toView:self)
NSLayoutConstraint.leftToLeft(
view:shadeBottom,
toView:thumbBottomLeft,
constant:thumbSize_2)
NSLayoutConstraint.rightToRight(
view:shadeBottom,
toView:thumbBottomRight,
constant:-thumbSize_2)
NSLayoutConstraint.topToTop(
view:shadeLeft,
toView:thumbTopLeft,
constant:thumbSize_2)
NSLayoutConstraint.bottomToBottom(
view:shadeLeft,
toView:thumbBottomLeft,
constant:-thumbSize_2)
NSLayoutConstraint.leftToLeft(
view:shadeLeft,
toView:self)
NSLayoutConstraint.rightToLeft(
view:shadeLeft,
toView:thumbTopLeft,
constant:thumbSize_2)
NSLayoutConstraint.topToTop(
view:shadeRight,
toView:thumbTopRight,
constant:thumbSize_2)
NSLayoutConstraint.bottomToBottom(
view:shadeRight,
toView:thumbBottomRight,
constant:-thumbSize_2)
NSLayoutConstraint.leftToRight(
view:shadeRight,
toView:thumbTopRight,
constant:-thumbSize_2)
NSLayoutConstraint.rightToRight(
view:shadeRight,
toView:self)
NSLayoutConstraint.topToTop(
view:shadeCornerTopLeft,
toView:self)
NSLayoutConstraint.bottomToTop(
view:shadeCornerTopLeft,
toView:shadeLeft)
NSLayoutConstraint.leftToLeft(
view:shadeCornerTopLeft,
toView:self)
NSLayoutConstraint.rightToLeft(
view:shadeCornerTopLeft,
toView:shadeTop)
NSLayoutConstraint.topToTop(
view:shadeCornerTopRight,
toView:self)
NSLayoutConstraint.bottomToTop(
view:shadeCornerTopRight,
toView:shadeRight)
NSLayoutConstraint.leftToRight(
view:shadeCornerTopRight,
toView:shadeTop)
NSLayoutConstraint.rightToRight(
view:shadeCornerTopRight,
toView:self)
NSLayoutConstraint.topToBottom(
view:shadeCornerBottomLeft,
toView:shadeLeft)
NSLayoutConstraint.bottomToBottom(
view:shadeCornerBottomLeft,
toView:self)
NSLayoutConstraint.leftToLeft(
view:shadeCornerBottomLeft,
toView:self)
NSLayoutConstraint.rightToLeft(
view:shadeCornerBottomLeft,
toView:shadeBottom)
NSLayoutConstraint.topToBottom(
view:shadeCornerBottomRight,
toView:shadeRight)
NSLayoutConstraint.bottomToBottom(
view:shadeCornerBottomRight,
toView:self)
NSLayoutConstraint.leftToRight(
view:shadeCornerBottomRight,
toView:shadeBottom)
NSLayoutConstraint.rightToRight(
view:shadeCornerBottomRight,
toView:self)
NSLayoutConstraint.topToBottom(
view:viewMover,
toView:shadeTop)
NSLayoutConstraint.bottomToTop(
view:viewMover,
toView:shadeBottom)
NSLayoutConstraint.leftToRight(
view:viewMover,
toView:shadeLeft)
NSLayoutConstraint.rightToLeft(
view:viewMover,
toView:shadeRight)
}
private func positionThumbs()
{
let width:CGFloat = bounds.maxX
let height:CGFloat = bounds.maxY
let width_margin:CGFloat = width - kMinMargin
let height_margin:CGFloat = height - kMinMargin
thumbTopLeft.position(
positionX:kMinMargin,
positionY:kMinMargin)
thumbTopRight.position(
positionX:width_margin,
positionY:kMinMargin)
thumbBottomLeft.position(
positionX:kMinMargin,
positionY:height_margin)
thumbBottomRight.position(
positionX:width_margin,
positionY:height_margin)
}
//MARK: public
func viewAppeared()
{
positionThumbs()
createShades()
}
func resetThumbs()
{
thumbTopLeft.reset()
thumbTopRight.reset()
thumbBottomLeft.reset()
thumbBottomRight.reset()
}
}
| mit | d83665a290f3fbfb4dafc28d8a4394b0 | 29.393092 | 96 | 0.57357 | 5.48013 | false | false | false | false |
EvsenevDev/SmartReceiptsiOS | SmartReceipts/Common/UI/Eureka Custom Cells/HorizontalPickerCell/HorizontalPickerCell.swift | 2 | 2784 | //
// HorizontalPicker.swift
// SmartReceipts
//
// Created by Bogdan Evsenev on 08/03/2018.
// Copyright ยฉ 2018 Will Baumann. All rights reserved.
//
import Eureka
public class HorizontalPickerCell: Cell<Int>, CellType, UICollectionViewDataSource, UICollectionViewDelegate, UICollectionViewDelegateFlowLayout {
@IBOutlet weak var collectionView: UICollectionView!
fileprivate let cellName = "HorizontalPickerItemCell"
public override func setup() {
super.setup()
height = { 56 }
let cellNib = UINib(nibName: cellName, bundle: nil)
collectionView.register(cellNib, forCellWithReuseIdentifier: cellName)
collectionView.delegate = self
collectionView.dataSource = self
}
public override func update() {
super.update()
}
fileprivate func row() -> HorizontalPickerRow {
return (row as! HorizontalPickerRow)
}
// MARK: - UICollectionViewDelegate
public func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
row().value = indexPath.row
UIImpactFeedbackGenerator().impactOccurred()
}
// MARK: - UICollectionViewDataSource
public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: cellName, for: indexPath)
if let itemCell = cell as? HorizontalPickerItemCell {
itemCell.configureFor(any: row().options[indexPath.row])
}
return cell
}
public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return row().options.count
}
// MARK: - UICollectionViewDelegateFlowLayout
public func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
guard let cell = Bundle.main.loadNibNamed(cellName, owner: nil, options: nil)?.first as? HorizontalPickerItemCell else {
return CGSize(width: collectionView.bounds.height, height: collectionView.bounds.height)
}
let option = row().options[indexPath.row]
return CGSize(width: cell.widthFor(any: option), height: collectionView.bounds.height)
}
}
public final class HorizontalPickerRow: Row<HorizontalPickerCell>, RowType {
var options: [Any] = [] {
didSet {
cell.collectionView.reloadData()
}
}
public required init(tag: String?) {
super.init(tag: tag)
cellProvider = CellProvider<HorizontalPickerCell>(nibName: "HorizontalPickerCell")
}
}
| agpl-3.0 | daf27949951fda91e6b0604d2185fd0b | 34.227848 | 167 | 0.685591 | 5.403883 | false | false | false | false |
hulinSun/Swift-collection | Swift 3.playground/Contents.swift | 1 | 2108 | import UIKit
import PlaygroundSupport
var i = 0
i += 1
i -= 1
for i in 1...10 {
print(i)
}
(1...10).forEach {
print($0)
}
func gcd(a: Int, b: Int) -> Int {
if (a == b) {
return a
}
var c = a
var d = b
repeat {
if (c > d) {
c = c - d
} else {
d = d - c
}
} while (c != d)
return c
}
gcd(a: 8, b: 12)
class Responder: NSObject {
func tap() {
print("Button pressed")
}
}
let responder = Responder()
let button = UIButton(type: .system)
button.setTitle("Button", for: [])
button.addTarget(responder, action: #selector(Responder.tap), for: .touchUpInside)
button.sizeToFit()
button.center = CGPoint(x: 50, y: 25)
let frame = CGRect(x: 0, y: 0, width: 100, height: 50)
let view = UIView(frame: frame)
view.addSubview(button)
PlaygroundPage.current.liveView = view
class Person: NSObject {
var name: String = ""
init(name: String) {
self.name = name
}
}
let me = Person(name: "Cosmin")
me.value(forKeyPath: #keyPath(Person.name))
let file = Bundle.main().pathForResource("tutorials", ofType: "json")
let url = URL(fileURLWithPath: file!)
let data = try! Data(contentsOf: url)
let json = try! JSONSerialization.jsonObject(with: data)
print(json)
let r = 3.0
let circumference = 2 * .pi * r
let area = .pi * r * r
let queue = DispatchQueue(label: "Swift 3")
queue.async {
print("Swift 3 queue")
}
class View: UIView {
override func draw(_ rect: CGRect) {
guard let context = UIGraphicsGetCurrentContext() else {
return
}
#colorLiteral(red: 1.0, green: 1.0, blue: 1.0, alpha: 1.0)
let blue = UIColor.blue().cgColor
context.setFillColor(blue)
let red = UIColor.red().cgColor
context.setStrokeColor(red)
context.setLineWidth(10)
context.addRect(frame)
context.drawPath(using: .fillStroke)
}
}
let aView = View(frame: frame)
for i in (1...10).reversed() {
print(i)
}
var array = [1, 5, 3, 2, 4]
for (index, value) in array.enumerated() {
print("\(index + 1) \(value)")
}
let sortedArray = array.sorted()
print(sortedArray)
array.sort()
print(array)
| apache-2.0 | f5a60b7a4c0f733f33a6042fb564a83b | 15.598425 | 82 | 0.624288 | 3.16042 | false | false | false | false |
quire-io/SwiftyChrono | Sources/Parsers/EN/ENCasualTimeParser.swift | 1 | 1335 | //
// ENCasualTimeParser.swift
// SwiftyChrono
//
// Created by Jerry Chen on 1/18/17.
// Copyright ยฉ 2017 Potix. All rights reserved.
//
import Foundation
private let PATTERN = "(\\W|^)((this)?\\s*(morning|afternoon|evening|noon))"
private let timeMatch = 4
public class ENCasualTimeParser: Parser {
override var pattern: String { return PATTERN }
override public func extract(text: String, ref: Date, match: NSTextCheckingResult, opt: [OptionType: Int]) -> ParsedResult? {
let (matchText, index) = matchTextAndIndex(from: text, andMatchResult: match)
var result = ParsedResult(ref: ref, index: index, text: matchText)
if match.isNotEmpty(atRangeIndex: timeMatch) {
let time = match.string(from: text, atRangeIndex: timeMatch)
switch time {
case "afternoon":
result.start.imply(.hour, to: opt[.afternoon] ?? 15)
case "evening":
result.start.imply(.hour, to: opt[.evening] ?? 18)
case "morning":
result.start.imply(.hour, to: opt[.morning] ?? 6)
case "noon":
result.start.imply(.hour, to: opt[.noon] ?? 12)
default: break
}
}
result.tags[.enCasualTimeParser] = true
return result
}
}
| mit | c7badafc59d0689d273ede3ff96493fa | 33.205128 | 129 | 0.589955 | 4.030211 | false | false | false | false |
Eonil/Monolith.Swift | Text/Sources/EDXC/Entity.swift | 2 | 2661 | //
// Entity.swift
// EDXC
//
// Created by Hoon H. on 10/14/14.
// Copyright (c) 2014 Eonil. All rights reserved.
//
import Foundation
struct Entity: Printable {
let name:String
let type:String
let parameters:[Parameter]
enum Parameter {
case Expression(String)
case Subentity(Entity)
var expression:String? {
get {
switch self {
case let Expression(state): return state
default: return nil
}
}
}
var subentity:Entity? {
get {
switch self {
case let Subentity(state): return state
default: return nil
}
}
}
}
}
extension Entity {
var description:String {
get {
let a1 = ListConverter.print(self)
return a1.description
}
}
func listify() -> Atom {
return ListConverter.print(self)
}
}
extension Atom {
func tryEntitifying() -> Entity? {
return Entity.ListConverter.scan(self)
}
}
private extension Entity {
struct ListConverter {
static func print(v:Entity) -> Atom {
func parameterToAtom(p:Entity.Parameter) -> Atom {
switch p {
case let Entity.Parameter.Expression(state): return Atom.Value(expression: state)
case let Entity.Parameter.Subentity(state): return self.print(state)
}
}
let as1 = [Atom.Value(expression: v.name), Atom.Value(expression: v.type)] + v.parameters.map(parameterToAtom)
let a1 = Atom.List(atoms: as1)
return a1
}
static func scan(v:Atom) -> Entity? {
func tryEntitification(as1:[Atom]) -> Entity? {
func symbolify(a:Atom) -> String? {
switch a {
case let Atom.Value(state): return state
case let Atom.List(state): return nil
}
}
func parameteriseAll(as1:ArraySlice<Atom>) -> [Parameter]? {
func parameterise(a:Atom) -> Parameter? {
switch a {
case let Atom.Value(state): return Parameter.Expression(state)
case let Atom.List(state):
if let e1 = ListConverter.scan(a) {
return Parameter.Subentity(e1)
} else {
return nil
}
}
}
var ps1 = [] as [Parameter]
for a1 in as1 {
if let p1 = parameterise(a1) {
ps1.append(p1)
} else {
return nil
}
}
return ps1
}
if as1.count < 3 {
return nil
}
let name1 = symbolify(as1[0])
let type1 = symbolify(as1[1])
let params1 = parameteriseAll(as1[2..<as1.count])
if name1 != nil && type1 != nil && params1 != nil {
return Entity(name: name1!, type: type1!, parameters: params1!)
}
return nil
}
switch v {
case let Atom.Value(state): return nil
case let Atom.List(state): return tryEntitification(state)
}
}
}
}
| mit | de2779afffb1a3de576d41446adcb79d | 19.159091 | 113 | 0.613303 | 2.905022 | false | false | false | false |
raymondshadow/SwiftDemo | SwiftApp/StudyNote/StudyNote/LayerCorner/SNLayerSummaryViewController.swift | 1 | 1633 | //
// SNLayerSummaryViewController.swift
// StudyNote
//
// Created by wuyp on 2019/7/5.
// Copyright ยฉ 2019 Raymond. All rights reserved.
//
import UIKit
import Common
class SNLayerSummaryViewController: UIViewController {
@objc private dynamic var hybCornerCliped: SNhybCornerClipedView = {
let view = SNhybCornerClipedView(frame: CGRect(x: 0, y: 100, width: kScreenWidth, height: 50))
view.layer.shadowOpacity = 1
view.layer.shadowColor = UIColor.red.cgColor
view.layer.shadowRadius = 8
view.layer.shadowOffset = CGSize(width: 5, height: 5)
return view
}()
@objc override dynamic func viewDidLoad() {
super.viewDidLoad()
addHybCornerClipedView()
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// hybCornerCliped.y = 120
let maskLayer = CAShapeLayer()
let path = UIBezierPath(roundedRect: hybCornerCliped.bounds, byRoundingCorners: [.topRight, .topLeft], cornerRadii: CGSize(width: 20, height: 20))
maskLayer.path = path.cgPath
maskLayer.strokeColor = UIColor.yellow.cgColor
maskLayer.fillColor = UIColor.purple.cgColor
maskLayer.lineWidth = 1
path.stroke()
hybCornerCliped.layer.masksToBounds = true
hybCornerCliped.layer.mask = maskLayer
}
}
extension SNLayerSummaryViewController {
@objc private dynamic func addHybCornerClipedView() {
self.view.addSubview(hybCornerCliped)
// self.view.backgroundColor = .white
// hybCornerCliped.hyb_add(.topRight, cornerRadius: 20)
}
}
| apache-2.0 | 2c758a4c7bb2336ba65f40b029e3d5b4 | 32.306122 | 154 | 0.675858 | 4.173913 | false | false | false | false |
Nirma/UIDeviceComplete | Tests/UIDeviceExtensionsTests.swift | 1 | 2244 | //
// UIDeviceExtensionsTests .swift
//
// Copyright (c) 2017-2019 Nicholas Maccharoli
//
// 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.
@testable import UIDeviceComplete
import XCTest
class UIDeviceExtensionsTests: XCTestCase {
let DeviceExtensions = UIDeviceComplete(UIDevice())
func testDeviceExtensionsDeviceFamily() {
XCTAssertNotEqual(.unknown, DeviceExtensions.deviceFamily, "DeviceExtensions - .deviceFamily is failing")
}
func testDeviceExtensionsDeviceModel() {
XCTAssertNotEqual(.unknown, DeviceExtensions.deviceModel, "DeviceExtensions - .deviceModel is failing")
}
func testDeviceExtensionsIsIphone() {
let deviceFamily = DeviceFamily(rawValue: "iPhone")
XCTAssert(deviceFamily == .iPhone, "DeviceExtensions - .isIphone is failing")
}
func testDeviceExtensionsIsIpad() {
let deviceFamily = DeviceFamily(rawValue: "iPad")
XCTAssert(deviceFamily == .iPad, "DeviceExtensions - .isIpad is failing")
}
func testDeviceExtensionsIsIpod() {
let deviceFamily = DeviceFamily(rawValue: "iPod")
XCTAssert(deviceFamily == .iPod, "DeviceExtensions - .isIpod is failing")
}
}
| mit | 4e34ca3a1da830d9f08c0cb13fa875e2 | 40.555556 | 113 | 0.732175 | 4.734177 | false | true | false | false |
codefellows/sea-b19-ios | Projects/iBeacons-Workshop/iBeacons Workshop.playground/section-1.swift | 1 | 480 | // Playground - noun: a place where people can play
import UIKit
import CoreLocation
import CoreBluetooth
let uuidString = "5E145790-AC19-463A-A7D7-5EF29CB2A571"
let myUUID = NSUUID(UUIDString: uuidString)
let myIdentifier = "com.codefellows.beacons.the_east_room"
var region = CLBeaconRegion(proximityUUID: myUUID, identifier: myIdentifier)
let beaconData = region.peripheralDataWithMeasuredPower(nil)
let peripheralManager = CBPeripheralManager(delegate: nil, queue: nil) | gpl-2.0 | 5465ac73759382eccd7f433d74a57588 | 27.294118 | 76 | 0.808333 | 3.664122 | false | false | false | false |
AliceAponasko/LJReader | LJReader/Controllers/AddAuthorViewController.swift | 1 | 3947 | //
// AddAuthorViewController.swift
// LJReader
//
// Created by Alice Aponasko on 2/29/16.
// Copyright ยฉ 2016 aliceaponasko. All rights reserved.
//
import UIKit
class AddAuthorViewController: UIViewController {
@IBOutlet weak var addAuthorTextField: UITextField!
// MARK: Properties
var loadingOverlayView: UIView!
var loadingActivityIndicator: UIActivityIndicatorView!
let ljClient = LJClient.sharedInstance
let defaults = NSUserDefaults.standardUserDefaults()
override func viewDidLoad() {
super.viewDidLoad()
addAuthorTextField.becomeFirstResponder()
}
// MARK: Actions
@IBAction func addAuthorButtonTapped(sender: AnyObject) {
guard let author = addAuthorTextField.text else {
return
}
if author.isEmpty {
return
}
showLoadingScreen()
addAuthorTextField.resignFirstResponder()
ljClient.get(author, parameters: nil) {
[unowned self] success, _, _ in
if success {
self.defaults.addAuthor(author)
self.showSuccessAlertWithTitle()
} else {
self.showFailureAlertWithTitle()
}
}
}
// MARK: Loading
func showLoadingScreen() {
loadingOverlayView = UIView(frame: view.frame)
loadingOverlayView.backgroundColor = UIColor(white: 0, alpha: 0.2)
loadingActivityIndicator = UIActivityIndicatorView(
activityIndicatorStyle: .WhiteLarge)
loadingActivityIndicator.center = view.center
loadingActivityIndicator.startAnimating()
view.addSubview(loadingOverlayView)
view.addSubview(loadingActivityIndicator)
view.userInteractionEnabled = false
}
func hideLoadingScreen() {
UIView.animateWithDuration(0.2, animations: { () -> Void in
self.loadingOverlayView?.alpha = 0
self.loadingActivityIndicator?.alpha = 0
}) { isFinished in
self.loadingOverlayView?.removeFromSuperview()
self.loadingActivityIndicator?.removeFromSuperview()
self.loadingActivityIndicator = nil
self.loadingOverlayView = nil
}
view.userInteractionEnabled = true
}
// MARK: Alert
func showSuccessAlertWithTitle() {
let alertVC = UIAlertController(
title: "YAY",
message: "Author was added to your reading list. Enjoy! ๐",
preferredStyle: UIAlertControllerStyle.Alert)
alertVC.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: {
[unowned self] action in
self.navigationController?.popViewControllerAnimated(true)
}))
presentViewController(
alertVC,
animated: true,
completion: nil)
hideLoadingScreen()
}
func showFailureAlertWithTitle() {
let alertVC = UIAlertController(
title: "Hmmm...",
message: "Cannot find this author ๐\nCheck the spelling and try again.",
preferredStyle: UIAlertControllerStyle.Alert)
alertVC.addAction(UIAlertAction(
title: "OK",
style: .Default,
handler: {
[unowned self] action in
self.addAuthorTextField.becomeFirstResponder()
}))
presentViewController(
alertVC,
animated: true,
completion: nil)
hideLoadingScreen()
}
}
// MARK: - UITextFieldDelegate
extension AddAuthorViewController: UITextFieldDelegate {
func textFieldShouldReturn(
textField: UITextField) -> Bool {
addAuthorButtonTapped(self)
return true
}
}
| mit | 61964be37f2a0b503061dba60bd37007 | 26.552448 | 84 | 0.592386 | 5.693642 | false | false | false | false |
nghiaphunguyen/NKit | NKit/Source/Diff/ExtendedPatch+Apply.swift | 1 | 2191 |
// TODO: Fix ugly copy paste :/
typealias IntMax = Int64
public extension RangeReplaceableCollection where Self.Iterator.Element: Equatable {
public func apply(_ patch: [ExtendedPatch<Iterator.Element>]) -> Self {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.remove(at: target)
case let .move(from, to):
let fromIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(from)))
let toIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(to)))
let element = mutableSelf.remove(at: fromIndex)
mutableSelf.insert(element, at: toIndex)
}
}
return mutableSelf
}
}
public extension String {
public func apply(_ patch: [ExtendedPatch<String.Iterator.Element>]) -> String {
var mutableSelf = self
for change in patch {
switch change {
case let .insertion(i, element):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.insert(element, at: target)
case let .deletion(i):
let target = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(i)))
mutableSelf.remove(at: target)
case let .move(from, to):
let fromIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(from)))
let toIndex = mutableSelf.index(mutableSelf.startIndex, offsetBy: IndexDistance(IntMax(to)))
let element = mutableSelf.remove(at: fromIndex)
mutableSelf.insert(element, at: toIndex)
}
}
return mutableSelf
}
}
| mit | d0b1b36ef21cf1ab49dc7857c6f31d94 | 39.574074 | 112 | 0.616613 | 5.002283 | false | false | false | false |
niunaruto/DeDaoAppSwift | testSwift/Pods/RxCocoa/RxCocoa/iOS/UIControl+Rx.swift | 19 | 3417 | //
// UIControl+Rx.swift
// RxCocoa
//
// Created by Daniel Tartaglia on 5/23/15.
// Copyright ยฉ 2015 Krunoslav Zaher. All rights reserved.
//
#if os(iOS) || os(tvOS)
import RxSwift
import UIKit
extension Reactive where Base: UIControl {
/// Bindable sink for `enabled` property.
public var isEnabled: Binder<Bool> {
return Binder(self.base) { control, value in
control.isEnabled = value
}
}
/// Bindable sink for `selected` property.
public var isSelected: Binder<Bool> {
return Binder(self.base) { control, selected in
control.isSelected = selected
}
}
/// Reactive wrapper for target action pattern.
///
/// - parameter controlEvents: Filter for observed event types.
public func controlEvent(_ controlEvents: UIControl.Event) -> ControlEvent<()> {
let source: Observable<Void> = Observable.create { [weak control = self.base] observer in
MainScheduler.ensureRunningOnMainThread()
guard let control = control else {
observer.on(.completed)
return Disposables.create()
}
let controlTarget = ControlTarget(control: control, controlEvents: controlEvents) { _ in
observer.on(.next(()))
}
return Disposables.create(with: controlTarget.dispose)
}
.takeUntil(deallocated)
return ControlEvent(events: source)
}
/// Creates a `ControlProperty` that is triggered by target/action pattern value updates.
///
/// - parameter controlEvents: Events that trigger value update sequence elements.
/// - parameter getter: Property value getter.
/// - parameter setter: Property value setter.
public func controlProperty<T>(
editingEvents: UIControl.Event,
getter: @escaping (Base) -> T,
setter: @escaping (Base, T) -> Void
) -> ControlProperty<T> {
let source: Observable<T> = Observable.create { [weak weakControl = base] observer in
guard let control = weakControl else {
observer.on(.completed)
return Disposables.create()
}
observer.on(.next(getter(control)))
let controlTarget = ControlTarget(control: control, controlEvents: editingEvents) { _ in
if let control = weakControl {
observer.on(.next(getter(control)))
}
}
return Disposables.create(with: controlTarget.dispose)
}
.takeUntil(deallocated)
let bindingObserver = Binder(base, binding: setter)
return ControlProperty<T>(values: source, valueSink: bindingObserver)
}
/// This is a separate method to better communicate to public consumers that
/// an `editingEvent` needs to fire for control property to be updated.
internal func controlPropertyWithDefaultEvents<T>(
editingEvents: UIControl.Event = [.allEditingEvents, .valueChanged],
getter: @escaping (Base) -> T,
setter: @escaping (Base, T) -> Void
) -> ControlProperty<T> {
return controlProperty(
editingEvents: editingEvents,
getter: getter,
setter: setter
)
}
}
#endif
| mit | 338642cc964ea6b20a48c8a40accc0c6 | 32.821782 | 104 | 0.592506 | 5.07578 | false | false | false | false |
sergdort/CleanArchitectureRxSwift | CoreDataPlatform/RxCoreData/NSManagedObjectContext+Rx.swift | 1 | 2958 | import Foundation
import CoreData
import RxSwift
import QueryKit
extension Reactive where Base: NSManagedObjectContext {
/**
Executes a fetch request and returns the fetched objects as an `Observable` array of `NSManagedObjects`.
- parameter fetchRequest: an instance of `NSFetchRequest` to describe the search criteria used to retrieve data from a persistent store
- parameter sectionNameKeyPath: the key path on the fetched objects used to determine the section they belong to; defaults to `nil`
- parameter cacheName: the name of the file used to cache section information; defaults to `nil`
- returns: An `Observable` array of `NSManagedObjects` objects that can be bound to a table view.
*/
func entities<T: NSFetchRequestResult>(fetchRequest: NSFetchRequest<T>,
sectionNameKeyPath: String? = nil,
cacheName: String? = nil) -> Observable<[T]> {
return Observable.create { observer in
let observerAdapter = FetchedResultsControllerEntityObserver(observer: observer, fetchRequest: fetchRequest, managedObjectContext: self.base, sectionNameKeyPath: sectionNameKeyPath, cacheName: cacheName)
return Disposables.create {
observerAdapter.dispose()
}
}
}
func save() -> Observable<Void> {
return Observable.create { observer in
do {
try self.base.save()
observer.onNext(())
} catch {
observer.onError(error)
}
return Disposables.create()
}
}
func delete<T: NSManagedObject>(entity: T) -> Observable<Void> {
return Observable.create { observer in
self.base.delete(entity)
observer.onNext(())
return Disposables.create()
}.flatMapLatest {
self.save()
}
}
func first<T: NSFetchRequestResult>(ofType: T.Type = T.self, with predicate: NSPredicate) -> Observable<T?> {
return Observable.deferred {
let entityName = String(describing: T.self)
let request = NSFetchRequest<T>(entityName: entityName)
request.predicate = predicate
do {
let result = try self.base.fetch(request).first
return Observable.just(result)
} catch {
return Observable.error(error)
}
}
}
func sync<C: CoreDataRepresentable, P>(entity: C,
update: @escaping (P) -> Void) -> Observable<P> where C.CoreDataType == P {
let predicate: NSPredicate = P.primaryAttribute == entity.uid
return first(ofType: P.self, with: predicate)
.flatMap { obj -> Observable<P> in
let object = obj ?? self.base.create()
update(object)
return Observable.just(object)
}
}
}
| mit | 20b021471d7802749739fda5a873104f | 38.44 | 215 | 0.602772 | 5.216931 | false | false | false | false |
AblePear/Peary | Peary/in6_addr.swift | 1 | 718 | import Foundation
import Darwin.POSIX.netinet.`in`
extension in6_addr : CustomStringConvertible, Equatable {
public static func ==(first: in6_addr, second: in6_addr) -> Bool {
return first.__u6_addr.__u6_addr32 == second.__u6_addr.__u6_addr32
}
public init?(_ address: String) {
self.init()
if 1 != inet_pton(AF_INET6, address, &self) {
return nil
}
}
public var description: String {
var copy = self
var buffer = [CChar](repeating: 0, count: Int(INET6_ADDRSTRLEN))
let result = inet_ntop(AF_INET6, ©, &buffer, socklen_t(buffer.count))
assert(result != nil)
return String(cString: &buffer)
}
}
| bsd-2-clause | 2ca10269fd18c309b40e434fc1b2f1cc | 28.916667 | 81 | 0.593315 | 3.663265 | false | false | false | false |
ianyh/Amethyst | Amethyst/Layout/Layouts/WideLayout.swift | 1 | 3944 | //
// WideLayout.swift
// Amethyst
//
// Created by Ian Ynda-Hummel on 12/14/15.
// Copyright ยฉ 2015 Ian Ynda-Hummel. All rights reserved.
//
import Silica
class WideLayout<Window: WindowType>: Layout<Window>, PanedLayout {
override static var layoutName: String { return "Wide" }
override static var layoutKey: String { return "wide" }
enum CodingKeys: String, CodingKey {
case mainPaneCount
case mainPaneRatio
}
private(set) var mainPaneCount: Int = 1
private(set) var mainPaneRatio: CGFloat = 0.5
required init() {
super.init()
}
required init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
self.mainPaneCount = try values.decode(Int.self, forKey: .mainPaneCount)
self.mainPaneRatio = try values.decode(CGFloat.self, forKey: .mainPaneRatio)
super.init()
}
override func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(mainPaneCount, forKey: .mainPaneCount)
try container.encode(mainPaneRatio, forKey: .mainPaneRatio)
}
func recommendMainPaneRawRatio(rawRatio: CGFloat) {
mainPaneRatio = rawRatio
}
func increaseMainPaneCount() {
mainPaneCount += 1
}
func decreaseMainPaneCount() {
mainPaneCount = max(1, mainPaneCount - 1)
}
override func frameAssignments(_ windowSet: WindowSet<Window>, on screen: Screen) -> [FrameAssignmentOperation<Window>]? {
let windows = windowSet.windows
guard !windows.isEmpty else {
return []
}
let secondaryPaneCount = windows.count - mainPaneCount
let hasSecondaryPane = secondaryPaneCount > 0
let screenFrame = screen.adjustedFrame()
let mainPaneWindowHeight = round(screenFrame.height * CGFloat(hasSecondaryPane ? mainPaneRatio : 1))
let secondaryPaneWindowHeight = screenFrame.height - mainPaneWindowHeight
let mainPaneWindowWidth = round(screenFrame.width / CGFloat(mainPaneCount))
let secondaryPaneWindowWidth = hasSecondaryPane ? round(screenFrame.width / CGFloat(secondaryPaneCount)) : 0.0
return windows.reduce([]) { frameAssignments, window -> [FrameAssignmentOperation<Window>] in
var assignments = frameAssignments
var windowFrame = CGRect.zero
let isMain = frameAssignments.count < mainPaneCount
var scaleFactor: CGFloat
if isMain {
scaleFactor = screenFrame.height / mainPaneWindowHeight
windowFrame.origin.x = screenFrame.origin.x + (mainPaneWindowWidth * CGFloat(frameAssignments.count))
windowFrame.origin.y = screenFrame.origin.y
windowFrame.size.width = mainPaneWindowWidth
windowFrame.size.height = mainPaneWindowHeight
} else {
scaleFactor = screenFrame.height / secondaryPaneWindowHeight
windowFrame.origin.x = screenFrame.origin.x + (secondaryPaneWindowWidth * CGFloat(frameAssignments.count - mainPaneCount))
windowFrame.origin.y = screenFrame.origin.y + mainPaneWindowHeight
windowFrame.size.width = secondaryPaneWindowWidth
windowFrame.size.height = secondaryPaneWindowHeight
}
let resizeRules = ResizeRules(isMain: isMain, unconstrainedDimension: .vertical, scaleFactor: scaleFactor)
let frameAssignment = FrameAssignment<Window>(
frame: windowFrame,
window: window,
screenFrame: screenFrame,
resizeRules: resizeRules
)
let operation = FrameAssignmentOperation(frameAssignment: frameAssignment, windowSet: windowSet)
assignments.append(operation)
return assignments
}
}
}
| mit | 8c4dd537222bb48193ddbc58fd16ae35 | 36.913462 | 138 | 0.660664 | 4.727818 | false | false | false | false |
TruckMuncher/TruckMuncher-iOS | TruckMuncher/api/RCategory.swift | 1 | 1133 | //
// RCategory.swift
// TruckMuncher
//
// Created by Josh Ault on 10/27/14.
// Copyright (c) 2014 TruckMuncher. All rights reserved.
//
import UIKit
import Realm
class RCategory: RLMObject {
dynamic var id = ""
dynamic var name = ""
dynamic var notes = ""
dynamic var orderInMenu = 0
dynamic var menuItems = RLMArray(objectClassName: RMenuItem.className())
override init() {
super.init()
}
class func initFromProto(category: [String: AnyObject]) -> RCategory {
let rcategory = RCategory()
rcategory.id = category["id"] as! String
rcategory.name = category["name"] as? String ?? ""
rcategory.notes = category["notes"] as? String ?? ""
rcategory.orderInMenu = category["orderInMenu"] as? Int ?? 0
if let menuItems = category["menuItems"] as? [[String: AnyObject]] {
for menuItem in menuItems {
rcategory.menuItems.addObject(RMenuItem.initFromFullProto(menuItem))
}
}
return rcategory
}
override class func primaryKey() -> String! {
return "id"
}
}
| gpl-2.0 | e12f60baec60e6c8cde9ee2c17a1111c | 27.325 | 84 | 0.606355 | 4.227612 | false | false | false | false |
sharath-cliqz/browser-ios | Client/Cliqz/Foundation/Environment/AppStatus.swift | 2 | 11068 | //
// AppStatus.swift
// Client
//
// Created by Mahmoud Adam on 11/12/15.
// Copyright ยฉ 2015 Cliqz. All rights reserved.
//
import Foundation
class AppStatus {
//MARK constants
let versionDescriptorKey = "VersionDescriptor"
let buildNumberDescriptorKey = "BuildNumberDescriptor"
let dispatchQueue = DispatchQueue.global(qos: DispatchQoS.QoSClass.utility)
//MARK Instance variables
var versionDescriptor: (String, String)?
var lastOpenedDate: Date?
var lastEnvironmentEventDate: Date?
lazy var extensionVersion: String = {
if let path = Bundle.main.path(forResource: "cliqz", ofType: "json", inDirectory: "Extension/build/mobile/search"),
let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path), options: .mappedIfSafe) as Data,
let jsonResult: NSDictionary = try! JSONSerialization.jsonObject(with: jsonData, options: JSONSerialization.ReadingOptions.mutableContainers) as? NSDictionary {
if let extensionVersion : String = jsonResult["EXTENSION_VERSION"] as? String {
return extensionVersion
}
}
return ""
}()
lazy var distVersion: String = {
let versionDescription = self.getVersionDescriptor()
return self.getAppVersion(versionDescription)
}()
lazy var hostVersion: String = {
// Firefox version
if let path = Bundle.main.path(forResource: "Info", ofType: "plist"),
let infoDict = NSDictionary(contentsOfFile: path),
let hostVersion = infoDict["HostVersion"] as? String {
return hostVersion
}
return ""
}()
func isRelease() -> Bool {
#if BETA
return false
#else
return true
#endif
}
func isDebug() -> Bool {
return _isDebugAssertConfiguration()
}
func getAppVersion(_ versionDescriptor: (version: String, buildNumber: String)) -> String {
return "\(versionDescriptor.version.trim()) (\(versionDescriptor.buildNumber))"
}
func batteryLevel() -> Int {
return Int(UIDevice.current.batteryLevel * 100)
}
//MARK: - Singltone
static let sharedInstance = AppStatus()
fileprivate init() {
UIDevice.current.isBatteryMonitoringEnabled = true
}
//MARK:- pulbic interface
internal func appWillFinishLaunching() {
lastOpenedDate = Date()
NetworkReachability.sharedInstance.startMonitoring()
}
internal func appDidFinishLaunching() {
PrivateBrowsing.singleton.startupCheckIfKilledWhileInPBMode()
dispatchQueue.async {
let (version, buildNumber) = self.getVersionDescriptor()
if let (storedVersion, storedBuildNumber) = self.loadStoredVersionDescriptor() {
if version > storedVersion || buildNumber > storedBuildNumber {
// new update
self.logLifeCycleEvent("update")
}
} else {
// new Install
self.logLifeCycleEvent("install")
}
//store current version descriptor
self.updateVersionDescriptor((version, buildNumber))
}
}
internal func appWillEnterForeground() {
SessionState.sessionResumed()
lastOpenedDate = Date()
}
internal func appDidBecomeActive(_ profile: Profile) {
NetworkReachability.sharedInstance.refreshStatus()
logApplicationUsageEvent("Active")
logEnvironmentEventIfNecessary(profile)
}
internal func appDidBecomeResponsive(_ startupType: String) {
let startupTime = Date.milliSecondsSinceDate(lastOpenedDate)
logApplicationUsageEvent("Responsive", startupType: startupType, startupTime: startupTime, openDuration: nil)
}
internal func appWillResignActive() {
let openDuration = Date.milliSecondsSinceDate(lastOpenedDate)
logApplicationUsageEvent("Inactive", startupType:nil, startupTime: nil, openDuration: openDuration)
NetworkReachability.sharedInstance.logNetworkStatusEvent()
TelemetryLogger.sharedInstance.persistState()
}
internal func appDidEnterBackground() {
SessionState.sessionPaused()
let openDuration = Date.milliSecondsSinceDate(lastOpenedDate)
logApplicationUsageEvent("Background", startupType:nil, startupTime: nil, openDuration: openDuration)
TelemetryLogger.sharedInstance.appDidEnterBackground()
NewsNotificationPermissionHelper.sharedInstance.onAppEnterBackground()
}
internal func appWillTerminate() {
logApplicationUsageEvent("Terminate")
TelemetryLogger.sharedInstance.persistState()
}
//MARK:- Private Helper Methods
//MARK: VersionDescriptor
fileprivate func getVersionDescriptor() -> (version: String, buildNumber: String) {
var version = "0"
var buildNumber = "0"
if let shortVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
version = shortVersion
}
if let bundleVersion = Bundle.main.infoDictionary?["CFBundleVersion"] as? String {
buildNumber = bundleVersion
}
return (version, buildNumber)
}
fileprivate func loadStoredVersionDescriptor() -> (version: String, buildNumber: String)? {
if let storedVersion = LocalDataStore.objectForKey(self.versionDescriptorKey) as? String {
if let storedBuildNumber = LocalDataStore.objectForKey(self.buildNumberDescriptorKey) as? String {
return (storedVersion, storedBuildNumber)
}
}
// otherwise return nil
return nil
}
fileprivate func updateVersionDescriptor(_ versionDescriptor: (version: String, buildNumber: String)) {
self.versionDescriptor = versionDescriptor
LocalDataStore.setObject(versionDescriptor.version, forKey: self.versionDescriptorKey)
LocalDataStore.setObject(versionDescriptor.buildNumber, forKey: self.buildNumberDescriptorKey)
}
//MARK: application life cycle event
fileprivate func logLifeCycleEvent(_ action: String) {
TelemetryLogger.sharedInstance.logEvent(.LifeCycle(action, distVersion))
}
//MARK: application usage event
fileprivate func logApplicationUsageEvent(_ action: String) {
logApplicationUsageEvent(action, startupType: nil, startupTime: nil, openDuration: nil)
}
fileprivate func logApplicationUsageEvent(_ action: String, startupType: String?, startupTime: Double?, openDuration: Double?) {
dispatchQueue.async {
let network = NetworkReachability.sharedInstance.networkReachabilityStatus?.description
let battery = self.batteryLevel()
let memory = self.getMemoryUsage()
TelemetryLogger.sharedInstance.logEvent(TelemetryLogEventType.ApplicationUsage(action, network!, battery, memory, startupType, startupTime, openDuration))
}
}
//MARK: application Environment event
fileprivate func logEnvironmentEventIfNecessary(_ profile: Profile) {
if let lastdate = lastEnvironmentEventDate {
let timeSinceLastEvent = Date().timeIntervalSince(lastdate)
if timeSinceLastEvent < 3600 {
//less than an hour since last sent event
return
}
}
dispatchQueue.async {
self.lastEnvironmentEventDate = Date()
let device: String = UIDevice.current.modelName
let language = self.getAppLanguage()
let extensionVersion = self.extensionVersion
let distVersion = self.distVersion
let hostVersion = self.hostVersion
let osVersion = UIDevice.current.systemVersion
let defaultSearchEngine = profile.searchEngines.defaultEngine.shortName
let historyUrls = profile.history.count()
let historyDays = self.getHistoryDays(profile)
//TODO `prefs`
let prefs = self.getEnvironmentPrefs(profile)
TelemetryLogger.sharedInstance.logEvent(TelemetryLogEventType.Environment(device, language, extensionVersion, distVersion, hostVersion, osVersion, defaultSearchEngine, historyUrls, historyDays, prefs))
}
}
fileprivate func getEnvironmentPrefs(_ profile: Profile) -> [String: AnyObject] {
var prefs = [String: AnyObject]()
prefs["block_popups"] = SettingsPrefs.shared.getBlockPopupsPref() as AnyObject?
prefs["block_explicit"] = SettingsPrefs.shared.getBlockExplicitContentPref() as AnyObject?
prefs["block_ads"] = SettingsPrefs.shared.getAdBlockerPref() as AnyObject?
prefs["fair_blocking"] = SettingsPrefs.shared.getFairBlockingPref() as AnyObject?
prefs["human_web"] = SettingsPrefs.shared.getHumanWebPref() as AnyObject?
prefs["country"] = SettingsPrefs.shared.getDefaultRegion() as AnyObject?
prefs["location_access"] = LocationManager.sharedInstance.isLocationAcessEnabled() as AnyObject?
if let abTests = ABTestsManager.getABTests(), JSONSerialization.isValidJSONObject(abTests) {
do {
let data = try JSONSerialization.data(withJSONObject: abTests, options: [])
let stringifiedAbTests = NSString(data: data, encoding: String.Encoding.utf8.rawValue)
prefs["ABTests"] = stringifiedAbTests
} catch let error as NSError {
print("stringifyABTests: \(error)")
}
}
return prefs
}
fileprivate func getAppLanguage() -> String {
if let languageCode = Locale.current.languageCode, let regionCode = Locale.current.regionCode {
return "\(languageCode)-\(regionCode)"
}
return ""
}
fileprivate func getHistoryDays(_ profile: Profile) -> Int {
var historyDays = 0
if let oldestVisitDate = profile.history.getOldestVisitDate() {
historyDays = Date().daysSinceDate(oldestVisitDate)
}
return historyDays
}
func getMemoryUsage()-> Double {
var info = task_basic_info()
var count = mach_msg_type_number_t(MemoryLayout.size(ofValue: info))/4
let kerr: kern_return_t = withUnsafeMutablePointer(to: &info) {
$0.withMemoryRebound(to: integer_t.self, capacity: 1) {
task_info(mach_task_self_,
task_flavor_t(TASK_BASIC_INFO),
$0,
&count)
}
}
if kerr == KERN_SUCCESS {
let memorySize = Double(info.resident_size) / 1048576.0
return memorySize
}
else {
return -1
}
}
}
| mpl-2.0 | d7e0b162b78a893fd08bac3762e8d941 | 35.645695 | 213 | 0.640101 | 5.245024 | false | false | false | false |
finn-no/Finjinon | Sources/PhotoCaptureViewController/PhotoCollectionViewCell.swift | 1 | 3259 | //
// Copyright (c) 2017 FINN.no AS. All rights reserved.
//
import UIKit
protocol PhotoCollectionViewCellDelegate: NSObjectProtocol {
func collectionViewCellDidTapDelete(_ cell: PhotoCollectionViewCell)
}
open class PhotoCollectionViewCell: UICollectionViewCell {
open class func cellIdentifier() -> String { return "PhotoCell" }
public let imageView = UIImageView(frame: CGRect.zero)
public let closeButton: UIButton = CloseButton(frame: CGRect(x: 0, y: 0, width: 22, height: 22))
open internal(set) var asset: Asset?
weak var delegate: PhotoCollectionViewCellDelegate?
public override init(frame: CGRect) {
super.init(frame: frame)
let offset = closeButton.bounds.height / 3
imageView.frame = CGRect(x: offset, y: offset, width: contentView.bounds.width - (offset * 2), height: contentView.bounds.height - (offset * 2))
imageView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
contentView.addSubview(imageView)
closeButton.addTarget(self, action: #selector(closeButtonTapped(_:)), for: .touchUpInside)
contentView.addSubview(closeButton)
}
public required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
open override func prepareForReuse() {
super.prepareForReuse()
delegate = nil
asset = nil
}
@objc func closeButtonTapped(_: UIButton) {
delegate?.collectionViewCellDidTapDelete(self)
}
func proxy() -> UIView {
var wrapperFrame = self.imageView.bounds
wrapperFrame.origin.x = (bounds.size.width - wrapperFrame.size.width) / 2
wrapperFrame.origin.y = (bounds.size.height - wrapperFrame.size.height) / 2
let imageWrapper = UIView(frame: wrapperFrame)
imageWrapper.clipsToBounds = true
let image = UIImage(cgImage: self.imageView.image!.cgImage!, scale: self.imageView.image!.scale, orientation: self.imageView.image!.imageOrientation)
// Cumbersome indeed, but unfortunately re-rendering through begin graphicContext etc. fails quite often in iOS9
var imageRect: CGRect {
let viewSize = self.imageView.frame.size
let imageIsLandscape = image.size.width > image.size.height
if imageIsLandscape {
let ratio = image.size.height / viewSize.height
let width = image.size.width / ratio
let x = -(width - viewSize.width) / 2
return CGRect(x: x, y: 0, width: width, height: viewSize.height)
} else {
let ratio = image.size.width / viewSize.width
let height = image.size.height / ratio
let y = -(height - viewSize.height) / 2
return CGRect(x: 0, y: y, width: viewSize.width, height: height)
}
}
let imageView = UIImageView(image: image)
imageView.contentMode = .scaleAspectFill
imageView.clipsToBounds = true
imageView.frame = imageRect
imageWrapper.addSubview(imageView)
imageWrapper.transform = contentView.transform
return imageWrapper
}
}
| mit | aa6a3abcbdcdfd3c12e44505d6e52164 | 37.341176 | 157 | 0.656029 | 4.778592 | false | false | false | false |
okhanokbay/ExpyTableView | ExpyTableView/Classes/ExpyTableView.swift | 1 | 8361 | //
// ExpyTableView.swift
//
// Created by Okhan Okbay on 15/06/2017.
//
// The MIT License (MIT)
//
// Copyright (c) 2017 okhanokbay
//
// 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
@objcMembers open class ExpyTableView: UITableView {
fileprivate weak var expyDataSource: ExpyTableViewDataSource?
fileprivate weak var expyDelegate: ExpyTableViewDelegate?
public fileprivate(set) var expandedSections: [Int: Bool] = [:]
open var expandingAnimation: UITableView.RowAnimation = ExpyTableViewDefaultValues.expandingAnimation
open var collapsingAnimation: UITableView.RowAnimation = ExpyTableViewDefaultValues.collapsingAnimation
public override init(frame: CGRect, style: UITableView.Style) {
super.init(frame: frame, style: style)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
open override var dataSource: UITableViewDataSource? {
get { return super.dataSource }
set(dataSource) {
guard let dataSource = dataSource else { return }
expyDataSource = dataSource as? ExpyTableViewDataSource
super.dataSource = self
}
}
open override var delegate: UITableViewDelegate? {
get { return super.delegate }
set(delegate) {
guard let delegate = delegate else { return }
expyDelegate = delegate as? ExpyTableViewDelegate
super.delegate = self
}
}
open override func awakeFromNib() {
super.awakeFromNib()
if expyDelegate == nil {
//Set UITableViewDelegate even if ExpyTableViewDelegate is nil. Because we are getting callbacks here in didSelectRowAtIndexPath UITableViewDelegate method.
super.delegate = self
}
}
}
extension ExpyTableView {
public func expand(_ section: Int) {
animate(with: .expand, forSection: section)
}
public func collapse(_ section: Int) {
animate(with: .collapse, forSection: section)
}
private func animate(with type: ExpyActionType, forSection section: Int) {
guard canExpand(section) else { return }
let sectionIsExpanded = didExpand(section)
//If section is visible and action type is expand, OR, If section is not visible and action type is collapse, return.
if ((type == .expand) && (sectionIsExpanded)) || ((type == .collapse) && (!sectionIsExpanded)) { return }
assign(section, asExpanded: (type == .expand))
startAnimating(self, with: type, forSection: section)
}
private func startAnimating(_ tableView: ExpyTableView, with type: ExpyActionType, forSection section: Int) {
let headerCell = (self.cellForRow(at: IndexPath(row: 0, section: section)))
let headerCellConformant = headerCell as? ExpyTableViewHeaderCell
CATransaction.begin()
headerCell?.isUserInteractionEnabled = false
//Inform the delegates here.
headerCellConformant?.changeState((type == .expand ? .willExpand : .willCollapse), cellReuseStatus: false)
expyDelegate?.tableView(tableView, expyState: (type == .expand ? .willExpand : .willCollapse), changeForSection: section)
CATransaction.setCompletionBlock {
//Inform the delegates here.
headerCellConformant?.changeState((type == .expand ? .didExpand : .didCollapse), cellReuseStatus: false)
self.expyDelegate?.tableView(tableView, expyState: (type == .expand ? .didExpand : .didCollapse), changeForSection: section)
headerCell?.isUserInteractionEnabled = true
}
self.beginUpdates()
//Don't insert or delete anything if section has only 1 cell.
if let sectionRowCount = expyDataSource?.tableView(tableView, numberOfRowsInSection: section), sectionRowCount > 1 {
var indexesToProcess: [IndexPath] = []
//Start from 1, because 0 is the header cell.
for row in 1..<sectionRowCount {
indexesToProcess.append(IndexPath(row: row, section: section))
}
//Expand means inserting rows, collapse means deleting rows.
if type == .expand {
self.insertRows(at: indexesToProcess, with: expandingAnimation)
}else if type == .collapse {
self.deleteRows(at: indexesToProcess, with: collapsingAnimation)
}
}
self.endUpdates()
CATransaction.commit()
}
}
extension ExpyTableView: UITableViewDataSource {
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let numberOfRows = expyDataSource?.tableView(self, numberOfRowsInSection: section) ?? 0
guard canExpand(section) else { return numberOfRows }
guard numberOfRows != 0 else { return 0 }
return didExpand(section) ? numberOfRows : 1
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
guard canExpand(indexPath.section), indexPath.row == 0 else {
return expyDataSource!.tableView(tableView, cellForRowAt: indexPath)
}
let headerCell = expyDataSource!.tableView(self, expandableCellForSection: indexPath.section)
guard let headerCellConformant = headerCell as? ExpyTableViewHeaderCell else {
return headerCell
}
DispatchQueue.main.async {
if self.didExpand(indexPath.section) {
headerCellConformant.changeState(.willExpand, cellReuseStatus: true)
headerCellConformant.changeState(.didExpand, cellReuseStatus: true)
}else {
headerCellConformant.changeState(.willCollapse, cellReuseStatus: true)
headerCellConformant.changeState(.didCollapse, cellReuseStatus: true)
}
}
return headerCell
}
}
extension ExpyTableView: UITableViewDelegate {
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
expyDelegate?.tableView?(tableView, didSelectRowAt: indexPath)
guard canExpand(indexPath.section), indexPath.row == 0 else { return }
didExpand(indexPath.section) ? collapse(indexPath.section) : expand(indexPath.section)
}
}
//MARK: Helper Methods
extension ExpyTableView {
fileprivate func canExpand(_ section: Int) -> Bool {
//If canExpandSections delegate method is not implemented, it defaults to true.
return expyDataSource?.tableView(self, canExpandSection: section) ?? ExpyTableViewDefaultValues.expandableStatus
}
fileprivate func didExpand(_ section: Int) -> Bool {
return expandedSections[section] ?? false
}
fileprivate func assign(_ section: Int, asExpanded: Bool) {
expandedSections[section] = asExpanded
}
}
//MARK: Protocol Helper
extension ExpyTableView {
fileprivate func verifyProtocol(_ aProtocol: Protocol, contains aSelector: Selector) -> Bool {
return protocol_getMethodDescription(aProtocol, aSelector, true, true).name != nil || protocol_getMethodDescription(aProtocol, aSelector, false, true).name != nil
}
override open func responds(to aSelector: Selector!) -> Bool {
if verifyProtocol(UITableViewDataSource.self, contains: aSelector) {
return (super.responds(to: aSelector)) || (expyDataSource?.responds(to: aSelector) ?? false)
}else if verifyProtocol(UITableViewDelegate.self, contains: aSelector) {
return (super.responds(to: aSelector)) || (expyDelegate?.responds(to: aSelector) ?? false)
}
return super.responds(to: aSelector)
}
override open func forwardingTarget(for aSelector: Selector!) -> Any? {
if verifyProtocol(UITableViewDataSource.self, contains: aSelector) {
return expyDataSource
}else if verifyProtocol(UITableViewDelegate.self, contains: aSelector) {
return expyDelegate
}
return super.forwardingTarget(for: aSelector)
}
}
| mit | df0a9bb18f71ef72b96e7ec36dc5700e | 35.038793 | 164 | 0.744289 | 4.104566 | false | false | false | false |
danielgindi/Charts | ChartsDemo-macOS/PlaygroundChart.playground/Pages/PieChart.xcplaygroundpage/Contents.swift | 9 | 2196 | //
// PlayGround
//
// Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda
// Copyright ยฉ 2017 thierry Hentic.
// A port of MPAndroidChart for iOS
// Licensed under Apache License 2.0
//
// https://github.com/danielgindi/ios-charts
/*:
****
[Menu](Menu)
[Previous](@previous) | [Next](@next)
****
*/
//: # Pie Chart
import Cocoa
import Charts
import PlaygroundSupport
let r = CGRect(x: 0, y: 0, width: 600, height: 600)
var chartView = PieChartView(frame: r)
//: ### General
let paragraphStyle: NSMutableParagraphStyle = NSParagraphStyle.default().mutableCopy() as! NSMutableParagraphStyle
paragraphStyle.lineBreakMode = .byTruncatingTail
paragraphStyle.alignment = .center
let centerText: NSMutableAttributedString = NSMutableAttributedString(string: "Charts\nby Daniel Cohen Gindi")
centerText.setAttributes([NSFontAttributeName: NSUIFont(name: "HelveticaNeue-Light", size: 15.0)!, NSParagraphStyleAttributeName: paragraphStyle], range: NSMakeRange(0, centerText.length))
centerText.addAttributes([NSFontAttributeName: NSUIFont(name: "HelveticaNeue-Light", size: 13.0)!, NSForegroundColorAttributeName: NSUIColor.gray], range: NSMakeRange(10, centerText.length - 10))
centerText.addAttributes([NSFontAttributeName: NSUIFont(name: "HelveticaNeue-LightItalic", size: 13.0)!, NSForegroundColorAttributeName: NSUIColor(red: 51 / 255.0, green: 181 / 255.0, blue: 229 / 255.0, alpha: 1.0)], range: NSMakeRange(centerText.length - 19, 19))
chartView.centerAttributedText = centerText
chartView.chartDescription?.text = "Pie Chart"
//: ### PieChartDataEntry
let ys1 = Array(1..<10).map { x in return sin(Double(x) / 2.0 / 3.141 * 1.5) * 100.0 }
let yse1 = ys1.enumerated().map { x, y in return PieChartDataEntry(value: y, label: String(x)) }
//: ### PieChartDataSet
let ds1 = PieChartDataSet(values: yse1, label: "Hello")
ds1.colors = ChartColorTemplates.vordiplom()
//: ### PieChartData
let data = PieChartData()
data.addDataSet(ds1)
chartView.data = data
chartView.animate(xAxisDuration: 2.0, yAxisDuration: 2.0, easingOption: .easeInBounce)
/*:---*/
//: ### Setup for the live view
PlaygroundPage.current.liveView = chartView
/*:
****
[Previous](@previous) | [Next](@next)
*/
| apache-2.0 | 2621684114aa316738776429877e3693 | 37.508772 | 264 | 0.736219 | 3.926655 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.