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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
devxoul/Date.swift
|
Date/Date.swift
|
1
|
12283
|
// The MIT License (MIT)
//
// Copyright (c) 2015 Suyeol Jeon (xoul.kr)
//
// 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
// MARK: - Initializing with date components
public extension NSDate {
public convenience init(year: Int, month: Int, day: Int, hours: Int, minutes: Int, seconds: Double) {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
components.hour = hours
components.minute = minutes
components.second = Int(seconds)
components.nanosecond = Int((seconds - floor(seconds)) * 1_000_000_000)
let interval = NSCalendar.currentCalendar().dateFromComponents(components)?.timeIntervalSinceReferenceDate ?? 0
self.init(timeIntervalSinceReferenceDate: interval)
}
public convenience init(year: Int, month: Int, day: Int) {
let components = NSDateComponents()
components.year = year
components.month = month
components.day = day
let interval = NSCalendar.currentCalendar().dateFromComponents(components)?.timeIntervalSinceReferenceDate ?? 0
self.init(timeIntervalSinceReferenceDate: interval)
}
public convenience init(hours: Int, minutes: Int, seconds: Double) {
let components = NSDateComponents()
components.hour = hours
components.minute = minutes
components.second = Int(seconds)
components.nanosecond = Int((seconds - floor(seconds)) * 1_000_000_000)
let interval = NSCalendar.currentCalendar().dateFromComponents(components)?.timeIntervalSinceReferenceDate ?? 0
self.init(timeIntervalSinceReferenceDate: interval)
}
public class func date(year: Int, _ month: Int, _ day: Int) -> NSDate {
return NSDate(year: year, month: month, day: day)
}
public class func time(hours: Int, _ minutes: Int, _ seconds: Double) -> NSDate {
return NSDate(hours: hours, minutes: minutes, seconds: seconds)
}
}
// MARK: - Extracting date
public extension NSDate {
public var date: NSDate {
return NSDate(year: self.year, month: self.month, day: self.day)
}
public class var today: NSDate {
return NSDate().date
}
}
// MARK: - Setter and getters for date components
public extension NSDate {
public var year: Int { return self.components(.Year).year }
public var month: Int { return self.components(.Month).month }
public var day: Int { return self.components(.Day).day }
public var hours: Int { return self.components(.Hour).hour }
public var minutes: Int { return self.components(.Minute).minute }
public var seconds: Double {
let components = self.components([.Second, .Nanosecond])
return Double(components.second) + Double(components.nanosecond) / 1_000_000_000
}
public var weekday: Int { return self.components(.Weekday).weekday }
public func withYear(year: Int) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withMonth(month: Int) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withDay(day: Int) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withHours(hours: Int) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withMinutes(minutes: Int) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withSeconds(seconds: Double) -> NSDate {
return NSDate(year: year, month: month, day: day, hours: hours, minutes: minutes, seconds: seconds)
}
public func withWeekday(weekday: Int) -> NSDate! {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Weekday], fromDate: self)
components.day += weekday - components.weekday
return calendar.dateFromComponents(components)!
}
private func components(units: NSCalendarUnit) -> NSDateComponents {
return NSCalendar.currentCalendar().components(units, fromDate: self)
}
}
// MARK: - Relative datetime
public extension IntegerLiteralType {
public var years: _DateTimeDelta { return _DateTimeDelta(self, .Year) }
public var months: _DateTimeDelta { return _DateTimeDelta(self, .Month) }
public var days: _DateTimeDelta { return _DateTimeDelta(self, .Day) }
public var hours: _DateTimeDelta { return _DateTimeDelta(self, .Hour) }
public var minutes: _DateTimeDelta { return _DateTimeDelta(self, .Minute) }
public var seconds: _DateTimeDelta { return _DateTimeDelta(self, .Second) }
public var year: _DateTimeDelta { return self.years }
public var month: _DateTimeDelta { return self.months }
public var day: _DateTimeDelta { return self.days }
public var hour: _DateTimeDelta { return self.hours }
public var minute: _DateTimeDelta { return self.minutes }
public var second: _DateTimeDelta { return self.seconds }
}
public extension FloatLiteralType {
public var seconds: _DateTimeDelta { return _DateTimeDelta(self, .Second) }
public var second: _DateTimeDelta { return self.seconds }
}
public struct _DateTimeDelta {
public var value: NSTimeInterval
public var unit: NSCalendarUnit
public init(_ value: NSTimeInterval, _ unit: NSCalendarUnit) {
self.value = value
self.unit = unit
}
public init(_ value: IntegerLiteralType, _ unit: NSCalendarUnit) {
self.init(NSTimeInterval(value), unit)
}
private var negativeDelta: _DateTimeDelta {
return self.dynamicType.init(-self.value, self.unit)
}
public func after(date: NSDate) -> NSDate {
switch self.unit {
case NSCalendarUnit.Year: return date.withYear(date.year + Int(self.value))
case NSCalendarUnit.Month: return date.withMonth(date.month + Int(self.value))
case NSCalendarUnit.Day: return date.withDay(date.day + Int(self.value))
case NSCalendarUnit.Hour: return date.withHours(date.hours + Int(self.value))
case NSCalendarUnit.Minute: return date.withMinutes(date.minutes + Int(self.value))
case NSCalendarUnit.Second: return date.withSeconds(date.seconds + self.value)
default: return date
}
}
public func before(date: NSDate) -> NSDate {
return self.negativeDelta.after(date)
}
public var fromNow: NSDate {
return self.after(NSDate())
}
public var ago: NSDate {
return self.negativeDelta.fromNow
}
}
public func + (date: NSDate, delta: _DateTimeDelta) -> NSDate { return delta.after(date) }
public func + (delta: _DateTimeDelta, date: NSDate) -> NSDate { return delta.after(date) }
public func - (date: NSDate, delta: _DateTimeDelta) -> NSDate { return delta.before(date) }
// MARK: - Calendar
public extension NSDate {
public class var january: NSDate { return NSDate.today.withMonth(1).withDay(1) }
public class var february: NSDate { return NSDate.today.withMonth(2).withDay(1) }
public class var march: NSDate { return NSDate.today.withMonth(3).withDay(1) }
public class var april: NSDate { return NSDate.today.withMonth(4).withDay(1) }
public class var may: NSDate { return NSDate.today.withMonth(5).withDay(1) }
public class var june: NSDate { return NSDate.today.withMonth(6).withDay(1) }
public class var july: NSDate { return NSDate.today.withMonth(7).withDay(1) }
public class var august: NSDate { return NSDate.today.withMonth(8).withDay(1) }
public class var september: NSDate { return NSDate.today.withMonth(9).withDay(1) }
public class var october: NSDate { return NSDate.today.withMonth(10).withDay(1) }
public class var november: NSDate { return NSDate.today.withMonth(11).withDay(1) }
public class var december: NSDate { return NSDate.today.withMonth(12).withDay(1) }
public class var jan: NSDate { return self.january }
public class var feb: NSDate { return self.february }
public class var mar: NSDate { return self.march }
public class var apr: NSDate { return self.april }
public class var jun: NSDate { return self.june }
public class var jul: NSDate { return self.july }
public class var aug: NSDate { return self.august }
public class var sep: NSDate { return self.september }
public class var oct: NSDate { return self.october }
public class var nov: NSDate { return self.november }
public class var dec: NSDate { return self.december }
public var first: _CalendarDelta { return self.calendarDelta(0) }
public var second: _CalendarDelta { return self.calendarDelta(1) }
public var third: _CalendarDelta { return self.calendarDelta(2) }
public var fourth: _CalendarDelta { return self.calendarDelta(3) }
public var fifth: _CalendarDelta { return self.calendarDelta(4) }
public var last: _CalendarDelta { return self.calendarDelta(-1) }
private func calendarDelta(ordinal: Int) -> _CalendarDelta {
return _CalendarDelta(date: self, ordinal: ordinal)
}
public class var sunday: NSDate? { return NSDate.today.withWeekday(1) }
public class var monday: NSDate? { return NSDate.today.withWeekday(2) }
public class var tuesday: NSDate? { return NSDate.today.withWeekday(3) }
public class var wednesday: NSDate? { return NSDate.today.withWeekday(4) }
public class var thursday: NSDate? { return NSDate.today.withWeekday(5) }
public class var friday: NSDate? { return NSDate.today.withWeekday(6) }
public class var saturday: NSDate? { return NSDate.today.withWeekday(7) }
}
public struct _CalendarDelta {
public var date: NSDate
/// `0` for first and `-1` for last
public var ordinal: Int
public var sunday: NSDate? { return self.weekday(1) }
public var monday: NSDate? { return self.weekday(2) }
public var tuesday: NSDate? { return self.weekday(3) }
public var wednesday: NSDate? { return self.weekday(4) }
public var thursday: NSDate? { return self.weekday(5) }
public var friday: NSDate? { return self.weekday(6) }
public var saturday: NSDate? { return self.weekday(7) }
private func weekday(weekday: Int) -> NSDate? {
if self.ordinal == -1 {
for i in (1...5).reverse() {
if let date = _CalendarDelta(date: self.date, ordinal: i).weekday(weekday) {
return date
}
}
return nil
}
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Month, .Day, .Weekday], fromDate: self.date)
let ordinal = (weekday >= components.weekday) ? self.ordinal : self.ordinal + 1
components.day += weekday + 7 * ordinal - components.weekday
if let date = calendar.dateFromComponents(components) where date.month == components.month {
return date
}
return nil
}
}
|
mit
|
ca36ccd7d015edf71f0ae245f74d0e57
| 39.272131 | 119 | 0.684523 | 4.159499 | false | false | false | false |
arinjoy/Landmark-Remark
|
LandmarkRemark/Font.swift
|
1
|
3635
|
//
// Font.swift
// LandmarkRemark
//
// Created by Arinjoy Biswas on 6/06/2016.
// Copyright © 2016 Arinjoy Biswas. All rights reserved.
//
import UIKit
/**
* Utility for a list of custom font instances
*/
struct Font {
static let avenir8 = UIFont(name: "Avenir Next", size: 8)
static let avenir10 = UIFont(name: "Avenir Next", size: 10)
static let avenir12 = UIFont(name: "Avenir Next", size: 12)
static let avenir13 = UIFont(name: "Avenir Next", size: 13)
static let avenir14 = UIFont(name: "Avenir Next", size: 14)
static let avenir15 = UIFont(name: "Avenir Next", size: 15)
static let avenir16 = UIFont(name: "Avenir Next", size: 16)
static let avenir17 = UIFont(name: "Avenir Next", size: 17)
static let avenir18 = UIFont(name: "Avenir Next", size: 18)
static let avenir19 = UIFont(name: "Avenir Next", size: 19)
static let avenir20 = UIFont(name: "Avenir Next", size: 20)
static let avenir21 = UIFont(name: "Avenir Next", size: 21)
static let avenir10B = UIFont(name: "AvenirNext-Bold", size: 10)
static let avenir10D = UIFont(name: "AvenirNext-DemiBold", size: 10)
static let avenir10M = UIFont(name: "AvenirNext-Medium", size: 10)
static let avenir12B = UIFont(name: "AvenirNext-Bold", size: 12)
static let avenir12D = UIFont(name: "AvenirNext-DemiBold", size: 12)
static let avenir12M = UIFont(name: "AvenirNext-Medium", size: 12)
static let avenir13B = UIFont(name: "AvenirNext-Bold", size: 13)
static let avenir13D = UIFont(name: "AvenirNext-DemiBold", size: 13)
static let avenir13M = UIFont(name: "AvenirNext-Medium", size: 13)
static let avenir14B = UIFont(name: "AvenirNext-Bold", size: 14)
static let avenir14D = UIFont(name: "AvenirNext-DemiBold", size: 14)
static let avenir14M = UIFont(name: "AvenirNext-Medium", size: 14)
static let avenir15B = UIFont(name: "AvenirNext-Bold", size: 15)
static let avenir15D = UIFont(name: "AvenirNext-DemiBold", size: 15)
static let avenir15M = UIFont(name: "AvenirNext-Medium", size: 15)
static let avenir16B = UIFont(name: "AvenirNext-Bold", size: 16)
static let avenir16D = UIFont(name: "AvenirNext-DemiBold", size: 16)
static let avenir16M = UIFont(name: "AvenirNext-Medium", size: 16)
static let avenir17B = UIFont(name: "AvenirNext-Bold", size: 17)
static let avenir17D = UIFont(name: "AvenirNext-DemiBold", size: 17)
static let avenir17M = UIFont(name: "AvenirNext-Medium", size: 17)
static let avenir18B = UIFont(name: "AvenirNext-Bold", size: 18)
static let avenir18D = UIFont(name: "AvenirNext-DemiBold", size: 18)
static let avenir18M = UIFont(name: "AvenirNext-Medium", size: 18)
static let avenir19B = UIFont(name: "AvenirNext-Bold", size: 19)
static let avenir19D = UIFont(name: "AvenirNext-DemiBold", size: 19)
static let avenir19M = UIFont(name: "AvenirNext-Medium", size: 19)
static let avenir20B = UIFont(name: "AvenirNext-Bold", size: 20)
static let avenir20D = UIFont(name: "AvenirNext-DemiBold", size: 20)
static let avenir20M = UIFont(name: "AvenirNext-Medium", size: 20)
static let avenir21B = UIFont(name: "AvenirNext-Bold", size: 21)
static let avenir21D = UIFont(name: "AvenirNext-DemiBold", size: 21)
static let avenir21M = UIFont(name: "AvenirNext-Medium", size: 21)
static let avenir22B = UIFont(name: "AvenirNext-Bold", size: 22)
static let avenir22D = UIFont(name: "AvenirNext-DemiBold", size: 22)
static let avenir22M = UIFont(name: "AvenirNext-Medium", size: 22)
}
|
mit
|
e1957243a41a3248649b05a3d49f4c89
| 44.4375 | 72 | 0.679141 | 3.583826 | false | false | false | false |
coffee-cup/solis
|
SunriseSunset/AppDelegate.swift
|
1
|
4417
|
//
// AppDelegate.swift
// SunriseSunset
//
// Created by Jake Runzer on 2016-05-14.
// Copyright © 2016 Puddllee. All rights reserved.
//
import UIKit
import GooglePlaces
import Fabric
import Crashlytics
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var notifications: Notifications!
let timeZones = TimeZones()
let GoogleAPIKey = "AIzaSyATdTWF9AwHXq3UnCrAfr6czN7f_E86658"
func defaultString(_ defaultKey: DefaultKey) -> String {
return defaultKey.description
}
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
Defaults.defaults.register(defaults: [
defaultString(.timeFormat): "h:mm a",
defaultString(.firstLight): false,
defaultString(.lastLight): false,
defaultString(.sunset): false,
defaultString(.sunrise): false,
defaultString(.notificationPreTime): 60 * 60 * 5, // minutes
defaultString(.currentLocation): true,
defaultString(.locationHistoryPlaces): [],
defaultString(.showWalkthrough): true,
defaultString(.showSunAreas): true
])
GMSPlacesClient.provideAPIKey(GoogleAPIKey)
application.setMinimumBackgroundFetchInterval(60 * 60 * 3) // 3 hours
// Set initial view controller
self.window = UIWindow(frame: UIScreen.main.bounds)
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initViewControllerIdentifier = Defaults.showWalkthrough ? "WalkthroughViewController" : "MainViewController"
let initialViewController = storyboard.instantiateViewController(withIdentifier: initViewControllerIdentifier)
self.window?.rootViewController = initialViewController
self.window?.makeKeyAndVisible()
#if RELEASE
Fabric.with([Crashlytics.self])
#else
print("DEBUG MODE")
#endif
// This MUST come after Fabric has been initialized
notifications = Notifications()
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:.
}
func application(_ application: UIApplication, performFetchWithCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if notifications == nil {
notifications = Notifications()
}
_ = notifications.scheduleNotifications()
notifications.checkIfNotificationsTriggered()
completionHandler(.newData)
}
}
|
mit
|
2235f108baaba736b4d81b5de3dbce07
| 41.461538 | 285 | 0.694067 | 5.795276 | false | false | false | false |
grachro/swift-layout
|
add-on/AutolayoutPullArea.swift
|
1
|
1901
|
//
// AutolayoutPullArea.swift
// swift-layout
//
// Created by grachro on 2014/09/15.
// Copyright (c) 2014年 grachro. All rights reserved.
//
import UIKit
class AutolayoutPullArea:ScrollViewPullArea {
fileprivate var _minHeight:CGFloat
fileprivate var _maxHeight:CGFloat
var topConstraint:NSLayoutConstraint?
var headerConstraint:NSLayoutConstraint?
let view = UIView()
fileprivate var _layout:Layout?
var layout:Layout {
get {return _layout!}
}
var pullCallback:((_ viewHeight:CGFloat, _ pullAreaHeight:CGFloat) -> Void)? = nil
init(minHeight:CGFloat, maxHeight:CGFloat, superview:UIView) {
self._minHeight = minHeight
self._maxHeight = maxHeight
_layout = Layout.addSubView(view, superview: superview)
.horizontalCenterInSuperview()
.leftIsSameSuperview()
.rightIsSameSuperview()
.top(-self._maxHeight).fromSuperviewTop().lastConstraint(&topConstraint)
.height(self._maxHeight).lastConstraint(&headerConstraint)
}
}
//implements ScrollViewPullArea
extension AutolayoutPullArea {
func minHeight() -> CGFloat {
return _minHeight
}
func maxHeight() -> CGFloat {
return _maxHeight
}
func animationSpeed() -> TimeInterval {
return 0.4
}
func show(viewHeight:CGFloat, pullAreaHeight:CGFloat) {
if viewHeight < pullAreaHeight {
self.topConstraint?.constant = -((pullAreaHeight - viewHeight) / 2 + viewHeight)
} else {
self.topConstraint?.constant = -viewHeight
}
self.headerConstraint?.constant = viewHeight
view.superview?.layoutIfNeeded()
self.pullCallback?(viewHeight, pullAreaHeight)
view.layoutIfNeeded()
}
}
|
mit
|
c5be6a7cb4df2a2a8877025e7484c670
| 24.662162 | 92 | 0.621906 | 4.958225 | false | false | false | false |
dreamsxin/swift
|
stdlib/public/core/CString.swift
|
3
|
7403
|
//===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
// String interop with C
//===----------------------------------------------------------------------===//
import SwiftShims
extension String {
/// Creates a new string by copying the null-terminated UTF-8 data referenced
/// by the given pointer.
///
/// If `cString` contains ill-formed UTF-8 code unit sequences, this
/// initializer replaces them with the Unicode replacement character
/// (`"\u{FFFD}"`).
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Café"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(cString: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Caf�"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init(cString: UnsafePointer<CChar>) {
self = String.decodeCString(UnsafePointer(cString), as: UTF8.self,
repairingInvalidCodeUnits: true)!.result
}
/// Creates a new string by copying and validating the null-terminated UTF-8
/// data referenced by the given pointer.
///
/// This initializer does not try to repair ill-formed UTF-8 code unit
/// sequences. If any are found, the result of the initializer is `nil`.
///
/// The following example calls this initializer with pointers to the
/// contents of two different `CChar` arrays---the first with well-formed
/// UTF-8 code unit sequences and the second with an ill-formed sequence at
/// the end.
///
/// let validUTF8: [CChar] = [67, 97, 102, -61, -87, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "Optional(Café)"
///
/// let invalidUTF8: [CChar] = [67, 97, 102, -61, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String(validatingUTF8: ptr.baseAddress!)
/// print(s)
/// }
/// // Prints "nil"
///
/// - Parameter cString: A pointer to a null-terminated UTF-8 code sequence.
public init?(validatingUTF8 cString: UnsafePointer<CChar>) {
guard let (result, _) = String.decodeCString(
UnsafePointer(cString),
as: UTF8.self,
repairingInvalidCodeUnits: false) else {
return nil
}
self = result
}
/// Creates a new string by copying the null-terminated data referenced by
/// the given pointer using the specified encoding.
///
/// When you pass `true` as `isRepairing`, this method replaces ill-formed
/// sequences with the Unicode replacement character (`"\u{FFFD}"`);
/// otherwise, an ill-formed sequence causes this method to stop decoding
/// and return `nil`.
///
/// The following example calls this method with pointers to the contents of
/// two different `CChar` arrays---the first with well-formed UTF-8 code
/// unit sequences and the second with an ill-formed sequence at the end.
///
/// let validUTF8: [UInt8] = [67, 97, 102, 195, 169, 0]
/// validUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((Café, false))"
///
/// let invalidUTF8: [UInt8] = [67, 97, 102, 195, 0]
/// invalidUTF8.withUnsafeBufferPointer { ptr in
/// let s = String.decodeCString(ptr.baseAddress,
/// as: UTF8.self,
/// repairingInvalidCodeUnits: true)
/// print(s)
/// }
/// // Prints "Optional((Caf�, true))"
///
/// - Parameters:
/// - cString: A pointer to a null-terminated code sequence encoded in
/// `encoding`.
/// - encoding: The Unicode encoding of the data referenced by `cString`.
/// - isRepairing: Pass `true` to create a new string, even when the data
/// referenced by `cString` contains ill-formed sequences. Ill-formed
/// sequences are replaced with the Unicode replacement character
/// (`"\u{FFFD}"`). Pass `false` to interrupt the creation of the new
/// string if an ill-formed sequence is detected.
/// - Returns: A tuple with the new string and a Boolean value that indicates
/// whether any repairs were made. If `isRepairing` is `false` and an
/// ill-formed sequence is detected, this method returns `nil`.
///
/// - SeeAlso: `UnicodeCodec`
public static func decodeCString<Encoding : UnicodeCodec>(
_ cString: UnsafePointer<Encoding.CodeUnit>?,
as encoding: Encoding.Type,
repairingInvalidCodeUnits isRepairing: Bool = true)
-> (result: String, repairsMade: Bool)? {
guard let cString = cString else {
return nil
}
let len = encoding._nullCodeUnitOffset(in: cString)
let buffer = UnsafeBufferPointer<Encoding.CodeUnit>(
start: cString, count: len)
let (stringBuffer, hadError) = _StringBuffer.fromCodeUnits(
buffer, encoding: encoding, repairIllFormedSequences: isRepairing)
return stringBuffer.map {
(result: String(_storage: $0), repairsMade: hadError)
}
}
}
/// From a non-`nil` `UnsafePointer` to a null-terminated string
/// with possibly-transient lifetime, create a null-terminated array of 'C' char.
/// Returns `nil` if passed a null pointer.
public func _persistCString(_ p: UnsafePointer<CChar>?) -> [CChar]? {
guard let s = p else {
return nil
}
let count = Int(_swift_stdlib_strlen(s))
var result = [CChar](repeating: 0, count: count + 1)
for i in 0..<count {
result[i] = s[i]
}
return result
}
extension String {
@available(*, unavailable, message: "Please use String.init?(validatingUTF8:) instead. Note that it no longer accepts NULL as a valid input. Also consider using String(cString:), that will attempt to repair ill-formed code units.")
public static func fromCString(_ cs: UnsafePointer<CChar>) -> String? {
Builtin.unreachable()
}
@available(*, unavailable, message: "Please use String.init(cString:) instead. Note that it no longer accepts NULL as a valid input. See also String.decodeCString if you need more control.")
public static func fromCStringRepairingIllFormedUTF8(
_ cs: UnsafePointer<CChar>
) -> (String?, hadError: Bool) {
Builtin.unreachable()
}
}
|
apache-2.0
|
fdf48c9e5abceeac5d97ca8d78236875
| 40.088889 | 233 | 0.617226 | 4.332748 | false | false | false | false |
tucali/Locksmith
|
Source/LocksmithSecurityClass.swift
|
14
|
1319
|
import Foundation
// With thanks to http://iosdeveloperzone.com/2014/10/22/taming-foundation-constants-into-swift-enums/
// MARK: Security Class
public enum LocksmithSecurityClass: RawRepresentable {
case GenericPassword, InternetPassword, Certificate, Key, Identity
public init?(rawValue: String) {
switch rawValue {
case String(kSecClassGenericPassword):
self = GenericPassword
case String(kSecClassInternetPassword):
self = InternetPassword
case String(kSecClassCertificate):
self = Certificate
case String(kSecClassKey):
self = Key
case String(kSecClassIdentity):
self = Identity
default:
print("SecurityClass: Invalid raw value provided. Defaulting to .GenericPassword")
self = GenericPassword
}
}
public var rawValue: String {
switch self {
case .GenericPassword:
return String(kSecClassGenericPassword)
case .InternetPassword:
return String(kSecClassInternetPassword)
case .Certificate:
return String(kSecClassCertificate)
case .Key:
return String(kSecClassKey)
case .Identity:
return String(kSecClassIdentity)
}
}
}
|
mit
|
20050cab5639f95fa6ef357500ffb7f1
| 31.975 | 102 | 0.634572 | 5.612766 | false | false | false | false |
GorCat/TSImagePicker
|
ImagePicker/ImagePicker/ImagePicker/UI/camera/core/CameraView.swift
|
1
|
5578
|
//
// CameraView.swift
// ImagePicker
//
// Created by GorCat on 2017/6/26.
// Copyright © 2017年 GorCat. All rights reserved.
//
import UIKit
import AVFoundation
protocol CameraViewDeleagate: class {
func camera(view: CameraView, finishTakePhoto image: UIImage?)
}
class CameraView: UIView, AVCapturePhotoCaptureDelegate {
let cameraQueue = DispatchQueue(label: "com.zero.ALCameraViewController.Queue")
/// 代理
weak var delegate: CameraViewDeleagate?
/// 摄像配置
let config = CameraConfig(position: .back)
/// 预览视图
var preview: AVCaptureVideoPreviewLayer?
/// 是否开启闪光灯
var isflashOpen = false
override init(frame: CGRect) {
super.init(frame: frame)
startSession()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
// MARK: - Custom user interface
// 开启相机
func startSession() {
config.starSession { [weak self] (preview) in
guard let weakSelf = self else {
return
}
weakSelf.preview = preview
weakSelf.preview?.frame = weakSelf.bounds
weakSelf.layer.addSublayer(weakSelf.preview!)
}
}
// MARK: - Public
/// 照相
func takePhoto() {
// 1.iOS 10 以下,通过 AVCaptureStillImageOutput 的 block 返回相片
guard #available(iOS 10, *) else {
let stillImageOutput = config.output as! AVCaptureStillImageOutput
let orientation = AVCaptureVideoOrientation(rawValue: UIDevice.current.orientation.rawValue)!
let connection = stillImageOutput.connection(withMediaType: AVMediaTypeVideo)
connection?.videoOrientation = orientation
stillImageOutput.captureStillImageAsynchronously(from: connection, completionHandler: { [weak self] (buffer: CMSampleBuffer?, error: Error?) in
guard let weakSelf = self, let buffer = buffer else {
return
}
guard let data = AVCaptureStillImageOutput.jpegStillImageNSDataRepresentation(buffer) else {
return
}
var image = UIImage(data: data)
// 如果是前置摄像头,镜像一下图片
if weakSelf.config.device?.position == .front {
image = image?.mirrorImage()
}
weakSelf.delegate?.camera(view: weakSelf, finishTakePhoto: image)
})
return
}
// 2.iOS 10 以上,通过 AVCapturePhotoOutput 的 代理方法 返回相片
guard let photoOutput = config.output as? AVCapturePhotoOutput else {
return
}
let setting = AVCapturePhotoSettings()
setting.flashMode = isflashOpen ? .on : .off
// 如果是前置摄像头,关闭闪光灯
if config.device?.position == .front {
setting.flashMode = .off
}
photoOutput.capturePhoto(with: setting, delegate: self)
}
/// 切换镜头
func swap() {
// 1.获取新的镜头方向
let currentPosition = config.input?.device.position
let newPosition: AVCaptureDevicePosition = currentPosition == .back ? .front : .back
// 2.切换镜头
config.swap(position: newPosition)
// 3.如果是 iOS 10,在切换前置后置摄像头时,需要设置一下闪光灯
guard #available(iOS 10, *) else {
guard config.device?.hasFlash == true else {
return
}
try! config.device?.lockForConfiguration()
if newPosition == .front {
// 前置时,关闭赏光
config.device?.flashMode = .on
} else {
// 后置时,开启闪光设置
config.device?.flashMode = isflashOpen ? .on : .off
}
config.device?.unlockForConfiguration()
return
}
}
/// 切换闪光灯
func switchFlash() {
// 1.iOS 10 以上,通过 output 设置闪光灯
isflashOpen = !isflashOpen
// 2.iOS 10 以下,通过 device 设置闪光灯
guard config.device?.hasFlash == true else {
return
}
guard #available(iOS 10, *) else {
try! config.device?.lockForConfiguration()
config.device?.flashMode = isflashOpen ? .on : .off
config.device?.unlockForConfiguration()
return
}
}
// MARK: - Delegate
// MARK: - AVCapturePhotoCaptureDelegate
@available(iOS 10.0, *)
func capture(_ captureOutput: AVCapturePhotoOutput, didFinishProcessingPhotoSampleBuffer photoSampleBuffer: CMSampleBuffer?, previewPhotoSampleBuffer: CMSampleBuffer?, resolvedSettings: AVCaptureResolvedPhotoSettings, bracketSettings: AVCaptureBracketedStillImageSettings?, error: Error?) {
guard let sampleBuffer = photoSampleBuffer else {
return
}
guard let data = AVCapturePhotoOutput.jpegPhotoDataRepresentation(forJPEGSampleBuffer: sampleBuffer, previewPhotoSampleBuffer: previewPhotoSampleBuffer) else {
return
}
var image = UIImage(data: data)
// 如果是前置摄像头,镜像一下图片
if config.device?.position == .front {
image = image?.mirrorImage()
}
delegate?.camera(view: self, finishTakePhoto: image)
}
}
|
mit
|
95ad1a1bab23c0d4cf601a64332ebe5a
| 32.280255 | 294 | 0.592919 | 4.971456 | false | true | false | false |
frootloops/swift
|
stdlib/public/core/Indices.swift
|
2
|
4144
|
//===----------------------------------------------------------------------===//
//
// 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 collection of indices for an arbitrary collection
@_fixed_layout
public struct DefaultIndices<Elements: Collection> {
@_versioned
internal var _elements: Elements
@_versioned
internal var _startIndex: Elements.Index
@_versioned
internal var _endIndex: Elements.Index
@_inlineable
@_versioned
internal init(
_elements: Elements,
startIndex: Elements.Index,
endIndex: Elements.Index
) {
self._elements = _elements
self._startIndex = startIndex
self._endIndex = endIndex
}
}
extension DefaultIndices: Collection {
public typealias Index = Elements.Index
public typealias Element = Elements.Index
public typealias Indices = DefaultIndices<Elements>
public typealias SubSequence = DefaultIndices<Elements>
public typealias Iterator = IndexingIterator<DefaultIndices<Elements>>
@_inlineable
public var startIndex: Index {
return _startIndex
}
@_inlineable
public var endIndex: Index {
return _endIndex
}
@_inlineable
public subscript(i: Index) -> Elements.Index {
// FIXME: swift-3-indexing-model: range check.
return i
}
@_inlineable
public subscript(bounds: Range<Index>) -> DefaultIndices<Elements> {
// FIXME: swift-3-indexing-model: range check.
return DefaultIndices(
_elements: _elements,
startIndex: bounds.lowerBound,
endIndex: bounds.upperBound)
}
@_inlineable
public func index(after i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(after: i)
}
@_inlineable
public func formIndex(after i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(after: &i)
}
@_inlineable
public var indices: Indices {
return self
}
}
extension DefaultIndices: BidirectionalCollection
where Elements: BidirectionalCollection {
@_inlineable
public func index(before i: Index) -> Index {
// FIXME: swift-3-indexing-model: range check.
return _elements.index(before: i)
}
@_inlineable
public func formIndex(before i: inout Index) {
// FIXME: swift-3-indexing-model: range check.
_elements.formIndex(before: &i)
}
}
extension DefaultIndices: RandomAccessCollection
where Elements: RandomAccessCollection { }
extension Collection where Indices == DefaultIndices<Self> {
/// The indices that are valid for subscripting the collection, in ascending
/// order.
///
/// A collection's `indices` property can hold a strong reference to the
/// collection itself, causing the collection to be non-uniquely referenced.
/// If you mutate the collection while iterating over its indices, a strong
/// reference can cause an unexpected copy of the collection. To avoid the
/// unexpected copy, use the `index(after:)` method starting with
/// `startIndex` to produce indices instead.
///
/// var c = MyFancyCollection([10, 20, 30, 40, 50])
/// var i = c.startIndex
/// while i != c.endIndex {
/// c[i] /= 5
/// i = c.index(after: i)
/// }
/// // c == MyFancyCollection([2, 4, 6, 8, 10])
@_inlineable // FIXME(sil-serialize-all)
public var indices: DefaultIndices<Self> {
return DefaultIndices(
_elements: self,
startIndex: self.startIndex,
endIndex: self.endIndex)
}
}
@available(*, deprecated, renamed: "DefaultIndices")
public typealias DefaultBidirectionalIndices<T> = DefaultIndices<T> where T : BidirectionalCollection
@available(*, deprecated, renamed: "DefaultIndices")
public typealias DefaultRandomAccessIndices<T> = DefaultIndices<T> where T : RandomAccessCollection
|
apache-2.0
|
c4e511194c61b861a8dd604fcc7af17f
| 29.696296 | 101 | 0.673986 | 4.484848 | false | false | false | false |
KrishMunot/swift
|
stdlib/public/core/StringUnicodeScalarView.swift
|
3
|
13535
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
@warn_unused_result
public func ==(
lhs: String.UnicodeScalarView.Index,
rhs: String.UnicodeScalarView.Index
) -> Bool {
return lhs._position == rhs._position
}
@warn_unused_result
public func <(
lhs: String.UnicodeScalarView.Index,
rhs: String.UnicodeScalarView.Index
) -> Bool {
return lhs._position < rhs._position
}
extension String {
/// A collection of [Unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value) that
/// encodes a `String` value.
public struct UnicodeScalarView : Collection, CustomStringConvertible, CustomDebugStringConvertible {
internal init(_ _core: _StringCore) {
self._core = _core
}
internal struct _ScratchIterator : IteratorProtocol {
var core: _StringCore
var idx: Int
@_versioned
init(_ core: _StringCore, _ pos: Int) {
self.idx = pos
self.core = core
}
@inline(__always)
mutating func next() -> UTF16.CodeUnit? {
if idx == core.endIndex {
return nil
}
defer { idx += 1 }
return self.core[idx]
}
}
/// A position in a `String.UnicodeScalarView`.
public struct Index : BidirectionalIndex, Comparable {
public init(_ _position: Int, _ _core: _StringCore) {
self._position = _position
self._core = _core
}
/// Returns the next consecutive value after `self`.
///
/// - Precondition: The next value is representable.
@warn_unused_result
@inline(__always)
public func successor() -> Index {
var scratch = _ScratchIterator(_core, _position)
var decoder = UTF16()
let (_, length) = decoder._decodeOne(&scratch)
return Index(_position + length, _core)
}
/// Returns the previous consecutive value before `self`.
///
/// - Precondition: The previous value is representable.
@warn_unused_result
public func predecessor() -> Index {
var i = _position-1
let codeUnit = _core[i]
if _slowPath((codeUnit >> 10) == 0b1101_11) {
if i != 0 && (_core[i - 1] >> 10) == 0b1101_10 {
i -= 1
}
}
return Index(i, _core)
}
/// The end index that for this view.
internal var _viewStartIndex: Index {
return Index(_core.startIndex, _core)
}
/// The end index that for this view.
internal var _viewEndIndex: Index {
return Index(_core.endIndex, _core)
}
@_versioned internal var _position: Int
@_versioned internal var _core: _StringCore
}
/// The position of the first `UnicodeScalar` if the `String` is
/// non-empty; identical to `endIndex` otherwise.
public var startIndex: Index {
return Index(_core.startIndex, _core)
}
/// The "past the end" position.
///
/// `endIndex` is not a valid argument to `subscript`, and is always
/// reachable from `startIndex` by zero or more applications of
/// `successor()`.
public var endIndex: Index {
return Index(_core.endIndex, _core)
}
/// Access the element at `position`.
///
/// - Precondition: `position` is a valid position in `self` and
/// `position != endIndex`.
public subscript(position: Index) -> UnicodeScalar {
var scratch = _ScratchIterator(_core, position._position)
var decoder = UTF16()
switch decoder.decode(&scratch) {
case .scalarValue(let us):
return us
case .emptyInput:
_sanityCheckFailure("cannot subscript using an endIndex")
case .error:
return UnicodeScalar(0xfffd)
}
}
/// Access the contiguous subrange of elements enclosed by `bounds`.
///
/// - Complexity: O(1) unless bridging from Objective-C requires an
/// O(N) conversion.
public subscript(r: Range<Index>) -> UnicodeScalarView {
return UnicodeScalarView(
_core[r.startIndex._position..<r.endIndex._position])
}
/// A type whose instances can produce the elements of this
/// sequence, in order.
public struct Iterator : IteratorProtocol {
init(_ _base: _StringCore) {
if _base.hasContiguousStorage {
self._baseSet = true
if _base.isASCII {
self._ascii = true
self._asciiBase = UnsafeBufferPointer<UInt8>(
start: UnsafePointer(_base._baseAddress),
count: _base.count).makeIterator()
} else {
self._ascii = false
self._base = UnsafeBufferPointer<UInt16>(
start: UnsafePointer(_base._baseAddress),
count: _base.count).makeIterator()
}
} else {
self._ascii = false
self._baseSet = false
self._iterator = _base.makeIterator()
}
}
/// Advance to the next element and return it, or `nil` if no next
/// element exists.
///
/// - Precondition: No preceding call to `self.next()` has returned
/// `nil`.
public mutating func next() -> UnicodeScalar? {
var result: UnicodeDecodingResult
if _baseSet {
if _ascii {
switch self._asciiBase.next() {
case let x?:
result = .scalarValue(UnicodeScalar(x))
case nil:
result = .emptyInput
}
} else {
result = _decoder.decode(&(self._base!))
}
} else {
result = _decoder.decode(&(self._iterator!))
}
switch result {
case .scalarValue(let us):
return us
case .emptyInput:
return nil
case .error:
return UnicodeScalar(0xfffd)
}
}
internal var _decoder: UTF16 = UTF16()
internal let _baseSet: Bool
internal let _ascii: Bool
internal var _asciiBase: UnsafeBufferPointerIterator<UInt8>!
internal var _base: UnsafeBufferPointerIterator<UInt16>!
internal var _iterator: IndexingIterator<_StringCore>!
}
/// Returns an iterator over the `UnicodeScalar`s that comprise
/// this sequence.
///
/// - Complexity: O(1).
@warn_unused_result
public func makeIterator() -> Iterator {
return Iterator(_core)
}
public var description: String {
return String(_core[startIndex._position..<endIndex._position])
}
public var debugDescription: String {
return "StringUnicodeScalarView(\(self.description.debugDescription))"
}
internal var _core: _StringCore
}
/// Construct the `String` corresponding to the given sequence of
/// Unicode scalars.
public init(_ unicodeScalars: UnicodeScalarView) {
self.init(unicodeScalars._core)
}
/// The index type for subscripting a `String`'s `.unicodeScalars`
/// view.
public typealias UnicodeScalarIndex = UnicodeScalarView.Index
}
extension String {
/// The value of `self` as a collection of [Unicode scalar values](http://www.unicode.org/glossary/#unicode_scalar_value).
public var unicodeScalars : UnicodeScalarView {
get {
return UnicodeScalarView(_core)
}
set {
_core = newValue._core
}
}
}
extension String.UnicodeScalarView : RangeReplaceableCollection {
/// Construct an empty instance.
public init() {
self = String.UnicodeScalarView(_StringCore())
}
/// Reserve enough space to store `n` ASCII characters.
///
/// - Complexity: O(`n`).
public mutating func reserveCapacity(_ n: Int) {
_core.reserveCapacity(n)
}
/// Append `x` to `self`.
///
/// - Complexity: Amortized O(1).
public mutating func append(_ x: UnicodeScalar) {
_core.append(x)
}
/// Append the elements of `newElements` to `self`.
///
/// - Complexity: O(*length of result*).
public mutating func append<
S : Sequence where S.Iterator.Element == UnicodeScalar
>(contentsOf newElements: S) {
_core.append(contentsOf: newElements.lazy.flatMap { $0.utf16 })
}
/// Replace the elements within `bounds` with `newElements`.
///
/// Invalidates all indices with respect to `self`.
///
/// - Complexity: O(`bounds.count`) if `bounds.endIndex
/// == self.endIndex` and `newElements.isEmpty`, O(N) otherwise.
public mutating func replaceSubrange<
C: Collection where C.Iterator.Element == UnicodeScalar
>(
_ bounds: Range<Index>, with newElements: C
) {
let rawSubRange = bounds.startIndex._position
..< bounds.endIndex._position
let lazyUTF16 = newElements.lazy.flatMap { $0.utf16 }
_core.replaceSubrange(rawSubRange, with: lazyUTF16)
}
}
// Index conversions
extension String.UnicodeScalarIndex {
/// Construct the position in `unicodeScalars` that corresponds exactly to
/// `utf16Index`. If no such position exists, the result is `nil`.
///
/// - Precondition: `utf16Index` is an element of
/// `String(unicodeScalars).utf16.indices`.
public init?(
_ utf16Index: String.UTF16Index,
within unicodeScalars: String.UnicodeScalarView
) {
let utf16 = String.UTF16View(unicodeScalars._core)
if utf16Index != utf16.startIndex
&& utf16Index != utf16.endIndex {
_precondition(
utf16Index >= utf16.startIndex
&& utf16Index <= utf16.endIndex,
"Invalid String.UTF16Index for this UnicodeScalar view")
// Detect positions that have no corresponding index. Note that
// we have to check before and after, because an unpaired
// surrogate will be decoded as a single replacement character,
// thus making the corresponding position valid.
if UTF16.isTrailSurrogate(utf16[utf16Index])
&& UTF16.isLeadSurrogate(utf16[utf16Index.predecessor()]) {
return nil
}
}
self.init(utf16Index._offset, unicodeScalars._core)
}
/// Construct the position in `unicodeScalars` that corresponds exactly to
/// `utf8Index`. If no such position exists, the result is `nil`.
///
/// - Precondition: `utf8Index` is an element of
/// `String(unicodeScalars).utf8.indices`.
public init?(
_ utf8Index: String.UTF8Index,
within unicodeScalars: String.UnicodeScalarView
) {
let core = unicodeScalars._core
_precondition(
utf8Index._coreIndex >= 0 && utf8Index._coreIndex <= core.endIndex,
"Invalid String.UTF8Index for this UnicodeScalar view")
// Detect positions that have no corresponding index.
if !utf8Index._isOnUnicodeScalarBoundary {
return nil
}
self.init(utf8Index._coreIndex, core)
}
/// Construct the position in `unicodeScalars` that corresponds
/// exactly to `characterIndex`.
///
/// - Precondition: `characterIndex` is an element of
/// `String(unicodeScalars).indices`.
public init(
_ characterIndex: String.Index,
within unicodeScalars: String.UnicodeScalarView
) {
self.init(characterIndex._base._position, unicodeScalars._core)
}
/// Returns the position in `utf8` that corresponds exactly
/// to `self`.
///
/// - Precondition: `self` is an element of `String(utf8)!.indices`.
@warn_unused_result
public func samePosition(in utf8: String.UTF8View) -> String.UTF8View.Index {
return String.UTF8View.Index(self, within: utf8)
}
/// Returns the position in `utf16` that corresponds exactly
/// to `self`.
///
/// - Precondition: `self` is an element of `String(utf16)!.indices`.
@warn_unused_result
public func samePosition(
in utf16: String.UTF16View
) -> String.UTF16View.Index {
return String.UTF16View.Index(self, within: utf16)
}
/// Returns the position in `characters` that corresponds exactly
/// to `self`, or if no such position exists, `nil`.
///
/// - Precondition: `self` is an element of
/// `characters.unicodeScalars.indices`.
@warn_unused_result
public func samePosition(in characters: String) -> String.Index? {
return String.Index(self, within: characters)
}
internal var _isOnGraphemeClusterBoundary: Bool {
let scalars = String.UnicodeScalarView(_core)
if self == scalars.startIndex || self == scalars.endIndex {
return true
}
let precedingScalar = scalars[self.predecessor()]
let graphemeClusterBreakProperty =
_UnicodeGraphemeClusterBreakPropertyTrie()
let segmenter = _UnicodeExtendedGraphemeClusterSegmenter()
let gcb0 = graphemeClusterBreakProperty.getPropertyRawValue(
precedingScalar.value)
if segmenter.isBoundaryAfter(gcb0) {
return true
}
let gcb1 = graphemeClusterBreakProperty.getPropertyRawValue(
scalars[self].value)
return segmenter.isBoundary(gcb0, gcb1)
}
}
// Reflection
extension String.UnicodeScalarView : CustomReflectable {
/// Returns a mirror that reflects `self`.
public var customMirror: Mirror {
return Mirror(self, unlabeledChildren: self)
}
}
extension String.UnicodeScalarView : CustomPlaygroundQuickLookable {
public var customPlaygroundQuickLook: PlaygroundQuickLook {
return .text(description)
}
}
|
apache-2.0
|
fdf97beb37ce9736f44587b31bbb350b
| 30.847059 | 124 | 0.632139 | 4.450839 | false | false | false | false |
tomasharkema/HoelangTotTrein2.iOS
|
HoelangTotTrein2/View/AdvicesScrollView.swift
|
1
|
3273
|
//
// AdvicesScrollView.swift
// HoelangTotTrein2
//
// Created by Tomas Harkema on 14/10/2020.
// Copyright © 2020 Tomas Harkema. All rights reserved.
//
import API
import Foundation
import SwiftUI
struct AdvicesScrollView: View {
@EnvironmentObject var advices: VariableBindable<AdvicesAndRequest?>
@Binding var expanded: Bool
private func emptyState(size: CGSize) -> some View {
VStack(alignment: .center) {
Spacer()
HStack(alignment: .center) {
Spacer()
ActivityIndicator(isAnimating: .constant(true), style: UIActivityIndicatorView.Style.large)
Spacer()
}
.frame(width: size.width, height: size.height)
Spacer()
}
}
private func listView(size: CGSize) -> some View {
VStack(alignment: HorizontalAlignment.center) {
ForEach(self.advices.value?.advices ?? [], id: \.hashValue) { advice in
AdviceView(advice: advice, size: size)
.frame(width: size.width, height: size.height)
}
}
}
private func expandedList() -> some View {
GeometryReader { geometry in
ScrollView {
if (self.advices.value?.advices ?? []).isEmpty {
self.emptyState(size: geometry.size)
} else {
self.listView(size: geometry.size)
}
}
}
}
private func formattedString(_ departure: Date?) -> String? {
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
return departure.flatMap {
formatter.string(from: $0)
}
}
private func duration(_ duration: TimeInterval?) -> String? {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
formatter.unitsStyle = .abbreviated
return duration.flatMap {
formatter.string(from: $0)
}
}
private func collaspedListItem(advice: Advice) -> some View {
HStack(alignment: .top) {
VStack(alignment: .leading, spacing: 2) {
Ticker(date: advice.departure.actual, fontSize: 20, textAlignment: .left, fontWeight: .heavy)
HStack(spacing: 0) {
FareTimeView(fareTime: advice.departure)
.font(Font.footnote.weight(.light))
Text(verbatim: "–")
.font(Font.footnote.weight(.light))
FareTimeView(fareTime: advice.arrival)
.font(Font.footnote.weight(.light))
}
HStack {
Text(verbatim: "\(self.duration(advice.time) ?? "")")
.font(Font.footnote.weight(.light))
CrowdForecastView(crowdForecast: advice.crowdForecast)
}
}.padding()
CollapsedLegsView(legs: advice.legs).padding()
}.background(Color.black.opacity(0.2))
.listRowInsets(EdgeInsets(top: 0, leading: 0, bottom: 0, trailing: 0))
.listRowBackground(Color.clear)
}
private func collapsedList() -> some View {
Group {
if (self.advices.value?.advices ?? []).isEmpty {
GeometryReader { geometry in
self.emptyState(size: geometry.size)
}
} else {
List(advices.value?.advices ?? [], id: \.hashValue) {
self.collaspedListItem(advice: $0)
}
}
}
}
var body: some View {
VStack {
if expanded {
expandedList()
} else {
collapsedList()
}
}
}
}
|
mit
|
6a53373d4b4ff825b8d3e680ab7536d2
| 27.189655 | 101 | 0.612844 | 3.982948 | false | false | false | false |
xiaohaieryi/DYZB-YW
|
DYZB-YW/DYZB-YW/Classes/DYYHome/Controller/HomeViewController.swift
|
1
|
1773
|
//
// HomeViewController.swift
// DYZB-YW
//
// Created by 于武 on 2017/7/28.
// Copyright © 2017年 于武. All rights reserved.
//
import UIKit
class HomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupUI()
}
}
//设置UI界面
extension HomeViewController {
//private
func setupUI() {
//1.设置导航栏
setupNavigationBar()
}
//设置导航栏方法
private func setupNavigationBar(){
//1)设置左侧按钮
// let btn = UIButton()
// btn.setImage(UIImage(named:"logo"), for: .normal)
// btn.sizeToFit()
navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "logo")
//2)设置右侧按钮组
let size = CGSize(width: 40, height: 40)
//方法一 添加类方法
// let historyItem = UIBarButtonItem.creatItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
//let searchItem = UIBarButtonItem.creatItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
// let qrcodeItem = UIBarButtonItem.creatItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
//方法二 便利构造
let historyItem = UIBarButtonItem(imageName: "image_my_history", highImageName: "Image_my_history_click", size: size)
let searchItem = UIBarButtonItem(imageName: "btn_search", highImageName: "btn_search_clicked", size: size)
let qrcodeItem = UIBarButtonItem(imageName: "Image_scan", highImageName: "Image_scan_click", size: size)
navigationItem.rightBarButtonItems = [historyItem, searchItem,qrcodeItem]
}
}
|
mit
|
f919d65bbf08c3bc9ad03f5bb9862844
| 26.9 | 138 | 0.639785 | 4.259542 | false | false | false | false |
Alberto-Vega/SwiftCodeChallenges
|
BinaryTrees.playground/Sources/LinkedList.swift
|
1
|
4678
|
import Foundation
public class LinkedListNode<T> {
public var value: T?
public var next: LinkedListNode?
weak var previous: LinkedListNode?
public init(value: T) {
self.value = value
}
public init() {
self.value = nil
self.next = nil
}
}
public class LinkedList<T> {
public typealias Node = LinkedListNode<T>
fileprivate var head: Node?
public init() {}
public var isEmpty: Bool {
return head == nil
}
public var first: Node? {
return head
}
public var last: Node? {
if var node = head {
while case let next? = node.next {
node = next
}
return node
} else {
return nil
}
}
public var count: Int {
if var node = head {
var c = 1
while case let next? = node.next {
node = next
c += 1
}
return c
} else {
return 0
}
}
public func node(atIndex index: Int) -> Node? {
if index >= 0 {
var node = head
var i = index
while node != nil {
if i == 0 { return node }
i -= 1
node = node!.next
}
}
return nil
}
public subscript(index: Int) -> T {
let node = self.node(atIndex: index)
assert(node != nil)
return node!.value!
}
public func append(_ value: T) {
let newNode = Node(value: value)
if let lastNode = last {
newNode.previous = lastNode
lastNode.next = newNode
} else {
head = newNode
}
}
private func nodesBeforeAndAfter(index: Int) -> (Node?, Node?) {
assert(index >= 0)
var i = index
var next = head
var prev: Node?
while next != nil && i > 0 {
i -= 1
prev = next
next = next!.next
}
assert(i == 0) // if > 0, then specified index was too large
return (prev, next)
}
public func insert(_ value: T, atIndex index: Int) {
let (prev, next) = nodesBeforeAndAfter(index: index)
let newNode = Node(value: value)
newNode.previous = prev
newNode.next = next
prev?.next = newNode
next?.previous = newNode
if prev == nil {
head = newNode
}
}
public func removeAll() {
head = nil
}
public func remove(node: Node) -> T {
let prev = node.previous
let next = node.next
if let prev = prev {
prev.next = next
} else {
head = next
}
next?.previous = prev
node.previous = nil
node.next = nil
return node.value!
}
public func removeLast() -> T {
assert(!isEmpty)
return remove(node: last!)
}
public func remove(atIndex index: Int) -> T {
let node = self.node(atIndex: index)
assert(node != nil)
return remove(node: node!)
}
}
extension LinkedList: CustomStringConvertible {
public var description: String {
var s = "["
var node = head
while node != nil {
let value: String = node!.value as? String ?? ""
s += value
node = node!.next
if node != nil { s += ", " }
}
return s + "]"
}
}
extension LinkedList {
public func reverse() {
var node = head
while let currentNode = node {
node = currentNode.next
swap(¤tNode.next, ¤tNode.previous)
head = currentNode
}
}
}
extension LinkedList {
public func map<U>(transform: (T) -> U) -> LinkedList<U> {
let result = LinkedList<U>()
var node = head
while node != nil {
result.append(transform(node!.value!))
node = node!.next
}
return result
}
public func filter(predicate: (T) -> Bool) -> LinkedList<T> {
let result = LinkedList<T>()
var node = head
while node != nil {
if predicate(node!.value!) {
result.append(node!.value!)
}
node = node!.next
}
return result
}
}
extension LinkedList {
convenience init(array: Array<T>) {
self.init()
for element in array {
self.append(element)
}
}
}
|
mit
|
4c7113e65167311703227ec1c96932d5
| 21.819512 | 69 | 0.468149 | 4.555015 | false | false | false | false |
ckrey/mqttswift
|
Sources/MqttSubscription.swift
|
1
|
1790
|
//
// MqttSubscription.swift
// mqttswift
//
// Created by Christoph Krey on 20.09.17.
//
import Foundation
class MqttSubscription {
var topicFilter: String!
var subscribeOptions: UInt8 = 0
var qos: MqttQoS = MqttQoS.AtMostOnce
var noLocal: Bool = false
var retainHandling: MqttRetainHandling = MqttRetainHandling.SendRetained
var retainAsPublish: Bool = false
var subscriptionIdentifier: Int? = nil
init () {
}
init(topicFilter: String!,
qos: MqttQoS!,
noLocal: Bool!,
retainHandling: MqttRetainHandling!,
retainAsPublish: Bool!,
subscriptionIdentifier: Int?
) {
self.topicFilter = topicFilter
self.qos = qos
self.noLocal = noLocal
self.retainHandling = retainHandling
self.retainAsPublish = retainAsPublish
self.subscriptionIdentifier = subscriptionIdentifier
}
func isShared() -> Bool {
var topicFilterComponents = self.topicFilter.components(separatedBy: "/");
return topicFilterComponents.count >= 3 && topicFilterComponents[0] == "$share"
}
func shareName() -> String? {
var topicFilterComponents = self.topicFilter.components(separatedBy: "/");
if topicFilterComponents.count >= 3 && topicFilterComponents[0] == "$share" {
return topicFilterComponents[1]
}
return nil
}
func netTopicFilter() -> String {
var topicFilterComponents = self.topicFilter.components(separatedBy: "/");
if topicFilterComponents.count >= 3 && topicFilterComponents[0] == "$share" {
topicFilterComponents.removeFirst()
topicFilterComponents.removeFirst()
}
return topicFilterComponents.joined(separator:"/")
}
}
|
gpl-3.0
|
65dd4f46ab7ffff973ee7754d9787e2d
| 28.833333 | 87 | 0.646927 | 4.497487 | false | false | false | false |
suragch/Chimee-iOS
|
Chimee/AeiouKeyboard.swift
|
1
|
19133
|
import UIKit
class AeiouKeyboard: UIView, KeyboardKeyDelegate {
weak var delegate: KeyboardDelegate? // probably the view or keyboard controller
fileprivate let renderer = MongolUnicodeRenderer.sharedInstance
fileprivate var punctuationOn = false
fileprivate let nirugu = ScalarString(MongolUnicodeRenderer.Uni.MONGOLIAN_NIRUGU).toString()
fileprivate let fvs1 = ScalarString(MongolUnicodeRenderer.Uni.FVS1).toString()
fileprivate let fvs2 = ScalarString(MongolUnicodeRenderer.Uni.FVS2).toString()
fileprivate let fvs3 = ScalarString(MongolUnicodeRenderer.Uni.FVS3).toString()
fileprivate let mvs = ScalarString(MongolUnicodeRenderer.Uni.MVS).toString()
fileprivate let mongolA = ScalarString(MongolUnicodeRenderer.Uni.A).toString()
fileprivate let mongolE = ScalarString(MongolUnicodeRenderer.Uni.E).toString()
fileprivate let period = ScalarString(MongolUnicodeRenderer.Uni.MONGOLIAN_FULL_STOP).toString()
fileprivate let comma = ScalarString(MongolUnicodeRenderer.Uni.MONGOLIAN_COMMA).toString()
// Keyboard Keys
// Row 1
fileprivate let keyA = KeyboardTextKey()
fileprivate let keyE = KeyboardTextKey()
fileprivate let keyI = KeyboardTextKey()
fileprivate let keyO = KeyboardTextKey()
fileprivate let keyU = KeyboardTextKey()
// Row 2
fileprivate let keyNA = KeyboardTextKey()
fileprivate let keyBA = KeyboardTextKey()
fileprivate let keyQA = KeyboardTextKey()
fileprivate let keyGA = KeyboardTextKey()
fileprivate let keyMA = KeyboardTextKey()
fileprivate let keyLA = KeyboardTextKey()
// Row 3
fileprivate let keySA = KeyboardTextKey()
fileprivate let keyDA = KeyboardTextKey()
fileprivate let keyCHA = KeyboardTextKey()
fileprivate let keyJA = KeyboardTextKey()
fileprivate let keyYA = KeyboardTextKey()
fileprivate let keyRA = KeyboardTextKey()
// Row 4
fileprivate let keyFVS = KeyboardFvsKey()
fileprivate let keyMVS = KeyboardTextKey()
fileprivate let keyWA = KeyboardTextKey()
fileprivate let keyZA = KeyboardTextKey()
fileprivate let keySuffix = KeyboardTextKey()
fileprivate let keyBackspace = KeyboardImageKey()
// Row 5
fileprivate let keyKeyboard = KeyboardChooserKey()
fileprivate let keyComma = KeyboardTextKey()
fileprivate let keySpace = KeyboardImageKey()
fileprivate let keyQuestion = KeyboardTextKey()
fileprivate let keyReturn = KeyboardImageKey()
// MARK:- keyboard initialization
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
override init(frame: CGRect) {
super.init(frame: frame)
setup()
}
fileprivate func setup() {
addSubviews()
initializeNonChangingKeys()
setMongolKeyStrings()
assignDelegates()
}
fileprivate func addSubviews() {
// TableView
// Row 1
self.addSubview(keyA)
self.addSubview(keyE)
self.addSubview(keyI)
self.addSubview(keyO)
self.addSubview(keyU)
// Row 2
self.addSubview(keyNA)
self.addSubview(keyBA)
self.addSubview(keyQA)
self.addSubview(keyGA)
self.addSubview(keyMA)
self.addSubview(keyLA)
// Row 3
self.addSubview(keySA)
self.addSubview(keyDA)
self.addSubview(keyCHA)
self.addSubview(keyJA)
self.addSubview(keyYA)
self.addSubview(keyRA)
// Row 4
self.addSubview(keyFVS)
self.addSubview(keyMVS)
self.addSubview(keyWA)
self.addSubview(keyZA)
self.addSubview(keySuffix)
self.addSubview(keyBackspace)
// Row 5
self.addSubview(keyKeyboard)
self.addSubview(keyComma)
self.addSubview(keySpace)
self.addSubview(keyQuestion)
self.addSubview(keyReturn)
}
fileprivate func initializeNonChangingKeys() {
// Row 4
keyFVS.setStrings("", fvs2Top: "", fvs3Top: "", fvs1Bottom: "", fvs2Bottom: "", fvs3Bottom: "")
keyMVS.primaryString = "\u{180E}" // MVS
keyMVS.primaryStringDisplayOverride = " " // na ma ga
keyMVS.primaryStringFontSize = 11.0
keyMVS.secondaryString = "\u{200D}" // ZWJ
keyMVS.secondaryStringDisplayOverride = "" // TODO: make a better symbol
keySuffix.primaryString = "\u{202F}" // NNBS
keySuffix.primaryStringDisplayOverride = " " // yi du un
keySuffix.primaryStringFontSize = 11.0
keyBackspace.image = UIImage(named: "backspace_dark")
keyBackspace.keyType = KeyboardImageKey.KeyType.backspace
keyBackspace.repeatOnLongPress = true
// Row 5
keyKeyboard.image = UIImage(named: "keyboard_dark")
keyComma.primaryString = "\u{1802}" // mongol comma
keyComma.secondaryString = "\u{1803}" // mongol period
keySpace.primaryString = " "
keySpace.image = UIImage(named: "space_dark")
keySpace.repeatOnLongPress = true
keyQuestion.primaryString = "?"
keyQuestion.secondaryString = "!"
keyReturn.image = UIImage(named: "return_dark")
}
fileprivate func setMongolKeyStrings() {
// Row 1
keyA.primaryString = "ᠠ"
keyA.secondaryString = "᠊"
keyA.secondaryStringDisplayOverride = ""
keyE.primaryString = "ᠡ"
keyE.secondaryString = "ᠧ"
keyI.primaryString = "ᠢ"
keyI.secondaryString = ""
keyO.primaryString = "ᠤ"
keyO.primaryStringDisplayOverride = ""
keyO.secondaryString = "ᠣ"
keyU.primaryString = "ᠦ"
keyU.primaryStringDisplayOverride = ""
keyU.secondaryString = "ᠥ"
// Row 2
keyNA.primaryString = "ᠨ"
keyNA.secondaryString = "ᠩ"
keyBA.primaryString = "ᠪ"
keyBA.secondaryString = "ᠫ"
keyQA.primaryString = "ᠬ"
keyQA.secondaryString = "ᠾ"
keyGA.primaryString = "ᠭ"
keyGA.secondaryString = "ᠺ"
keyMA.primaryString = "ᠮ"
keyMA.secondaryString = ""
keyLA.primaryString = "ᠯ"
keyLA.secondaryString = "ᡀ"
// Row 3
keySA.primaryString = "ᠰ"
keySA.secondaryString = "ᠱ"
keyDA.primaryString = "ᠳ"
keyDA.secondaryString = "ᠲ"
keyCHA.primaryString = "ᠴ"
keyCHA.secondaryString = "ᡂ"
keyJA.primaryString = "ᠵ"
keyJA.secondaryString = "ᡁ"
keyYA.primaryString = "ᠶ"
keyYA.secondaryString = ""
keyRA.primaryString = "ᠷ"
keyRA.secondaryString = "ᠿ"
// Row 4
keyWA.primaryString = "ᠸ"
keyWA.secondaryString = "ᠹ"
keyZA.primaryString = "ᠽ"
keyZA.secondaryString = "ᠼ"
}
fileprivate func setPunctuationKeyStrings() {
// Row 1
keyA.primaryString = "("
keyA.secondaryString = "["
keyE.primaryString = ")"
keyE.secondaryString = "]"
keyI.primaryString = "«"
keyI.secondaryString = "<"
keyO.primaryString = "»"
keyO.secondaryString = ">"
keyU.primaryString = "·"
keyU.secondaryString = "᠁"
// Row 2
keyNA.primaryString = "1"
keyNA.secondaryString = "᠑"
keyBA.primaryString = "2"
keyBA.secondaryString = "᠒"
keyQA.primaryString = "3"
keyQA.secondaryString = "᠓"
keyGA.primaryString = "4"
keyGA.secondaryString = "᠔"
keyMA.primaryString = "5"
keyMA.secondaryString = "᠕"
keyLA.primaryString = "︱"
keyLA.secondaryString = "᠀"
// Row 3
keySA.primaryString = "6"
keySA.secondaryString = "᠖"
keyDA.primaryString = "7"
keyDA.secondaryString = "᠗"
keyCHA.primaryString = "8"
keyCHA.secondaryString = "᠘"
keyJA.primaryString = "9"
keyJA.secondaryString = "᠙"
keyYA.primaryString = "0"
keyYA.secondaryString = "᠐"
keyRA.primaryString = "."
keyRA.secondaryString = "᠅"
// Row 4
keyWA.primaryString = "⁈"
keyWA.secondaryString = "᠄"
keyZA.primaryString = "‼"
keyZA.secondaryString = ";"
}
fileprivate func assignDelegates() {
// Row 1
keyA.delegate = self
keyE.delegate = self
keyI.delegate = self
keyO.delegate = self
keyU.delegate = self
// Row 2
keyNA.delegate = self
keyBA.delegate = self
keyQA.delegate = self
keyGA.delegate = self
keyMA.delegate = self
keyLA.delegate = self
// Row 3
keySA.delegate = self
keyDA.delegate = self
keyCHA.delegate = self
keyJA.delegate = self
keyYA.delegate = self
keyRA.delegate = self
// Row 4
keyFVS.delegate = self
keyMVS.delegate = self
keyWA.delegate = self
keyZA.delegate = self
keySuffix.delegate = self
keyBackspace.delegate = self
// Row 5
keyKeyboard.delegate = self
keyComma.delegate = self
keySpace.delegate = self
keyQuestion.delegate = self
keyReturn.addTarget(self, action: #selector(keyReturnTapped), for: UIControlEvents.touchUpInside)
}
override func layoutSubviews() {
// TODO: - should add autolayout constraints instead
// | A | E | I | O | U | Row 1
// | N | B | Q | G | M | L | Row 2
// | S | D | Ch| J | Y | R | Row 3
// |fvs|mvs| W | Z |nbs|del| Row 4
// |123| . | space | ? |ret| Row 5
//let suggestionBarWidth: CGFloat = 30
let numberOfRows: CGFloat = 5
let keyUnitsInRow1: CGFloat = 5
let keyUnitsInRow2to5: CGFloat = 6
let rowHeight = self.bounds.height / numberOfRows
let row1KeyUnitWidth = self.bounds.width / keyUnitsInRow1
let row2to5KeyUnitWidth = self.bounds.width / keyUnitsInRow2to5
// Row 1
keyA.frame = CGRect(x: row1KeyUnitWidth*0, y: 0, width: row1KeyUnitWidth, height: rowHeight)
keyE.frame = CGRect(x: row1KeyUnitWidth*1, y: 0, width: row1KeyUnitWidth, height: rowHeight)
keyI.frame = CGRect(x: row1KeyUnitWidth*2, y: 0, width: row1KeyUnitWidth, height: rowHeight)
keyO.frame = CGRect(x: row1KeyUnitWidth*3, y: 0, width: row1KeyUnitWidth, height: rowHeight)
keyU.frame = CGRect(x: row1KeyUnitWidth*4, y: 0, width: row1KeyUnitWidth, height: rowHeight)
// Row 2
keyNA.frame = CGRect(x: row2to5KeyUnitWidth*0, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
keyBA.frame = CGRect(x: row2to5KeyUnitWidth*1, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
keyQA.frame = CGRect(x: row2to5KeyUnitWidth*2, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
keyGA.frame = CGRect(x: row2to5KeyUnitWidth*3, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
keyMA.frame = CGRect(x: row2to5KeyUnitWidth*4, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
keyLA.frame = CGRect(x: row2to5KeyUnitWidth*5, y: rowHeight, width: row2to5KeyUnitWidth, height: rowHeight)
// Row 3
keySA.frame = CGRect(x: row2to5KeyUnitWidth*0, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
keyDA.frame = CGRect(x: row2to5KeyUnitWidth*1, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
keyCHA.frame = CGRect(x: row2to5KeyUnitWidth*2, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
keyJA.frame = CGRect(x: row2to5KeyUnitWidth*3, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
keyYA.frame = CGRect(x: row2to5KeyUnitWidth*4, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
keyRA.frame = CGRect(x: row2to5KeyUnitWidth*5, y: rowHeight*2, width: row2to5KeyUnitWidth, height: rowHeight)
// Row 4
keyFVS.frame = CGRect(x: row2to5KeyUnitWidth*0, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
keyMVS.frame = CGRect(x: row2to5KeyUnitWidth*1, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
keyWA.frame = CGRect(x: row2to5KeyUnitWidth*2, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
keyZA.frame = CGRect(x: row2to5KeyUnitWidth*3, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
keySuffix.frame = CGRect(x: row2to5KeyUnitWidth*4, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
keyBackspace.frame = CGRect(x: row2to5KeyUnitWidth*5, y: rowHeight*3, width: row2to5KeyUnitWidth, height: rowHeight)
// Row 5
keyKeyboard.frame = CGRect(x: row2to5KeyUnitWidth*0, y: rowHeight*4, width: row2to5KeyUnitWidth, height: rowHeight)
keyComma.frame = CGRect(x: row2to5KeyUnitWidth*1, y: rowHeight*4, width: row2to5KeyUnitWidth, height: rowHeight)
keySpace.frame = CGRect(x: row2to5KeyUnitWidth*2, y: rowHeight*4, width: row2to5KeyUnitWidth*2, height: rowHeight)
keyQuestion.frame = CGRect(x: row2to5KeyUnitWidth*4, y: rowHeight*4, width: row2to5KeyUnitWidth, height: rowHeight)
keyReturn.frame = CGRect(x: row2to5KeyUnitWidth*5, y: rowHeight*4, width: row2to5KeyUnitWidth, height: rowHeight)
}
// MARK: - Other
func otherAvailableKeyboards(_ keyboardTypeAndName: [(KeyboardType, String)]) {
keyKeyboard.menuItems = keyboardTypeAndName
}
func updateFvsKey(_ previousChar: String?, currentChar: String) {
// get the last character (previousChar is not necessarily a single char)
var lastChar: UInt32 = 0
if let previous = previousChar {
for c in previous.unicodeScalars {
lastChar = c.value
}
}
// lookup the strings and update the key
if renderer.isMongolian(lastChar) { // Medial or Final
// Medial on top
var fvs1Top = ""
if let search = renderer.medialGlyphForUnicode(currentChar + fvs1) {
fvs1Top = search
}
var fvs2Top = ""
if let search = renderer.medialGlyphForUnicode(currentChar + fvs2) {
fvs2Top = search
}
var fvs3Top = ""
if let search = renderer.medialGlyphForUnicode(currentChar + fvs3) {
fvs3Top = search
}
// Final on bottom
var fvs1Bottom = ""
if let search = renderer.finalGlyphForUnicode(currentChar + fvs1) {
fvs1Bottom = search
}
var fvs2Bottom = ""
if let search = renderer.finalGlyphForUnicode(currentChar + fvs2) {
fvs2Bottom = search
}
var fvs3Bottom = ""
if let search = renderer.finalGlyphForUnicode(currentChar + fvs3) {
fvs3Bottom = search
}
keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom)
} else { // Initial or Isolate
// Initial on top
var fvs1Top = ""
if let search = renderer.initialGlyphForUnicode(currentChar + fvs1) {
fvs1Top = search
}
var fvs2Top = ""
if let search = renderer.initialGlyphForUnicode(currentChar + fvs2) {
fvs2Top = search
}
var fvs3Top = ""
if let search = renderer.initialGlyphForUnicode(currentChar + fvs3) {
fvs3Top = search
}
// Isolate on bottom
var fvs1Bottom = ""
if let search = renderer.isolateGlyphForUnicode(currentChar + fvs1) {
fvs1Bottom = search
}
var fvs2Bottom = ""
if let search = renderer.isolateGlyphForUnicode(currentChar + fvs2) {
fvs2Bottom = search
}
var fvs3Bottom = ""
if let search = renderer.isolateGlyphForUnicode(currentChar + fvs3) {
fvs3Bottom = search
}
keyFVS.setStrings(fvs1Top, fvs2Top: fvs2Top, fvs3Top: fvs3Top, fvs1Bottom: fvs1Bottom, fvs2Bottom: fvs2Bottom, fvs3Bottom: fvs3Bottom)
}
}
// FIXME: Type Baina space Jirguga, highlight Jirguga, type something else.
// MARK: - KeyboardKeyDelegate protocol
func keyTextEntered(_ keyText: String) {
if keyText == mvs {
keyMvsTapped()
return
}
let previousChar = self.delegate?.charBeforeCursor()
updateFvsKey(previousChar, currentChar: keyText)
self.delegate?.keyWasTapped(keyText)
}
func keyBackspaceTapped() {
self.delegate?.keyBackspace()
clearFvsKey()
}
func keyReturnTapped() {
self.delegate?.keyWasTapped("\n")
clearFvsKey()
}
func keyMvsTapped() {
// add mvs + A or E (depending on word gender) + space
if let word = delegate?.twoMongolWordsBeforeCursor().0 {
if renderer.isFeminineWord(ScalarString(word)) {
self.delegate?.keyWasTapped(mvs + mongolE)
} else { // masculine
// neutur words default to masculine (for q/g diferentialtion)
// TODO: let user choose for masculine (or use database lookup)
self.delegate?.keyWasTapped(mvs + mongolA)
}
}
clearFvsKey()
}
func clearFvsKey() {
keyFVS.setStrings("", fvs2Top: "", fvs3Top: "", fvs1Bottom: "", fvs2Bottom: "", fvs3Bottom: "")
}
func keyFvsTapped(_ fvs: String) {
self.delegate?.keyWasTapped(fvs)
}
func keyKeyboardTapped() {
// switch punctuation
punctuationOn = !punctuationOn
if punctuationOn {
setPunctuationKeyStrings()
} else {
setMongolKeyStrings()
}
clearFvsKey()
}
// tell the view controller to switch keyboards
func keyNewKeyboardChosen(_ type: KeyboardType) {
delegate?.keyNewKeyboardChosen(type)
clearFvsKey()
}
}
|
mit
|
f874e599f64e648a8a34b4d851ea53ee
| 34.890359 | 146 | 0.597019 | 3.950479 | false | false | false | false |
iPrysyazhnyuk/SwiftNetworker
|
Example/SwiftNetworker/Controller/ViewController.swift
|
1
|
3571
|
//
// ViewController.swift
// SwiftNetworker
//
// Created by Igor Prysyazhnyuk on 10/15/2017.
// Copyright (c) 2017 Igor Prysyazhnyuk. All rights reserved.
//
import UIKit
import SwiftNetworker
import RxSwift
class ViewController: UIViewController {
private let disposeBag = DisposeBag()
private let userNickname = "git"
override func viewDidLoad() {
super.viewDidLoad()
getUserInfoSimplified()
getUserInfo()
getUserInfoWithoutRouterAndJSONParsing()
getUserInfoRx()
getUserRepositoriesSimplified()
updateUserInfoWithoutResponseHandling()
}
/// Get only User object without status code, JSON dictionary for success response
private func getUserInfoSimplified() {
GitHubRouter
.getUserDetails(nickname: userNickname)
.requestMappable(onSuccess: { (user: User) in
print("success getUserInfoSimplified, user name: \(user.name)")
}) { (error) in
let networkerError = error.networkerError
if let statusCode = networkerError?.statusCode {
print("failure status code: \(statusCode)")
}
if let json = networkerError?.info {
print("failure json: \(json)")
}
}
}
private func getUserInfo() {
GitHubRouter
.getUserDetails(nickname: userNickname)
.requestMappable { (result: NetworkerMappableResult<User>) in
switch result {
case .success(let response):
print("success getUserInfo, user name: \(response.object.name), status code: \(response.statusCode)")
case .failure(let error):
print(error.localizedDescription)
}
}
}
private func getUserInfoWithoutRouterAndJSONParsing() {
Networker.requestJSON(url: "https://api.github.com/users/git",
method: .get,
onSuccess: { (json, statusCode) in
print("success getUserInfoWithoutRouterAndJSONParsing, json: \(json)")
}) { (error) in
print(error.localizedDescription)
}
}
private func getUserInfoRx() {
GitHubRouter
.getUserDetails(nickname: "git")
.requestMappableRx()
.subscribe(onNext: { (result: NetworkerMappableResult<User>) in
switch result {
case .success(let response):
print("success getUserInfoRx, user name: \(response.object.name), status code: \(response.statusCode)")
case .failure(let error):
print(error.localizedDescription)
}
})
.addDisposableTo(disposeBag)
}
private func getUserRepositoriesSimplified() {
GitHubRouter
.getUserRepositories(ownerNickname: userNickname)
.requestMappable(onSuccess: { (repositories: ArrayResponse<Repository>) in
let reposNames = repositories.array.map { $0.name }
print("success getUserRepositoriesSimplified, repository names: \(reposNames)")
}, onError: { (error) in
print(error.localizedDescription)
})
}
private func updateUserInfoWithoutResponseHandling() {
GitHubRouter
.updateUser(name: "new name",
email: "[email protected]")
.request()
}
}
|
mit
|
75321c4ec5d91e5eea53645cfdf66b59
| 34.71 | 123 | 0.576029 | 5.190407 | false | false | false | false |
schibo/AI
|
GeneticAlgorithmStringMatch/GeneticAlgorithmStringMatch/GeneticAlgorithm.swift
|
1
|
5554
|
//
// GeneticAlgorithm.swift
// GeneticAlgorithmStringMatch
//
// Created by Joel Middendorf on 2/19/17.
// Copyright © 2017 Joel Middendorf. All rights reserved.
//
// Uses a genetic algorithm to match a string seeded with a population
// of random strings.
// 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
class GeneticAlgorithm {
var targetString = ""
var mutationRate = 0.9
init(_ stringValue: String) {
targetString = stringValue
}
func mutate(_ stringSequence: String) -> String {
let characterCount = UInt32(stringSequence.characters.count)
let randomOffset = arc4random_uniform(characterCount)
let range = NSRange(location: Int(randomOffset), length: 1 )
let randomPrintableAsciiCharacter = Character(UnicodeScalar(32 + arc4random_uniform(127-32))!)
var newSequence: NSString = stringSequence as NSString
newSequence = newSequence.replacingCharacters(in: range,
with: String(randomPrintableAsciiCharacter)) as NSString
return newSequence as String
}
func numCharsCorrect(string: NSString, targetString: NSString) -> Int {
var numCorrect = 0
for k in 0 ..< string.length {
numCorrect += string.character(at: k) == targetString.character(at: k) ? 1 : 0
}
return numCorrect
}
func isMoreFitThanAncestor(_ currentIndex: Int, population: [DNA], ancestorPopulation: [DNA]) -> (isMoreFit: Bool, distance: Int) {
let parentString = ancestorPopulation[currentIndex].stringSequence
let childString = population[currentIndex].stringSequence
let distanceOfParentString = numCharsCorrect(string: parentString as NSString, targetString: targetString as NSString)
let distanceOfChildString = numCharsCorrect(string: childString as NSString, targetString: targetString as NSString)
return (distanceOfParentString < distanceOfChildString) ? (true, distanceOfChildString) : (false, distanceOfChildString)
}
func replaceAncestor(_ currentIndex: Int, population: [DNA], ancestorPopulation: inout [DNA]) {
//swap the data
ancestorPopulation[currentIndex].stringSequence = population[currentIndex].stringSequence
}
/// Replace each ancestor at index k if and only if that child
/// is more fit than the ancestor at index k
///
/// - Parameters:
/// - population: the descendant population
/// - ancestorPopulation: the older generation
/// - Returns: a printable string of the most fit person
func analyzeGeneration(population: [DNA], ancestorPopulation: inout [DNA]) -> String {
var lowestDistanceSoFar = Int.max
var bestFitIndex = 0
for currentIndex in 0 ..< population.endIndex {
let result = isMoreFitThanAncestor(currentIndex, population: population, ancestorPopulation: ancestorPopulation)
if result.isMoreFit {
if result.distance < lowestDistanceSoFar {
lowestDistanceSoFar = result.distance
bestFitIndex = currentIndex
}
replaceAncestor(currentIndex, population: population, ancestorPopulation: &ancestorPopulation)
}
}
return ancestorPopulation[bestFitIndex].stringSequence
}
func createNextGeneration(population: [DNA], ancestorPopulation: [DNA]) {
for k in 0 ..< population.count {
reproduce(k, population: population, ancestorPopulation: ancestorPopulation)
}
}
func reproduce(_ parentIndex: Int, population: [DNA], ancestorPopulation: [DNA]) {
/// Crossover (totally random..no mating pool)
let fatherIndex = Int(arc4random_uniform(UInt32(ancestorPopulation.count)))
var motherIndex = Int(arc4random_uniform(UInt32(ancestorPopulation.count)))
/// Don't allow for asexual reproduction
if fatherIndex == motherIndex {
motherIndex = ancestorPopulation.count - motherIndex - 1
}
let fathersStringSequence = ancestorPopulation[fatherIndex].stringSequence
let randomMotherStr = ancestorPopulation[motherIndex].stringSequence
var index = fathersStringSequence.index(fathersStringSequence.startIndex, offsetBy: fathersStringSequence.characters.count / 2)
var concatString = fathersStringSequence.substring(to: index)
index = randomMotherStr.index(randomMotherStr.startIndex, offsetBy: randomMotherStr.characters.count / 2)
concatString += randomMotherStr.substring(from: index)
let newChild = population[parentIndex]
if arc4random_uniform(100) <= UInt32(mutationRate * 100) {
newChild.stringSequence = mutate(concatString)
} else {
newChild.stringSequence = concatString
}
}
}
|
gpl-3.0
|
238387f7bcc94ed4a88f206484f1a2d6
| 44.146341 | 135 | 0.680533 | 4.686076 | false | false | false | false |
y16ra/CookieCrunch
|
CookieCrunch/Extensions.swift
|
1
|
1620
|
//
// Extensions.swift
// CookieCrunch
//
// Created by Ichimura Yuichi on 2015/07/31.
// Copyright (c) 2015年 Ichimura Yuichi. All rights reserved.
//
import Foundation
extension Dictionary {
static func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? {
if let path = NSBundle.mainBundle().pathForResource(filename, ofType: "json") {
var error: NSError?
let data: NSData?
do {
data = try NSData(contentsOfFile: path, options: NSDataReadingOptions())
} catch let error1 as NSError {
error = error1
data = nil
}
if let data = data {
let dictionary: AnyObject?
do {
dictionary = try NSJSONSerialization.JSONObjectWithData(data,
options: NSJSONReadingOptions())
} catch let error1 as NSError {
error = error1
dictionary = nil
}
if let dictionary = dictionary as? Dictionary<String, AnyObject> {
return dictionary
} else {
print("Level file '\(filename)' is not valid JSON: \(error!)")
return nil
}
} else {
print("Could not load level file: \(filename), error: \(error!)")
return nil
}
} else {
print("Could not find level file: \(filename)")
return nil
}
}
}
|
mit
|
967d3144af052509defe301bc0aeb19e
| 32.729167 | 88 | 0.487021 | 5.57931 | false | false | false | false |
shorlander/firefox-ios
|
Client/Frontend/Browser/SearchViewController.swift
|
2
|
33061
|
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
import UIKit
import Shared
import Storage
import Telemetry
private let PromptMessage = NSLocalizedString("Turn on search suggestions?", tableName: "Search", comment: "Prompt shown before enabling provider search queries")
private let PromptYes = NSLocalizedString("Yes", tableName: "Search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private let PromptNo = NSLocalizedString("No", tableName: "Search", comment: "For search suggestions prompt. This string should be short so it fits nicely on the prompt row.")
private enum SearchListSection: Int {
case searchSuggestions
case bookmarksAndHistory
static let Count = 2
}
private struct SearchViewControllerUX {
static let SearchEngineScrollViewBackgroundColor = UIColor.white.withAlphaComponent(0.8).cgColor
static let SearchEngineScrollViewBorderColor = UIColor.black.withAlphaComponent(0.2).cgColor
// TODO: This should use ToolbarHeight in BVC. Fix this when we create a shared theming file.
static let EngineButtonHeight: Float = 44
static let EngineButtonWidth = EngineButtonHeight * 1.4
static let EngineButtonBackgroundColor = UIColor.clear.cgColor
static let SearchImage = "search"
static let SearchEngineTopBorderWidth = 0.5
static let SearchImageHeight: Float = 44
static let SearchImageWidth: Float = 24
static let SuggestionBackgroundColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.8)
static let SuggestionBorderColor = UIConstants.HighlightBlue
static let SuggestionBorderWidth: CGFloat = 1
static let SuggestionCornerRadius: CGFloat = 4
static let SuggestionInsets = UIEdgeInsets(top: 8, left: 8, bottom: 8, right: 8)
static let SuggestionMargin: CGFloat = 8
static let SuggestionCellVerticalPadding: CGFloat = 10
static let SuggestionCellMaxRows = 2
static let PromptColor = UIConstants.PanelBackgroundColor
static let PromptFont = UIFont.systemFont(ofSize: 12, weight: UIFontWeightRegular)
static let PromptYesFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightBold)
static let PromptNoFont = UIFont.systemFont(ofSize: 15, weight: UIFontWeightRegular)
static let PromptInsets = UIEdgeInsets(top: 15, left: 12, bottom: 15, right: 12)
static let PromptButtonColor = UIColor(rgb: 0x007aff)
static let IconSize: CGFloat = 23
static let IconBorderColor = UIColor(white: 0, alpha: 0.1)
static let IconBorderWidth: CGFloat = 0.5
}
protocol SearchViewControllerDelegate: class {
func searchViewController(_ searchViewController: SearchViewController, didSelectURL url: URL)
func presentSearchSettingsController()
}
class SearchViewController: SiteTableViewController, KeyboardHelperDelegate, LoaderListener {
var searchDelegate: SearchViewControllerDelegate?
fileprivate let isPrivate: Bool
fileprivate var suggestClient: SearchSuggestClient?
// Views for displaying the bottom scrollable search engine list. searchEngineScrollView is the
// scrollable container; searchEngineScrollViewContent contains the actual set of search engine buttons.
fileprivate let searchEngineScrollView = ButtonScrollView()
fileprivate let searchEngineScrollViewContent = UIView()
fileprivate lazy var bookmarkedBadge: UIImage = {
return UIImage(named: "bookmarked_passive")!
}()
// Cell for the suggestion flow layout. Since heightForHeaderInSection is called *before*
// cellForRowAtIndexPath, we create the cell to find its height before it's added to the table.
fileprivate let suggestionCell = SuggestionCell(style: UITableViewCellStyle.default, reuseIdentifier: nil)
fileprivate var suggestionPrompt: UIView?
static var userAgent: String?
init(isPrivate: Bool) {
self.isPrivate = isPrivate
super.init(nibName: nil, bundle: nil)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
view.backgroundColor = UIConstants.PanelBackgroundColor
let blur = UIVisualEffectView(effect: UIBlurEffect(style: UIBlurEffectStyle.light))
view.addSubview(blur)
super.viewDidLoad()
KeyboardHelper.defaultHelper.addDelegate(self)
searchEngineScrollView.layer.backgroundColor = SearchViewControllerUX.SearchEngineScrollViewBackgroundColor
searchEngineScrollView.layer.shadowRadius = 0
searchEngineScrollView.layer.shadowOpacity = 100
searchEngineScrollView.layer.shadowOffset = CGSize(width: 0, height: -SearchViewControllerUX.SearchEngineTopBorderWidth)
searchEngineScrollView.layer.shadowColor = SearchViewControllerUX.SearchEngineScrollViewBorderColor
searchEngineScrollView.clipsToBounds = false
searchEngineScrollView.decelerationRate = UIScrollViewDecelerationRateFast
view.addSubview(searchEngineScrollView)
searchEngineScrollViewContent.layer.backgroundColor = UIColor.clear.cgColor
searchEngineScrollView.addSubview(searchEngineScrollViewContent)
layoutTable()
layoutSearchEngineScrollView()
searchEngineScrollViewContent.snp.makeConstraints { make in
make.center.equalTo(self.searchEngineScrollView).priority(10)
//left-align the engines on iphones, center on ipad
if UIScreen.main.traitCollection.horizontalSizeClass == .compact {
make.left.equalTo(self.searchEngineScrollView).priority(1000)
} else {
make.left.greaterThanOrEqualTo(self.searchEngineScrollView).priority(1000)
}
make.right.lessThanOrEqualTo(self.searchEngineScrollView).priority(1000)
make.top.equalTo(self.searchEngineScrollView)
make.bottom.equalTo(self.searchEngineScrollView)
}
blur.snp.makeConstraints { make in
make.edges.equalTo(self.view)
}
suggestionCell.delegate = self
NotificationCenter.default.addObserver(self, selector: #selector(SearchViewController.SELDynamicFontChanged(_:)), name: NotificationDynamicFontChanged, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self, name: NotificationDynamicFontChanged, object: nil)
}
func SELDynamicFontChanged(_ notification: Notification) {
guard notification.name == NotificationDynamicFontChanged else { return }
reloadData()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
reloadSearchEngines()
reloadData()
}
fileprivate func layoutSearchEngineScrollView() {
let keyboardHeight = KeyboardHelper.defaultHelper.currentState?.intersectionHeightForView(self.view) ?? 0
searchEngineScrollView.snp.remakeConstraints { make in
make.left.right.equalTo(self.view)
make.bottom.equalTo(self.view).offset(-keyboardHeight)
}
}
var searchEngines: SearchEngines! {
didSet {
suggestClient?.cancelPendingRequest()
// Query and reload the table with new search suggestions.
querySuggestClient()
// Show the default search engine first.
if !isPrivate {
let ua = SearchViewController.userAgent as String! ?? "FxSearch"
suggestClient = SearchSuggestClient(searchEngine: searchEngines.defaultEngine, userAgent: ua)
}
// Reload the footer list of search engines.
reloadSearchEngines()
layoutSuggestionsOptInPrompt()
}
}
fileprivate var quickSearchEngines: [OpenSearchEngine] {
var engines = searchEngines.quickSearchEngines
// If we're not showing search suggestions, the default search engine won't be visible
// at the top of the table. Show it with the others in the bottom search bar.
if isPrivate || !searchEngines.shouldShowSearchSuggestions {
engines?.insert(searchEngines.defaultEngine, at: 0)
}
return engines!
}
fileprivate func layoutSuggestionsOptInPrompt() {
if isPrivate || !(searchEngines?.shouldShowSearchSuggestionsOptIn ?? false) {
// Make sure any pending layouts are drawn so they don't get coupled
// with the "slide up" animation below.
view.layoutIfNeeded()
// Set the prompt to nil so layoutTable() aligns the top of the table
// to the top of the view. We still need a reference to the prompt so
// we can remove it from the controller after the animation is done.
let prompt = suggestionPrompt
suggestionPrompt = nil
layoutTable()
UIView.animate(withDuration: 0.2,
animations: {
self.view.layoutIfNeeded()
prompt?.alpha = 0
},
completion: { _ in
prompt?.removeFromSuperview()
return
})
return
}
let prompt = UIView()
prompt.backgroundColor = SearchViewControllerUX.PromptColor
let promptBottomBorder = UIView()
promptBottomBorder.backgroundColor = UIColor.black.withAlphaComponent(0.1)
prompt.addSubview(promptBottomBorder)
// Insert behind the tableView so the tableView slides on top of it
// when the prompt is dismissed.
view.insertSubview(prompt, belowSubview: tableView)
suggestionPrompt = prompt
let promptImage = UIImageView()
promptImage.image = UIImage(named: SearchViewControllerUX.SearchImage)
prompt.addSubview(promptImage)
let promptLabel = UILabel()
promptLabel.text = PromptMessage
promptLabel.font = SearchViewControllerUX.PromptFont
promptLabel.numberOfLines = 0
promptLabel.lineBreakMode = NSLineBreakMode.byWordWrapping
prompt.addSubview(promptLabel)
let promptYesButton = InsetButton()
promptYesButton.setTitle(PromptYes, for: UIControlState())
promptYesButton.setTitleColor(SearchViewControllerUX.PromptButtonColor, for: UIControlState.normal)
promptYesButton.titleLabel?.font = SearchViewControllerUX.PromptYesFont
promptYesButton.titleEdgeInsets = SearchViewControllerUX.PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptYesButton.setContentCompressionResistancePriority(1000, for: UILayoutConstraintAxis.horizontal)
promptYesButton.addTarget(self, action: #selector(SearchViewController.SELdidClickOptInYes), for: UIControlEvents.touchUpInside)
prompt.addSubview(promptYesButton)
let promptNoButton = InsetButton()
promptNoButton.setTitle(PromptNo, for: UIControlState())
promptNoButton.setTitleColor(SearchViewControllerUX.PromptButtonColor, for: UIControlState.normal)
promptNoButton.titleLabel?.font = SearchViewControllerUX.PromptNoFont
promptNoButton.titleEdgeInsets = SearchViewControllerUX.PromptInsets
// If the prompt message doesn't fit, this prevents it from pushing the buttons
// off the row and makes it wrap instead.
promptNoButton.setContentCompressionResistancePriority(1000, for: UILayoutConstraintAxis.horizontal)
promptNoButton.addTarget(self, action: #selector(SearchViewController.SELdidClickOptInNo), for: UIControlEvents.touchUpInside)
prompt.addSubview(promptNoButton)
// otherwise the label (i.e. question) is visited by VoiceOver *after* yes and no buttons
prompt.accessibilityElements = [promptImage, promptLabel, promptYesButton, promptNoButton]
promptImage.snp.makeConstraints { make in
make.left.equalTo(prompt).offset(SearchViewControllerUX.PromptInsets.left)
make.centerY.equalTo(prompt)
}
promptLabel.snp.makeConstraints { make in
make.left.equalTo(promptImage.snp.right).offset(SearchViewControllerUX.PromptInsets.left)
let insets = SearchViewControllerUX.PromptInsets
make.top.equalTo(prompt).inset(insets.top)
make.bottom.equalTo(prompt).inset(insets.bottom)
make.right.lessThanOrEqualTo(promptYesButton.snp.left)
return
}
promptNoButton.snp.makeConstraints { make in
make.right.equalTo(prompt).inset(SearchViewControllerUX.PromptInsets.right)
make.centerY.equalTo(prompt)
}
promptYesButton.snp.makeConstraints { make in
make.right.equalTo(promptNoButton.snp.left).inset(SearchViewControllerUX.PromptInsets.right)
make.centerY.equalTo(prompt)
}
promptBottomBorder.snp.makeConstraints { make in
make.trailing.leading.equalTo(self.view)
make.top.equalTo(prompt.snp.bottom).offset(-1)
make.height.equalTo(1)
}
prompt.snp.makeConstraints { make in
make.top.leading.trailing.equalTo(self.view)
}
layoutTable()
}
var searchQuery: String = "" {
didSet {
// Reload the tableView to show the updated text in each engine.
reloadData()
}
}
override func reloadData() {
querySuggestClient()
}
fileprivate func layoutTable() {
tableView.snp.remakeConstraints { make in
make.top.equalTo(self.suggestionPrompt?.snp.bottom ?? self.view.snp.top)
make.leading.trailing.equalTo(self.view)
make.bottom.equalTo(self.searchEngineScrollView.snp.top)
}
}
fileprivate func reloadSearchEngines() {
searchEngineScrollViewContent.subviews.forEach { $0.removeFromSuperview() }
var leftEdge = searchEngineScrollViewContent.snp.left
//search settings icon
let searchButton = UIButton()
searchButton.setImage(UIImage(named: "quickSearch"), for: UIControlState())
searchButton.imageView?.contentMode = UIViewContentMode.center
searchButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor
searchButton.addTarget(self, action: #selector(SearchViewController.SELdidClickSearchButton), for: UIControlEvents.touchUpInside)
searchButton.accessibilityLabel = String(format: NSLocalizedString("Search Settings", tableName: "Search", comment: "Label for search settings button."))
searchButton.imageView?.snp.makeConstraints { make in
make.width.height.equalTo(SearchViewControllerUX.SearchImageWidth)
return
}
searchEngineScrollViewContent.addSubview(searchButton)
searchButton.snp.makeConstraints { make in
make.width.equalTo(SearchViewControllerUX.SearchImageWidth)
make.height.equalTo(SearchViewControllerUX.SearchImageHeight)
//offset the left edge to align with search results
make.left.equalTo(leftEdge).offset(SearchViewControllerUX.PromptInsets.left)
make.top.equalTo(self.searchEngineScrollViewContent)
make.bottom.equalTo(self.searchEngineScrollViewContent)
}
//search engines
leftEdge = searchButton.snp.right
for engine in quickSearchEngines {
let engineButton = UIButton()
engineButton.setImage(engine.image, for: UIControlState())
engineButton.imageView?.contentMode = UIViewContentMode.scaleAspectFit
engineButton.layer.backgroundColor = SearchViewControllerUX.EngineButtonBackgroundColor
engineButton.addTarget(self, action: #selector(SearchViewController.SELdidSelectEngine(_:)), for: UIControlEvents.touchUpInside)
engineButton.accessibilityLabel = String(format: NSLocalizedString("%@ search", tableName: "Search", comment: "Label for search engine buttons. The argument corresponds to the name of the search engine."), engine.shortName)
engineButton.imageView?.snp.makeConstraints { make in
make.width.height.equalTo(OpenSearchEngine.PreferredIconSize)
return
}
searchEngineScrollViewContent.addSubview(engineButton)
engineButton.snp.makeConstraints { make in
make.width.equalTo(SearchViewControllerUX.EngineButtonWidth)
make.height.equalTo(SearchViewControllerUX.EngineButtonHeight)
make.left.equalTo(leftEdge)
make.top.equalTo(self.searchEngineScrollViewContent)
make.bottom.equalTo(self.searchEngineScrollViewContent)
if engine === self.searchEngines.quickSearchEngines.last {
make.right.equalTo(self.searchEngineScrollViewContent)
}
}
leftEdge = engineButton.snp.right
}
}
func SELdidSelectEngine(_ sender: UIButton) {
// The UIButtons are the same cardinality and order as the array of quick search engines.
// Subtract 1 from index to account for magnifying glass accessory.
guard let index = searchEngineScrollViewContent.subviews.index(of: sender) else {
assertionFailure()
return
}
let engine = quickSearchEngines[index - 1]
guard let url = engine.searchURLForQuery(searchQuery) else {
assertionFailure()
return
}
Telemetry.recordEvent(SearchTelemetry.makeEvent(engine, source: .QuickSearch))
searchDelegate?.searchViewController(self, didSelectURL: url)
}
func SELdidClickSearchButton() {
self.searchDelegate?.presentSearchSettingsController()
}
func SELdidClickOptInYes() {
searchEngines.shouldShowSearchSuggestions = true
searchEngines.shouldShowSearchSuggestionsOptIn = false
querySuggestClient()
layoutSuggestionsOptInPrompt()
reloadSearchEngines()
}
func SELdidClickOptInNo() {
searchEngines.shouldShowSearchSuggestions = false
searchEngines.shouldShowSearchSuggestionsOptIn = false
layoutSuggestionsOptInPrompt()
reloadSearchEngines()
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillShowWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardDidShowWithState state: KeyboardState) {
}
func keyboardHelper(_ keyboardHelper: KeyboardHelper, keyboardWillHideWithState state: KeyboardState) {
animateSearchEnginesWithKeyboard(state)
}
override func viewWillTransition(to size: CGSize, with coordinator: UIViewControllerTransitionCoordinator) {
super.viewWillTransition(to: size, with: coordinator)
// The height of the suggestions row may change, so call reloadData() to recalculate cell heights.
coordinator.animate(alongsideTransition: { _ in
self.tableView.reloadData()
}, completion: nil)
}
fileprivate func animateSearchEnginesWithKeyboard(_ keyboardState: KeyboardState) {
layoutSearchEngineScrollView()
UIView.animate(withDuration: keyboardState.animationDuration, animations: {
UIView.setAnimationCurve(keyboardState.animationCurve)
self.view.layoutIfNeeded()
})
}
fileprivate func querySuggestClient() {
suggestClient?.cancelPendingRequest()
if searchQuery.isEmpty || !searchEngines.shouldShowSearchSuggestions || searchQuery.looksLikeAURL() {
suggestionCell.suggestions = []
tableView.reloadData()
return
}
suggestClient?.query(searchQuery, callback: { suggestions, error in
if let error = error {
let isSuggestClientError = error.domain == SearchSuggestClientErrorDomain
switch error.code {
case NSURLErrorCancelled where error.domain == NSURLErrorDomain:
// Request was cancelled. Do nothing.
break
case SearchSuggestClientErrorInvalidEngine where isSuggestClientError:
// Engine does not support search suggestions. Do nothing.
break
case SearchSuggestClientErrorInvalidResponse where isSuggestClientError:
print("Error: Invalid search suggestion data")
default:
print("Error: \(error.description)")
}
} else {
self.suggestionCell.suggestions = suggestions!
}
// If there are no suggestions, just use whatever the user typed.
if suggestions?.isEmpty ?? true {
self.suggestionCell.suggestions = [self.searchQuery]
}
// Reload the tableView to show the new list of search suggestions.
self.tableView.reloadData()
})
}
func loader(dataLoaded data: Cursor<Site>) {
self.data = data
tableView.reloadData()
}
func tableView(_ tableView: UITableView, didSelectRowAtIndexPath indexPath: IndexPath) {
let section = SearchListSection(rawValue: indexPath.section)!
if section == SearchListSection.bookmarksAndHistory {
if let site = data[indexPath.row] {
if let url = URL(string: site.url) {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
}
override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
if let currentSection = SearchListSection(rawValue: indexPath.section) {
switch currentSection {
case .searchSuggestions:
// heightForRowAtIndexPath is called *before* the cell is created, so to get the height,
// force a layout pass first.
suggestionCell.layoutIfNeeded()
return suggestionCell.frame.height
default:
return super.tableView(tableView, heightForRowAt: indexPath)
}
}
return 0
}
override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return 0
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
switch SearchListSection(rawValue: indexPath.section)! {
case .searchSuggestions:
suggestionCell.imageView?.image = searchEngines.defaultEngine.image
suggestionCell.imageView?.isAccessibilityElement = true
suggestionCell.imageView?.accessibilityLabel = String(format: NSLocalizedString("Search suggestions from %@", tableName: "Search", comment: "Accessibility label for image of default search engine displayed left to the actual search suggestions from the engine. The parameter substituted for \"%@\" is the name of the search engine. E.g.: Search suggestions from Google"), searchEngines.defaultEngine.shortName)
return suggestionCell
case .bookmarksAndHistory:
let cell = super.tableView(tableView, cellForRowAt: indexPath)
if let site = data[indexPath.row] {
if let cell = cell as? TwoLineTableViewCell {
let isBookmark = site.bookmarked ?? false
cell.setLines(site.title, detailText: site.url)
cell.setRightBadge(isBookmark ? self.bookmarkedBadge : nil)
cell.imageView!.layer.borderColor = SearchViewControllerUX.IconBorderColor.cgColor
cell.imageView!.layer.borderWidth = SearchViewControllerUX.IconBorderWidth
cell.imageView?.setIcon(site.icon, forURL: site.tileURL, completed: { (color, url) in
if site.tileURL == url {
cell.imageView?.image = cell.imageView?.image?.createScaled(CGSize(width: SearchViewControllerUX.IconSize, height: SearchViewControllerUX.IconSize))
cell.imageView?.contentMode = .center
cell.imageView?.backgroundColor = color
}
})
}
}
return cell
}
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch SearchListSection(rawValue: section)! {
case .searchSuggestions:
return searchEngines.shouldShowSearchSuggestions && !searchQuery.looksLikeAURL() && !isPrivate ? 1 : 0
case .bookmarksAndHistory:
return data.count
}
}
func numberOfSectionsInTableView(_ tableView: UITableView) -> Int {
return SearchListSection.Count
}
}
extension SearchViewController: SuggestionCellDelegate {
fileprivate func suggestionCell(_ suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String) {
// Assume that only the default search engine can provide search suggestions.
let engine = searchEngines.defaultEngine
var url = URIFixup.getURL(suggestion)
if url == nil {
url = engine.searchURLForQuery(suggestion)
}
Telemetry.recordEvent(SearchTelemetry.makeEvent(engine, source: .Suggestion))
if let url = url {
searchDelegate?.searchViewController(self, didSelectURL: url)
}
}
}
/**
* Private extension containing string operations specific to this view controller
*/
fileprivate extension String {
func looksLikeAURL() -> Bool {
// The assumption here is that if the user is typing in a forward slash and there are no spaces
// involved, it's going to be a URL. If we type a space, any url would be invalid.
// See https://bugzilla.mozilla.org/show_bug.cgi?id=1192155 for additional details.
return self.contains("/") && !self.contains(" ")
}
}
/**
* UIScrollView that prevents buttons from interfering with scroll.
*/
fileprivate class ButtonScrollView: UIScrollView {
fileprivate override func touchesShouldCancel(in view: UIView) -> Bool {
return true
}
}
fileprivate protocol SuggestionCellDelegate: class {
func suggestionCell(_ suggestionCell: SuggestionCell, didSelectSuggestion suggestion: String)
}
/**
* Cell that wraps a list of search suggestion buttons.
*/
fileprivate class SuggestionCell: UITableViewCell {
weak var delegate: SuggestionCellDelegate?
let container = UIView()
override init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
isAccessibilityElement = false
accessibilityLabel = nil
layoutMargins = UIEdgeInsets.zero
separatorInset = UIEdgeInsets.zero
selectionStyle = UITableViewCellSelectionStyle.none
container.backgroundColor = UIColor.clear
contentView.backgroundColor = UIColor.clear
backgroundColor = UIColor.clear
contentView.addSubview(container)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
var suggestions: [String] = [] {
didSet {
for view in container.subviews {
view.removeFromSuperview()
}
for suggestion in suggestions {
let button = SuggestionButton()
button.setTitle(suggestion, for: UIControlState())
button.addTarget(self, action: #selector(SuggestionCell.SELdidSelectSuggestion(_:)), for: UIControlEvents.touchUpInside)
// If this is the first image, add the search icon.
if container.subviews.isEmpty {
let image = UIImage(named: SearchViewControllerUX.SearchImage)
button.setImage(image, for: UIControlState())
button.titleEdgeInsets = UIEdgeInsets(top: 0, left: 8, bottom: 0, right: 0)
}
container.addSubview(button)
}
setNeedsLayout()
}
}
@objc
func SELdidSelectSuggestion(_ sender: UIButton) {
delegate?.suggestionCell(self, didSelectSuggestion: sender.titleLabel!.text!)
}
fileprivate override func layoutSubviews() {
super.layoutSubviews()
// The left bounds of the suggestions, aligned with where text would be displayed.
let textLeft: CGFloat = 48
// The maximum width of the container, after which suggestions will wrap to the next line.
let maxWidth = contentView.frame.width
let imageSize = CGFloat(OpenSearchEngine.PreferredIconSize)
// The height of the suggestions container (minus margins), used to determine the frame.
// We set it to imageSize.height as a minimum since we don't want the cell to be shorter than the icon
var height: CGFloat = imageSize
var currentLeft = textLeft
var currentTop = SearchViewControllerUX.SuggestionCellVerticalPadding
var currentRow = 0
for view in container.subviews {
let button = view as! UIButton
var buttonSize = button.intrinsicContentSize
// Update our base frame height by the max size of either the image or the button so we never
// make the cell smaller than any of the two
if height == imageSize {
height = max(buttonSize.height, imageSize)
}
var width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin
if width > maxWidth {
// Only move to the next row if there's already a suggestion on this row.
// Otherwise, the suggestion is too big to fit and will be resized below.
if currentLeft > textLeft {
currentRow += 1
if currentRow >= SearchViewControllerUX.SuggestionCellMaxRows {
// Don't draw this button if it doesn't fit on the row.
button.frame = CGRect.zero
continue
}
currentLeft = textLeft
currentTop += buttonSize.height + SearchViewControllerUX.SuggestionMargin
height += buttonSize.height + SearchViewControllerUX.SuggestionMargin
width = currentLeft + buttonSize.width + SearchViewControllerUX.SuggestionMargin
}
// If the suggestion is too wide to fit on its own row, shrink it.
if width > maxWidth {
buttonSize.width = maxWidth - currentLeft - SearchViewControllerUX.SuggestionMargin
}
}
button.frame = CGRect(x: currentLeft, y: currentTop, width: buttonSize.width, height: buttonSize.height)
currentLeft += buttonSize.width + SearchViewControllerUX.SuggestionMargin
}
frame.size.height = height + 2 * SearchViewControllerUX.SuggestionCellVerticalPadding
contentView.frame = frame
container.frame = frame
let imageX = (48 - imageSize) / 2
let imageY = (frame.size.height - imageSize) / 2
imageView!.frame = CGRect(x: imageX, y: imageY, width: imageSize, height: imageSize)
}
}
/**
* Rounded search suggestion button that highlights when selected.
*/
fileprivate class SuggestionButton: InsetButton {
override init(frame: CGRect) {
super.init(frame: frame)
setTitleColor(UIConstants.HighlightBlue, for: UIControlState())
setTitleColor(UIColor.white, for: UIControlState.highlighted)
titleLabel?.font = DynamicFontHelper.defaultHelper.DefaultMediumFont
backgroundColor = SearchViewControllerUX.SuggestionBackgroundColor
layer.borderColor = SearchViewControllerUX.SuggestionBorderColor.cgColor
layer.borderWidth = SearchViewControllerUX.SuggestionBorderWidth
layer.cornerRadius = SearchViewControllerUX.SuggestionCornerRadius
contentEdgeInsets = SearchViewControllerUX.SuggestionInsets
accessibilityHint = NSLocalizedString("Searches for the suggestion", comment: "Accessibility hint describing the action performed when a search suggestion is clicked")
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@objc
override var isHighlighted: Bool {
didSet {
backgroundColor = isHighlighted ? UIConstants.HighlightBlue : SearchViewControllerUX.SuggestionBackgroundColor
}
}
}
|
mpl-2.0
|
505af639de3b24009c2b1bf1f457cad5
| 42.444152 | 422 | 0.677414 | 5.54901 | false | false | false | false |
tzhenghao/DropIt
|
DropIt/DropItViewController.swift
|
1
|
1843
|
//
// DropItViewController.swift
// DropIt
//
// Created by Zheng Hao Tan on 7/10/15.
// Copyright (c) 2015 Zheng Hao Tan. All rights reserved.
//
import UIKit
class DropItViewController: UIViewController {
@IBOutlet weak var gameView: UIView!
lazy var animator: UIDynamicAnimator = {
let lazilyCreatedDynamicAnimator = UIDynamicAnimator(referenceView: self.gameView)
return lazilyCreatedDynamicAnimator
}()
var dropItBehavior = DropItBehavior()
override func viewDidLoad() {
super.viewDidLoad()
animator.addBehavior(dropItBehavior)
}
var dropsPerRow = 10
var dropSize: CGSize {
let size = gameView.bounds.size.width / CGFloat(dropsPerRow)
return CGSize(width: size, height: size)
}
@IBAction func drop(sender: UITapGestureRecognizer) {
drop()
}
func drop() {
var frame = CGRect(origin: CGPointZero, size: dropSize)
frame.origin.x = CGFloat.random(dropsPerRow) * dropSize.width
let dropView = UIView(frame: frame)
dropView.backgroundColor = UIColor.random
dropItBehavior.addDrop(dropView)
}
}
private extension CGFloat {
static func random(max:Int) -> CGFloat {
return CGFloat(arc4random() % UInt32(max))
}
}
// Extension for random UIColor colors.
private extension UIColor {
class var random: UIColor {
switch arc4random() % 6 {
case 0: return UIColor.greenColor()
case 1: return UIColor.blueColor()
case 2: return UIColor.redColor()
case 3: return UIColor.orangeColor()
case 4: return UIColor.purpleColor()
case 5: return UIColor.yellowColor()
default: return UIColor.blackColor()
}
}
}
|
mit
|
766498d152a50b5ff14cf33aa027dc05
| 24.957746 | 90 | 0.62344 | 4.550617 | false | false | false | false |
wordpress-mobile/WordPress-iOS
|
WordPress/Classes/Utility/ImmuTable.swift
|
1
|
18434
|
import UIKit
/**
ImmuTable represents the view model for a static UITableView.
ImmuTable consists of zero or more sections, each one containing zero or more rows,
and an optional header and footer text.
Each row contains the model necessary to configure a specific type of UITableViewCell.
To use ImmuTable, first you need to create some custom rows. An example row for a cell
that acts as a button which performs a destructive action could look like this:
struct DestructiveButtonRow: ImmuTableRow {
static let cell = ImmuTableCell.Class(UITableViewCell.self)
let title: String
let action: ImmuTableAction?
func configureCell(cell: UITableViewCell) {
cell.textLabel?.text = title
cell.textLabel?.textAlignment = .Center
cell.textLabel?.textColor = UIColor.redColor()
}
}
The easiest way to use ImmuTable is through ImmuTableViewHandler, which takes a
UITableViewController as an argument, and acts as the table view delegate and data
source. You would then assign an ImmuTable object to the handler's `viewModel`
property.
- attention: before using any ImmuTableRow type, you need to call `registerRows(_:tableView:)`
passing the row type. This is needed so ImmuTable can register the class or nib with the table view.
If you fail to do this, UIKit will raise an exception when it tries to load the row.
*/
public struct ImmuTable {
/// An array of the sections to be represented in the table view
public let sections: [ImmuTableSection]
/// Initializes an ImmuTable object with the given sections
public init(sections: [ImmuTableSection]) {
self.sections = sections
}
/// Returns the row model for a specific index path.
///
/// - Precondition: `indexPath` should represent a valid section and row, otherwise this method
/// will raise an exception.
///
public func rowAtIndexPath(_ indexPath: IndexPath) -> ImmuTableRow {
return sections[indexPath.section].rows[indexPath.row]
}
/// Registers the row custom class or nib with the table view so it can later be
/// dequeued with `dequeueReusableCellWithIdentifier(_:forIndexPath:)`
///
public static func registerRows(_ rows: [ImmuTableRow.Type], tableView: UITableView) {
registerRows(rows, registrator: tableView)
}
/// This function exists for testing purposes
/// - seealso: registerRows(_:tableView:)
internal static func registerRows(_ rows: [ImmuTableRow.Type], registrator: CellRegistrar) {
let registrables = rows.reduce([:]) {
(classes, row) -> [String: ImmuTableCell] in
var classes = classes
classes[row.cell.reusableIdentifier] = row.cell
return classes
}
for (identifier, registrable) in registrables {
registrator.register(registrable, cellReuseIdentifier: identifier)
}
}
}
extension ImmuTable {
/// Alias for an ImmuTable with no sections
static var Empty: ImmuTable {
return ImmuTable(sections: [])
}
}
// MARK: -
/// ImmuTableSection represents the view model for a table view section.
///
/// A section has an optional header and footer text, and zero or more rows.
/// - seealso: ImmuTableRow
///
public struct ImmuTableSection {
let headerText: String?
let rows: [ImmuTableRow]
let footerText: String?
/// Initializes a ImmuTableSection with the given rows and optionally header and footer text
public init(headerText: String? = nil, rows: [ImmuTableRow], footerText: String? = nil) {
self.headerText = headerText
self.rows = rows
self.footerText = footerText
}
}
// MARK: - ImmuTableRow
/// ImmuTableRow represents the minimum common elements of a row model.
///
/// You should implement your own types that conform to ImmuTableRow to define your custom rows.
///
public protocol ImmuTableRow {
/**
The closure to call when the row is tapped. The row is passed as an argument to the closure.
To improve readability, we recommend that you implement the action logic in one of
your view controller methods, instead of including the closure inline.
Also, be mindful of retain cycles. If your closure needs to reference `self` in
any way, make sure to use `[unowned self]` in the parameter list.
An example row with its action could look like this:
class ViewController: UITableViewController {
func buildViewModel() {
let item1Row = NavigationItemRow(title: "Item 1", action: navigationAction())
...
}
func navigationAction() -> ImmuTableRow -> Void {
return { [unowned self] row in
let controller = self.controllerForRow(row)
self.navigationController?.pushViewController(controller, animated: true)
}
}
...
}
*/
var action: ImmuTableAction? { get }
/// This method is called when an associated cell needs to be configured.
///
/// - Precondition: You can assume that the passed cell is of the type defined
/// by cell.cellClass and force downcast accordingly.
///
func configureCell(_ cell: UITableViewCell)
/// An ImmuTableCell value defining the associated cell type.
///
/// - Seealso: See ImmuTableCell for possible options.
///
static var cell: ImmuTableCell { get }
/// The desired row height (Optional)
///
/// If not defined or nil, the default height will be used.
///
static var customHeight: Float? { get }
}
extension ImmuTableRow {
public var reusableIdentifier: String {
return type(of: self).cell.reusableIdentifier
}
public var cellClass: UITableViewCell.Type {
return type(of: self).cell.cellClass
}
public static var customHeight: Float? {
return nil
}
}
// MARK: - ImmuTableCell
/// ImmuTableCell describes cell types so they can be registered with a table view.
///
/// It supports two options:
/// - Nib for Interface Builder defined cells.
/// - Class for cells defined in code.
/// Both cases presume a custom UITableViewCell subclass. If you aren't subclassing,
/// you can also use UITableViewCell as the type.
///
/// - Note: If you need to use any cell style other than .Default we recommend you
/// subclass UITableViewCell and override init(style:reuseIdentifier:).
///
public enum ImmuTableCell {
/// A cell using a UINib. Values are the UINib object and the custom cell class.
case nib(UINib, UITableViewCell.Type)
/// A cell using a custom class. The associated value is the custom cell class.
case `class`(UITableViewCell.Type)
/// A String that uniquely identifies the cell type
public var reusableIdentifier: String {
switch self {
case .class(let cellClass):
return NSStringFromClass(cellClass)
case .nib(_, let cellClass):
return NSStringFromClass(cellClass)
}
}
/// The class of the custom cell
public var cellClass: UITableViewCell.Type {
switch self {
case .class(let cellClass):
return cellClass
case .nib(_, let cellClass):
return cellClass
}
}
}
// MARK: -
/// ImmuTableViewHandler is a helper to facilitate integration of ImmuTable in your
/// table view controllers.
///
/// It acts as the table view data source and delegate, and signals the table view to
/// reload its data when the underlying model changes.
///
/// - Note: As it keeps a weak reference to its target, you should keep a strong
/// reference to the handler from your view controller.
///
open class ImmuTableViewHandler: NSObject, UITableViewDataSource, UITableViewDelegate {
typealias UIViewControllerWithTableView = TableViewContainer & UITableViewDataSource & UITableViewDelegate & UIViewController
@objc unowned let target: UIViewControllerWithTableView
private weak var passthroughScrollViewDelegate: UIScrollViewDelegate?
/// Initializes the handler with a target table view controller.
/// - postcondition: After initialization, it becomse the data source and
/// delegate for the the target's table view.
@objc init(takeOver target: UIViewControllerWithTableView, with passthroughScrollViewDelegate: UIScrollViewDelegate? = nil) {
self.target = target
self.passthroughScrollViewDelegate = passthroughScrollViewDelegate
super.init()
self.target.tableView.dataSource = self
self.target.tableView.delegate = self
}
/// An ImmuTable object representing the table structure.
open var viewModel = ImmuTable.Empty {
didSet {
if target.isViewLoaded {
target.tableView.reloadData()
}
}
}
/// Configure the handler to automatically deselect any cell after tapping it.
@objc var automaticallyDeselectCells = false
// MARK: UITableViewDataSource
open func numberOfSections(in tableView: UITableView) -> Int {
return viewModel.sections.count
}
open func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return viewModel.sections[section].rows.count
}
open func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let row = viewModel.rowAtIndexPath(indexPath)
let cell = tableView.dequeueReusableCell(withIdentifier: row.reusableIdentifier, for: indexPath)
row.configureCell(cell)
return cell
}
open func tableView(_ tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
return viewModel.sections[section].headerText
}
open func tableView(_ tableView: UITableView, titleForFooterInSection section: Int) -> String? {
return viewModel.sections[section].footerText
}
open func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool {
if target.responds(to: #selector(UITableViewDataSource.tableView(_:canEditRowAt:))) {
return target.tableView?(tableView, canEditRowAt: indexPath) ?? false
}
return false
}
open func tableView(_ tableView: UITableView, canMoveRowAt indexPath: IndexPath) -> Bool {
if target.responds(to: #selector(UITableViewDataSource.tableView(_:canMoveRowAt:))) {
return target.tableView?(tableView, canMoveRowAt: indexPath) ?? false
}
return false
}
open func tableView(_ tableView: UITableView, moveRowAt sourceIndexPath: IndexPath, to destinationIndexPath: IndexPath) {
target.tableView?(tableView, moveRowAt: sourceIndexPath, to: destinationIndexPath)
}
// MARK: UITableViewDelegate
open func tableView(_ tableView: UITableView, willSelectRowAt indexPath: IndexPath) -> IndexPath? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:willSelectRowAt:))) {
return target.tableView?(tableView, willSelectRowAt: indexPath)
} else {
return indexPath
}
}
open func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:didSelectRowAt:))) {
target.tableView?(tableView, didSelectRowAt: indexPath)
} else {
let row = viewModel.rowAtIndexPath(indexPath)
row.action?(row)
}
if automaticallyDeselectCells {
tableView.deselectRow(at: indexPath, animated: true)
}
}
open func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
let row = viewModel.rowAtIndexPath(indexPath)
if let customHeight = type(of: row).customHeight {
return CGFloat(customHeight)
}
return tableView.rowHeight
}
open func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:heightForFooterInSection:))) {
return target.tableView?(tableView, heightForFooterInSection: section) ?? UITableView.automaticDimension
}
return UITableView.automaticDimension
}
open func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:heightForHeaderInSection:))) {
return target.tableView?(tableView, heightForHeaderInSection: section) ?? UITableView.automaticDimension
}
return UITableView.automaticDimension
}
open func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:viewForFooterInSection:))) {
return target.tableView?(tableView, viewForFooterInSection: section)
}
return nil
}
open func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:viewForHeaderInSection:))) {
return target.tableView?(tableView, viewForHeaderInSection: section)
}
return nil
}
open func tableView(_ tableView: UITableView, targetIndexPathForMoveFromRowAt sourceIndexPath: IndexPath, toProposedIndexPath proposedDestinationIndexPath: IndexPath) -> IndexPath {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:targetIndexPathForMoveFromRowAt:toProposedIndexPath:))) {
return target.tableView?(tableView, targetIndexPathForMoveFromRowAt: sourceIndexPath, toProposedIndexPath: proposedDestinationIndexPath) ?? proposedDestinationIndexPath
}
return proposedDestinationIndexPath
}
open func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:editingStyleForRowAt:))) {
return target.tableView?(tableView, editingStyleForRowAt: indexPath) ?? .none
}
return .none
}
open func tableView(_ tableView: UITableView, shouldIndentWhileEditingRowAt indexPath: IndexPath) -> Bool {
return target.tableView?(tableView, shouldIndentWhileEditingRowAt: indexPath) ?? true
}
public func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
if target.responds(to: #selector(UITableViewDelegate.tableView(_:trailingSwipeActionsConfigurationForRowAt:))) {
return target.tableView?(tableView, trailingSwipeActionsConfigurationForRowAt: indexPath)
}
return nil
}
// MARK: UIScrollViewDelegate
open func scrollViewDidScroll(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidScroll?(scrollView)
}
open func scrollViewDidZoom(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidZoom?(scrollView)
}
open func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewWillBeginDragging?(scrollView)
}
open func scrollViewWillEndDragging(_ scrollView: UIScrollView, withVelocity velocity: CGPoint, targetContentOffset: UnsafeMutablePointer<CGPoint>) {
passthroughScrollViewDelegate?.scrollViewWillEndDragging?(scrollView, withVelocity: velocity, targetContentOffset: targetContentOffset)
}
open func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
passthroughScrollViewDelegate?.scrollViewDidEndDragging?(scrollView, willDecelerate: decelerate)
}
open func scrollViewWillBeginDecelerating(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewWillBeginDecelerating?(scrollView)
}
open func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidEndDecelerating?(scrollView)
}
open func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidEndScrollingAnimation?(scrollView)
}
open func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return passthroughScrollViewDelegate?.viewForZooming?(in: scrollView)
}
open func scrollViewWillBeginZooming(_ scrollView: UIScrollView, with view: UIView?) {
passthroughScrollViewDelegate?.scrollViewWillBeginZooming?(scrollView, with: view)
}
open func scrollViewDidEndZooming(_ scrollView: UIScrollView, with view: UIView?, atScale scale: CGFloat) {
passthroughScrollViewDelegate?.scrollViewDidEndZooming?(scrollView, with: view, atScale: scale)
}
open func scrollViewShouldScrollToTop(_ scrollView: UIScrollView) -> Bool {
return passthroughScrollViewDelegate?.scrollViewShouldScrollToTop?(scrollView) ?? true
}
open func scrollViewDidScrollToTop(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidScrollToTop?(scrollView)
}
open func scrollViewDidChangeAdjustedContentInset(_ scrollView: UIScrollView) {
passthroughScrollViewDelegate?.scrollViewDidChangeAdjustedContentInset?(scrollView)
}
}
// MARK: - Type aliases
public typealias ImmuTableAction = (ImmuTableRow) -> Void
// MARK: - Internal testing helpers
protocol CellRegistrar {
func register(_ cell: ImmuTableCell, cellReuseIdentifier: String)
}
extension UITableView: CellRegistrar {
public func register(_ cell: ImmuTableCell, cellReuseIdentifier: String) {
switch cell {
case .nib(let nib, _):
self.register(nib, forCellReuseIdentifier: cell.reusableIdentifier)
case .class(let cellClass):
self.register(cellClass, forCellReuseIdentifier: cell.reusableIdentifier)
}
}
}
// MARK: - UITableViewController conformance
@objc public protocol TableViewContainer: AnyObject {
var tableView: UITableView! { get set }
}
extension UITableViewController: TableViewContainer {}
|
gpl-2.0
|
68b8e5f01f2aa149dcaf164af72db247
| 36.315789 | 185 | 0.701042 | 5.569184 | false | false | false | false |
realm/SwiftLint
|
Source/SwiftLintFramework/Rules/Style/MultilineFunctionChainsRule.swift
|
1
|
8455
|
import Foundation
import SourceKittenFramework
struct MultilineFunctionChainsRule: ASTRule, OptInRule, ConfigurationProviderRule {
var configuration = SeverityConfiguration(.warning)
init() {}
static let description = RuleDescription(
identifier: "multiline_function_chains",
name: "Multiline Function Chains",
description: "Chained function calls should be either on the same line, or one per line.",
kind: .style,
nonTriggeringExamples: [
Example("let evenSquaresSum = [20, 17, 35, 4].filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)"),
Example("""
let evenSquaresSum = [20, 17, 35, 4]
.filter { $0 % 2 == 0 }.map { $0 * $0 }.reduce(0, +)",
"""),
Example("""
let chain = a
.b(1, 2, 3)
.c { blah in
print(blah)
}
.d()
"""),
Example("""
let chain = a.b(1, 2, 3)
.c { blah in
print(blah)
}
.d()
"""),
Example("""
let chain = a.b(1, 2, 3)
.c { blah in print(blah) }
.d()
"""),
Example("""
let chain = a.b(1, 2, 3)
.c(.init(
a: 1,
b, 2,
c, 3))
.d()
"""),
Example("""
self.viewModel.outputs.postContextualNotification
.observeForUI()
.observeValues {
NotificationCenter.default.post(
Notification(
name: .ksr_showNotificationsDialog,
userInfo: [UserInfoKeys.context: PushNotificationDialog.Context.pledge,
UserInfoKeys.viewController: self]
)
)
}
"""),
Example("let remainingIDs = Array(Set(self.currentIDs).subtracting(Set(response.ids)))"),
Example("""
self.happeningNewsletterOn = self.updateCurrentUser
.map { $0.newsletters.happening }.skipNil().skipRepeats()
""")
],
triggeringExamples: [
Example("""
let evenSquaresSum = [20, 17, 35, 4]
.filter { $0 % 2 == 0 }↓.map { $0 * $0 }
.reduce(0, +)
"""),
Example("""
let evenSquaresSum = a.b(1, 2, 3)
.c { blah in
print(blah)
}↓.d()
"""),
Example("""
let evenSquaresSum = a.b(1, 2, 3)
.c(2, 3, 4)↓.d()
"""),
Example("""
let evenSquaresSum = a.b(1, 2, 3)↓.c { blah in
print(blah)
}
.d()
"""),
Example("""
a.b {
// ““
}↓.e()
""")
]
)
func validate(file: SwiftLintFile,
kind: SwiftExpressionKind,
dictionary: SourceKittenDictionary) -> [StyleViolation] {
return violatingOffsets(file: file, kind: kind, dictionary: dictionary).map { offset in
return StyleViolation(ruleDescription: Self.description,
severity: configuration.severity,
location: Location(file: file, characterOffset: offset))
}
}
private func violatingOffsets(file: SwiftLintFile,
kind: SwiftExpressionKind,
dictionary: SourceKittenDictionary) -> [Int] {
let ranges = callRanges(file: file, kind: kind, dictionary: dictionary)
let calls = ranges.compactMap { range -> (dotLine: Int, dotOffset: Int, range: ByteRange)? in
guard
let offset = callDotOffset(file: file, callRange: range),
let line = file.stringView.lineAndCharacter(forCharacterOffset: offset)?.line else {
return nil
}
return (dotLine: line, dotOffset: offset, range: range)
}
let uniqueLines = calls.map { $0.dotLine }.unique
if uniqueLines.count == 1 { return [] }
// The first call (last here) is allowed to not have a leading newline.
let noLeadingNewlineViolations = calls
.dropLast()
.filter { line in
!callHasLeadingNewline(file: file, callRange: line.range)
}
return noLeadingNewlineViolations.map { $0.dotOffset }
}
private static let whitespaceDotRegex = regex("\\s*\\.")
private func callDotOffset(file: SwiftLintFile, callRange: ByteRange) -> Int? {
guard
let range = file.stringView.byteRangeToNSRange(callRange),
case let regex = Self.whitespaceDotRegex,
let match = regex.matches(in: file.contents, options: [], range: range).last?.range else {
return nil
}
return match.location + match.length - 1
}
private static let newlineWhitespaceDotRegex = regex("\\n\\s*\\.")
private func callHasLeadingNewline(file: SwiftLintFile, callRange: ByteRange) -> Bool {
guard
let range = file.stringView.byteRangeToNSRange(callRange),
case let regex = Self.newlineWhitespaceDotRegex,
regex.firstMatch(in: file.contents, options: [], range: range) != nil else {
return false
}
return true
}
private func callRanges(file: SwiftLintFile,
kind: SwiftExpressionKind,
dictionary: SourceKittenDictionary,
parentCallName: String? = nil) -> [ByteRange] {
guard
kind == .call,
case let contents = file.stringView,
let offset = dictionary.nameOffset,
let length = dictionary.nameLength,
case let nameByteRange = ByteRange(location: offset, length: length),
let name = contents.substringWithByteRange(nameByteRange)
else {
return []
}
let subcalls = dictionary.subcalls
if subcalls.isEmpty, let parentCallName = parentCallName, parentCallName.starts(with: name) {
return [ByteRange(location: offset, length: length)]
}
return subcalls.flatMap { call -> [ByteRange] in
// Bail out early if there's no subcall, since this means there's no chain.
guard let range = subcallRange(file: file, call: call, parentName: name, parentNameOffset: offset) else {
return []
}
return [range] + callRanges(file: file, kind: .call, dictionary: call, parentCallName: name)
}
}
private func subcallRange(file: SwiftLintFile,
call: SourceKittenDictionary,
parentName: String,
parentNameOffset: ByteCount) -> ByteRange? {
guard
case let contents = file.stringView,
let nameOffset = call.nameOffset,
parentNameOffset == nameOffset,
let nameLength = call.nameLength,
let bodyOffset = call.bodyOffset,
let bodyLength = call.bodyLength,
case let nameByteRange = ByteRange(location: nameOffset, length: nameLength),
let name = contents.substringWithByteRange(nameByteRange),
parentName.starts(with: name)
else {
return nil
}
let nameEndOffset = nameOffset + nameLength
let nameLengthDifference = ByteCount(parentName.lengthOfBytes(using: .utf8)) - nameLength
let offsetDifference = bodyOffset - nameEndOffset
return ByteRange(location: nameEndOffset + offsetDifference + bodyLength,
length: nameLengthDifference - bodyLength - offsetDifference)
}
}
private extension SourceKittenDictionary {
var subcalls: [SourceKittenDictionary] {
return substructure.compactMap { dictionary -> SourceKittenDictionary? in
guard dictionary.expressionKind == .call else {
return nil
}
return dictionary
}
}
}
|
mit
|
b94fd76a74be599ae356ee35a224c9b5
| 36.349558 | 117 | 0.518067 | 5.042413 | false | false | false | false |
zilverline/Dezignables
|
Pod/Classes/Dezignables/DezignableShadow.swift
|
1
|
1154
|
//
// DezignableShadow.swift
// Pods
//
// Created by Daniel van Hoesel on 28-02-16.
//
//
import UIKit
public protocol DezignableShadow {
var boxShadowColor: UIColor? { get set }
var boxShadowRadius: CGFloat { get set }
var boxShadowOpacity: CGFloat { get set }
var boxShadowOffset: CGPoint { get set }
}
public extension DezignableShadow where Self: UIView {
public func setupShadow() {
guard let shadowColor = self.boxShadowColor else {
return
}
self.layer.shadowColor = shadowColor.cgColor
if !self.boxShadowRadius.isNaN && self.boxShadowRadius > 0 {
self.layer.shadowRadius = self.boxShadowRadius
}
if !self.boxShadowOpacity.isNaN && self.boxShadowOpacity >= 0 && self.boxShadowOpacity <= 1 {
self.layer.shadowOpacity = Float(self.boxShadowOpacity)
} else {
self.layer.shadowOpacity = 1.0
}
if !self.boxShadowOffset.x.isNaN {
self.layer.shadowOffset.width = self.boxShadowOffset.x
}
if !self.boxShadowOffset.y.isNaN {
self.layer.shadowOffset.height = self.boxShadowOffset.y
}
self.layer.masksToBounds = false
}
}
|
mit
|
0586b42cf89720bb7e0f048fa33514eb
| 24.086957 | 97 | 0.674177 | 3.898649 | false | false | false | false |
VicFrolov/Markit
|
iOS/Markit/Pods/FontAwesome.swift/FontAwesome/Enum.swift
|
4
|
48180
|
// Enum.swift
//
// Copyright (c) 2014-present FontAwesome.swift contributors
//
// 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.
/// An enumaration of FontAwesome icon names.
public enum FontAwesome: String {
case fiveHundredPixels = "\u{f26e}"
case adjust = "\u{f042}"
case adn = "\u{f170}"
case alignCenter = "\u{f037}"
case alignJustify = "\u{f039}"
case alignLeft = "\u{f036}"
case alignRight = "\u{f038}"
case amazon = "\u{f270}"
case ambulance = "\u{f0f9}"
case americanSignLanguageInterpreting = "\u{f2a3}"
case anchor = "\u{f13d}"
case android = "\u{f17b}"
case angellist = "\u{f209}"
case angleDoubleDown = "\u{f103}"
case angleDoubleLeft = "\u{f100}"
case angleDoubleRight = "\u{f101}"
case angleDoubleUp = "\u{f102}"
case angleDown = "\u{f107}"
case angleLeft = "\u{f104}"
case angleRight = "\u{f105}"
case angleUp = "\u{f106}"
case apple = "\u{f179}"
case archive = "\u{f187}"
case areaChart = "\u{f1fe}"
case arrowCircleDown = "\u{f0ab}"
case arrowCircleLeft = "\u{f0a8}"
case arrowCircleODown = "\u{f01a}"
case arrowCircleOLeft = "\u{f190}"
case arrowCircleORight = "\u{f18e}"
case arrowCircleOUp = "\u{f01b}"
case arrowCircleRight = "\u{f0a9}"
case arrowCircleUp = "\u{f0aa}"
case arrowDown = "\u{f063}"
case arrowLeft = "\u{f060}"
case arrowRight = "\u{f061}"
case arrowUp = "\u{f062}"
case arrows = "\u{f047}"
case arrowsAlt = "\u{f0b2}"
case arrowsH = "\u{f07e}"
case arrowsV = "\u{f07d}"
case aslInterpreting = "\u{f2a3}A"
case assistiveListeningSystems = "\u{f2a2}"
case asterisk = "\u{f069}"
case at = "\u{f1fa}"
case audioDescription = "\u{f29e}"
case automobile = "\u{f1b9}A"
case backward = "\u{f04a}"
case balanceScale = "\u{f24e}"
case ban = "\u{f05e}"
case bank = "\u{f19c}A"
case barChart = "\u{f080}"
case barChartO = "\u{f080}A"
case barcode = "\u{f02a}"
case bars = "\u{f0c9}"
case battery0 = "\u{f244}A"
case battery1 = "\u{f243}A"
case battery2 = "\u{f242}A"
case battery3 = "\u{f241}A"
case battery4 = "\u{f240}A"
case batteryEmpty = "\u{f244}"
case batteryFull = "\u{f240}"
case batteryHalf = "\u{f242}"
case batteryQuarter = "\u{f243}"
case batteryThreeQuarters = "\u{f241}"
case bed = "\u{f236}"
case beer = "\u{f0fc}"
case behance = "\u{f1b4}"
case behanceSquare = "\u{f1b5}"
case bell = "\u{f0f3}"
case bellO = "\u{f0a2}"
case bellSlash = "\u{f1f6}"
case bellSlashO = "\u{f1f7}"
case bicycle = "\u{f206}"
case binoculars = "\u{f1e5}"
case birthdayCake = "\u{f1fd}"
case bitbucket = "\u{f171}"
case bitbucketSquare = "\u{f172}"
case bitcoin = "\u{f15a}A"
case blackTie = "\u{f27e}"
case blind = "\u{f29d}"
case bluetooth = "\u{f293}"
case bluetoothB = "\u{f294}"
case bold = "\u{f032}"
case bolt = "\u{f0e7}"
case bomb = "\u{f1e2}"
case book = "\u{f02d}"
case bookmark = "\u{f02e}"
case bookmarkO = "\u{f097}"
case braille = "\u{f2a1}"
case briefcase = "\u{f0b1}"
case btc = "\u{f15a}"
case bug = "\u{f188}"
case building = "\u{f1ad}"
case buildingO = "\u{f0f7}"
case bullhorn = "\u{f0a1}"
case bullseye = "\u{f140}"
case bus = "\u{f207}"
case buysellads = "\u{f20d}"
case cab = "\u{f1ba}A"
case calculator = "\u{f1ec}"
case calendar = "\u{f073}"
case calendarCheckO = "\u{f274}"
case calendarMinusO = "\u{f272}"
case calendarO = "\u{f133}"
case calendarPlusO = "\u{f271}"
case calendarTimesO = "\u{f273}"
case camera = "\u{f030}"
case cameraRetro = "\u{f083}"
case car = "\u{f1b9}"
case caretDown = "\u{f0d7}"
case caretLeft = "\u{f0d9}"
case caretRight = "\u{f0da}"
case caretSquareODown = "\u{f150}"
case caretSquareOLeft = "\u{f191}"
case caretSquareORight = "\u{f152}"
case caretSquareOUp = "\u{f151}"
case caretUp = "\u{f0d8}"
case cartArrowDown = "\u{f218}"
case cartPlus = "\u{f217}"
case cc = "\u{f20a}"
case ccAmex = "\u{f1f3}"
case ccDinersClub = "\u{f24c}"
case ccDiscover = "\u{f1f2}"
case ccJCB = "\u{f24b}"
case ccMasterCard = "\u{f1f1}"
case ccPaypal = "\u{f1f4}"
case ccStripe = "\u{f1f5}"
case ccVisa = "\u{f1f0}"
case certificate = "\u{f0a3}"
case chain = "\u{f0c1}A"
case chainBroken = "\u{f127}"
case check = "\u{f00c}"
case checkCircle = "\u{f058}"
case checkCircleO = "\u{f05d}"
case checkSquare = "\u{f14a}"
case checkSquareO = "\u{f046}"
case chevronCircleDown = "\u{f13a}"
case chevronCircleLeft = "\u{f137}"
case chevronCircleRight = "\u{f138}"
case chevronCircleUp = "\u{f139}"
case chevronDown = "\u{f078}"
case chevronLeft = "\u{f053}"
case chevronRight = "\u{f054}"
case chevronUp = "\u{f077}"
case child = "\u{f1ae}"
case chrome = "\u{f268}"
case circle = "\u{f111}"
case circleO = "\u{f10c}"
case circleONotch = "\u{f1ce}"
case circleThin = "\u{f1db}"
case clipboard = "\u{f0ea}"
case clockO = "\u{f017}"
case clone = "\u{f24d}"
case close = "\u{f00d}A"
case cloud = "\u{f0c2}"
case cloudDownload = "\u{f0ed}"
case cloudUpload = "\u{f0ee}"
case cny = "\u{f157}A"
case code = "\u{f121}"
case codeFork = "\u{f126}"
case codepen = "\u{f1cb}"
case codiepie = "\u{f284}"
case coffee = "\u{f0f4}"
case cog = "\u{f013}"
case cogs = "\u{f085}"
case columns = "\u{f0db}"
case comment = "\u{f075}"
case commentO = "\u{f0e5}"
case commenting = "\u{f27a}"
case commentingO = "\u{f27b}"
case comments = "\u{f086}"
case commentsO = "\u{f0e6}"
case compass = "\u{f14e}"
case compress = "\u{f066}"
case connectdevelop = "\u{f20e}"
case contao = "\u{f26d}"
case copy = "\u{f0c5}A"
case copyright = "\u{f1f9}"
case creativeCommons = "\u{f25e}"
case creditCard = "\u{f09d}"
case creditCardAlt = "\u{f283}"
case crop = "\u{f125}"
case crosshairs = "\u{f05b}"
case css3 = "\u{f13c}"
case cube = "\u{f1b2}"
case cubes = "\u{f1b3}"
case cut = "\u{f0c4}A"
case cutlery = "\u{f0f5}"
case dashboard = "\u{f0e4}A"
case dashcube = "\u{f210}"
case database = "\u{f1c0}"
case deaf = "\u{f2a4}"
case deafness = "\u{f2a4}A"
case dedent = "\u{f03b}A"
case delicious = "\u{f1a5}"
case desktop = "\u{f108}"
case deviantart = "\u{f1bd}"
case diamond = "\u{f219}"
case digg = "\u{f1a6}"
case dollar = "\u{f155}A"
case dotCircleO = "\u{f192}"
case download = "\u{f019}"
case dribbble = "\u{f17d}"
case dropbox = "\u{f16b}"
case drupal = "\u{f1a9}"
case edge = "\u{f282}"
case edit = "\u{f044}A"
case eject = "\u{f052}"
case ellipsisH = "\u{f141}"
case ellipsisV = "\u{f142}"
case empire = "\u{f1d1}"
case envelope = "\u{f0e0}"
case envelopeO = "\u{f003}"
case envelopeSquare = "\u{f199}"
case envira = "\u{f299}"
case eraser = "\u{f12d}"
case eur = "\u{f153}"
case euro = "\u{f153}A"
case exchange = "\u{f0ec}"
case exclamation = "\u{f12a}"
case exclamationCircle = "\u{f06a}"
case exclamationTriangle = "\u{f071}"
case expand = "\u{f065}"
case expeditedSSL = "\u{f23e}"
case externalLink = "\u{f08e}"
case externalLinkSquare = "\u{f14c}"
case eye = "\u{f06e}"
case eyeSlash = "\u{f070}"
case eyedropper = "\u{f1fb}"
case fa = "\u{f2b4}A"
case facebook = "\u{f09a}"
case facebookF = "\u{f09a}A"
case facebookOfficial = "\u{f230}"
case facebookSquare = "\u{f082}"
case fastBackward = "\u{f049}"
case fastForward = "\u{f050}"
case fax = "\u{f1ac}"
case feed = "\u{f09e}A"
case female = "\u{f182}"
case fighterJet = "\u{f0fb}"
case file = "\u{f15b}"
case fileArchiveO = "\u{f1c6}"
case fileAudioO = "\u{f1c7}"
case fileCodeO = "\u{f1c9}"
case fileExcelO = "\u{f1c3}"
case fileImageO = "\u{f1c5}"
case fileMovieO = "\u{f1c8}A"
case fileO = "\u{f016}"
case filePdfO = "\u{f1c1}"
case filePhotoO = "\u{f1c5}A"
case filePictureO = "\u{f1c5}B"
case filePowerpointO = "\u{f1c4}"
case fileSoundO = "\u{f1c7}A"
case fileText = "\u{f15c}"
case fileTextO = "\u{f0f6}"
case fileVideoO = "\u{f1c8}"
case fileWordO = "\u{f1c2}"
case fileZipO = "\u{f1c6}A"
case filesO = "\u{f0c5}"
case film = "\u{f008}"
case filter = "\u{f0b0}"
case fire = "\u{f06d}"
case fireExtinguisher = "\u{f134}"
case firefox = "\u{f269}"
case firstOrder = "\u{f2b0}"
case flag = "\u{f024}"
case flagCheckered = "\u{f11e}"
case flagO = "\u{f11d}"
case flash = "\u{f0e7}A"
case flask = "\u{f0c3}"
case flickr = "\u{f16e}"
case floppyO = "\u{f0c7}"
case folder = "\u{f07b}"
case folderO = "\u{f114}"
case folderOpen = "\u{f07c}"
case folderOpenO = "\u{f115}"
case font = "\u{f031}"
case fontAwesome = "\u{f2b4}"
case fonticons = "\u{f280}"
case fortAwesome = "\u{f286}"
case forumbee = "\u{f211}"
case forward = "\u{f04e}"
case foursquare = "\u{f180}"
case frownO = "\u{f119}"
case futbolO = "\u{f1e3}"
case gamepad = "\u{f11b}"
case gavel = "\u{f0e3}"
case gbp = "\u{f154}"
case ge = "\u{f1d1}A"
case gear = "\u{f013}A"
case gears = "\u{f085}A"
case genderless = "\u{f22d}"
case getPocket = "\u{f265}"
case gg = "\u{f260}"
case ggCircle = "\u{f261}"
case gift = "\u{f06b}"
case git = "\u{f1d3}"
case gitSquare = "\u{f1d2}"
case github = "\u{f09b}"
case githubAlt = "\u{f113}"
case githubSquare = "\u{f092}"
case gitlab = "\u{f296}"
case gittip = "\u{f184}A"
case glass = "\u{f000}"
case glide = "\u{f2a5}"
case glideG = "\u{f2a6}"
case globe = "\u{f0ac}"
case google = "\u{f1a0}"
case googlePlus = "\u{f0d5}"
case googlePlusCircle = "\u{f2b3}A"
case googlePlusOfficial = "\u{f2b3}"
case googlePlusSquare = "\u{f0d4}"
case googleWallet = "\u{f1ee}"
case graduationCap = "\u{f19d}"
case gratipay = "\u{f184}"
case group = "\u{f0c0}A"
case hSquare = "\u{f0fd}"
case hackerNews = "\u{f1d4}"
case handGrabO = "\u{f255}A"
case handLizardO = "\u{f258}"
case handODown = "\u{f0a7}"
case handOLeft = "\u{f0a5}"
case handORight = "\u{f0a4}"
case handOUp = "\u{f0a6}"
case handPaperO = "\u{f256}"
case handPeaceO = "\u{f25b}"
case handPointerO = "\u{f25a}"
case handRockO = "\u{f255}"
case handScissorsO = "\u{f257}"
case handSpockO = "\u{f259}"
case handStopO = "\u{f256}A"
case hardOfHearing = "\u{f2a4}B"
case hashtag = "\u{f292}"
case hddO = "\u{f0a0}"
case header = "\u{f1dc}"
case headphones = "\u{f025}"
case heart = "\u{f004}"
case heartO = "\u{f08a}"
case heartbeat = "\u{f21e}"
case history = "\u{f1da}"
case home = "\u{f015}"
case hospitalO = "\u{f0f8}"
case hotel = "\u{f236}A"
case hourglass = "\u{f254}"
case hourglass1 = "\u{f251}A"
case hourglass2 = "\u{f252}A"
case hourglass3 = "\u{f253}A"
case hourglassEnd = "\u{f253}"
case hourglassHalf = "\u{f252}"
case hourglassO = "\u{f250}"
case hourglassStart = "\u{f251}"
case houzz = "\u{f27c}"
case html5 = "\u{f13b}"
case iCursor = "\u{f246}"
case ils = "\u{f20b}"
case image = "\u{f03e}A"
case inbox = "\u{f01c}"
case indent = "\u{f03c}"
case industry = "\u{f275}"
case info = "\u{f129}"
case infoCircle = "\u{f05a}"
case inr = "\u{f156}"
case instagram = "\u{f16d}"
case institution = "\u{f19c}B"
case internetExplorer = "\u{f26b}"
case intersex = "\u{f224}A"
case ioxhost = "\u{f208}"
case italic = "\u{f033}"
case joomla = "\u{f1aa}"
case jpy = "\u{f157}"
case jsfiddle = "\u{f1cc}"
case key = "\u{f084}"
case keyboardO = "\u{f11c}"
case krw = "\u{f159}"
case language = "\u{f1ab}"
case laptop = "\u{f109}"
case lastFM = "\u{f202}"
case lastFMSquare = "\u{f203}"
case leaf = "\u{f06c}"
case leanpub = "\u{f212}"
case legal = "\u{f0e3}A"
case lemonO = "\u{f094}"
case levelDown = "\u{f149}"
case levelUp = "\u{f148}"
case lifeBouy = "\u{f1cd}A"
case lifeBuoy = "\u{f1cd}B"
case lifeRing = "\u{f1cd}"
case lifeSaver = "\u{f1cd}C"
case lightbulbO = "\u{f0eb}"
case lineChart = "\u{f201}"
case link = "\u{f0c1}"
case linkedIn = "\u{f0e1}"
case linkedInSquare = "\u{f08c}"
case linux = "\u{f17c}"
case list = "\u{f03a}"
case listAlt = "\u{f022}"
case listOL = "\u{f0cb}"
case listUL = "\u{f0ca}"
case locationArrow = "\u{f124}"
case lock = "\u{f023}"
case longArrowDown = "\u{f175}"
case longArrowLeft = "\u{f177}"
case longArrowRight = "\u{f178}"
case longArrowUp = "\u{f176}"
case lowVision = "\u{f2a8}"
case magic = "\u{f0d0}"
case magnet = "\u{f076}"
case mailForward = "\u{f064}A"
case mailReply = "\u{f112}A"
case mailReplyAll = "\u{f122}A"
case male = "\u{f183}"
case map = "\u{f279}"
case mapMarker = "\u{f041}"
case mapO = "\u{f278}"
case mapPin = "\u{f276}"
case mapSigns = "\u{f277}"
case mars = "\u{f222}"
case marsDouble = "\u{f227}"
case marsStroke = "\u{f229}"
case marsStrokeH = "\u{f22b}"
case marsStrokeV = "\u{f22a}"
case maxcdn = "\u{f136}"
case meanpath = "\u{f20c}"
case medium = "\u{f23a}"
case medkit = "\u{f0fa}"
case mehO = "\u{f11a}"
case mercury = "\u{f223}"
case microphone = "\u{f130}"
case microphoneSlash = "\u{f131}"
case minus = "\u{f068}"
case minusCircle = "\u{f056}"
case minusSquare = "\u{f146}"
case minusSquareO = "\u{f147}"
case mixcloud = "\u{f289}"
case mobile = "\u{f10b}"
case mobilePhone = "\u{f10b}A"
case modx = "\u{f285}"
case money = "\u{f0d6}"
case moonO = "\u{f186}"
case mortarBoard = "\u{f19d}A"
case motorcycle = "\u{f21c}"
case mousePointer = "\u{f245}"
case music = "\u{f001}"
case navicon = "\u{f0c9}A"
case neuter = "\u{f22c}"
case newspaperO = "\u{f1ea}"
case objectGroup = "\u{f247}"
case objectUngroup = "\u{f248}"
case odnoklassniki = "\u{f263}"
case odnoklassnikiSquare = "\u{f264}"
case openCart = "\u{f23d}"
case openID = "\u{f19b}"
case opera = "\u{f26a}"
case optinMonster = "\u{f23c}"
case outdent = "\u{f03b}"
case pagelines = "\u{f18c}"
case paintBrush = "\u{f1fc}"
case paperPlane = "\u{f1d8}"
case paperPlaneO = "\u{f1d9}"
case paperclip = "\u{f0c6}"
case paragraph = "\u{f1dd}"
case paste = "\u{f0ea}A"
case pause = "\u{f04c}"
case pauseCircle = "\u{f28b}"
case pauseCircleO = "\u{f28c}"
case paw = "\u{f1b0}"
case paypal = "\u{f1ed}"
case pencil = "\u{f040}"
case pencilSquare = "\u{f14b}"
case pencilSquareO = "\u{f044}"
case percent = "\u{f295}"
case phone = "\u{f095}"
case phoneSquare = "\u{f098}"
case photo = "\u{f03e}B"
case pictureO = "\u{f03e}"
case pieChart = "\u{f200}"
case piedPiper = "\u{f2ae}"
case piedPiperAlt = "\u{f1a8}"
case piedPiperPp = "\u{f1a7}"
case pinterest = "\u{f0d2}"
case pinterestP = "\u{f231}"
case pinterestSquare = "\u{f0d3}"
case plane = "\u{f072}"
case play = "\u{f04b}"
case playCircle = "\u{f144}"
case playCircleO = "\u{f01d}"
case plug = "\u{f1e6}"
case plus = "\u{f067}"
case plusCircle = "\u{f055}"
case plusSquare = "\u{f0fe}"
case plusSquareO = "\u{f196}"
case powerOff = "\u{f011}"
case print = "\u{f02f}"
case productHunt = "\u{f288}"
case puzzlePiece = "\u{f12e}"
case qq = "\u{f1d6}"
case qrcode = "\u{f029}"
case question = "\u{f128}"
case questionCircle = "\u{f059}"
case questionCircleO = "\u{f29c}"
case quoteLeft = "\u{f10d}"
case quoteRight = "\u{f10e}"
case ra = "\u{f1d0}A"
case random = "\u{f074}"
case rebel = "\u{f1d0}"
case recycle = "\u{f1b8}"
case reddit = "\u{f1a1}"
case redditAlien = "\u{f281}"
case redditSquare = "\u{f1a2}"
case refresh = "\u{f021}"
case registered = "\u{f25d}"
case remove = "\u{f00d}B"
case renren = "\u{f18b}"
case reorder = "\u{f0c9}B"
case `repeat` = "\u{f01e}"
case reply = "\u{f112}"
case replyAll = "\u{f122}"
case resistance = "\u{f1d0}B"
case retweet = "\u{f079}"
case rmb = "\u{f157}B"
case road = "\u{f018}"
case rocket = "\u{f135}"
case rotateLeft = "\u{f0e2}A"
case rotateRight = "\u{f01e}A"
case rouble = "\u{f158}A"
case rss = "\u{f09e}"
case rssSquare = "\u{f143}"
case rub = "\u{f158}"
case ruble = "\u{f158}B"
case rupee = "\u{f156}A"
case safari = "\u{f267}"
case save = "\u{f0c7}A"
case scissors = "\u{f0c4}"
case scribd = "\u{f28a}"
case search = "\u{f002}"
case searchMinus = "\u{f010}"
case searchPlus = "\u{f00e}"
case sellsy = "\u{f213}"
case send = "\u{f1d8}A"
case sendO = "\u{f1d9}A"
case server = "\u{f233}"
case share = "\u{f064}"
case shareAlt = "\u{f1e0}"
case shareAltSquare = "\u{f1e1}"
case shareSquare = "\u{f14d}"
case shareSquareO = "\u{f045}"
case shekel = "\u{f20b}A"
case sheqel = "\u{f20b}B"
case shield = "\u{f132}"
case ship = "\u{f21a}"
case shirtsinbulk = "\u{f214}"
case shoppingBag = "\u{f290}"
case shoppingBasket = "\u{f291}"
case shoppingCart = "\u{f07a}"
case signIn = "\u{f090}"
case signLanguage = "\u{f2a7}"
case signOut = "\u{f08b}"
case signal = "\u{f012}"
case signing = "\u{f2a7}A"
case simplybuilt = "\u{f215}"
case sitemap = "\u{f0e8}"
case skyatlas = "\u{f216}"
case skype = "\u{f17e}"
case slack = "\u{f198}"
case sliders = "\u{f1de}"
case slideshare = "\u{f1e7}"
case smileO = "\u{f118}"
case snapchat = "\u{f2ab}"
case snapchatGhost = "\u{f2ac}"
case snapchatSquare = "\u{f2ad}"
case soccerBallO = "\u{f1e3}A"
case sort = "\u{f0dc}"
case sortAlphaAsc = "\u{f15d}"
case sortAlphaDesc = "\u{f15e}"
case sortAmountAsc = "\u{f160}"
case sortAmountDesc = "\u{f161}"
case sortAsc = "\u{f0de}"
case sortDesc = "\u{f0dd}"
case sortDown = "\u{f0dd}A"
case sortNumericAsc = "\u{f162}"
case sortNumericDesc = "\u{f163}"
case sortUp = "\u{f0de}A"
case soundCloud = "\u{f1be}"
case spaceShuttle = "\u{f197}"
case spinner = "\u{f110}"
case spoon = "\u{f1b1}"
case spotify = "\u{f1bc}"
case square = "\u{f0c8}"
case squareO = "\u{f096}"
case stackExchange = "\u{f18d}"
case stackOverflow = "\u{f16c}"
case star = "\u{f005}"
case starHalf = "\u{f089}"
case starHalfEmpty = "\u{f123}A"
case starHalfFull = "\u{f123}B"
case starHalfO = "\u{f123}"
case starO = "\u{f006}"
case steam = "\u{f1b6}"
case steamSquare = "\u{f1b7}"
case stepBackward = "\u{f048}"
case stepForward = "\u{f051}"
case stethoscope = "\u{f0f1}"
case stickyNote = "\u{f249}"
case stickyNoteO = "\u{f24a}"
case stop = "\u{f04d}"
case stopCircle = "\u{f28d}"
case stopCircleO = "\u{f28e}"
case streetView = "\u{f21d}"
case strikethrough = "\u{f0cc}"
case stumbleUpon = "\u{f1a4}"
case stumbleUponCircle = "\u{f1a3}"
case `subscript` = "\u{f12c}"
case subway = "\u{f239}"
case suitcase = "\u{f0f2}"
case sunO = "\u{f185}"
case superscript = "\u{f12b}"
case support = "\u{f1cd}D"
case table = "\u{f0ce}"
case tablet = "\u{f10a}"
case tachometer = "\u{f0e4}"
case tag = "\u{f02b}"
case tags = "\u{f02c}"
case tasks = "\u{f0ae}"
case taxi = "\u{f1ba}"
case television = "\u{f26c}"
case tencentWeibo = "\u{f1d5}"
case terminal = "\u{f120}"
case textHeight = "\u{f034}"
case textWidth = "\u{f035}"
case th = "\u{f00a}"
case thLarge = "\u{f009}"
case thList = "\u{f00b}"
case themeisle = "\u{f2b2}"
case thumbTack = "\u{f08d}"
case thumbsDown = "\u{f165}"
case thumbsODown = "\u{f088}"
case thumbsOUp = "\u{f087}"
case thumbsUp = "\u{f164}"
case ticket = "\u{f145}"
case times = "\u{f00d}"
case timesCircle = "\u{f057}"
case timesCircleO = "\u{f05c}"
case tint = "\u{f043}"
case toggleDown = "\u{f150}A"
case toggleLeft = "\u{f191}A"
case toggleOff = "\u{f204}"
case toggleOn = "\u{f205}"
case toggleRight = "\u{f152}A"
case toggleUp = "\u{f151}A"
case trademark = "\u{f25c}"
case train = "\u{f238}"
case transgender = "\u{f224}"
case transgenderAlt = "\u{f225}"
case trash = "\u{f1f8}"
case trashO = "\u{f014}"
case tree = "\u{f1bb}"
case trello = "\u{f181}"
case tripAdvisor = "\u{f262}"
case trophy = "\u{f091}"
case truck = "\u{f0d1}"
case `try` = "\u{f195}"
case tty = "\u{f1e4}"
case tumblr = "\u{f173}"
case tumblrSquare = "\u{f174}"
case turkishLira = "\u{f195}A"
case tv = "\u{f26c}A"
case twitch = "\u{f1e8}"
case twitter = "\u{f099}"
case twitterSquare = "\u{f081}"
case umbrella = "\u{f0e9}"
case underline = "\u{f0cd}"
case undo = "\u{f0e2}"
case universalAccess = "\u{f29a}"
case university = "\u{f19c}"
case unlink = "\u{f127}A"
case unlock = "\u{f09c}"
case unlockAlt = "\u{f13e}"
case unsorted = "\u{f0dc}A"
case upload = "\u{f093}"
case usb = "\u{f287}"
case usd = "\u{f155}"
case user = "\u{f007}"
case userMd = "\u{f0f0}"
case userPlus = "\u{f234}"
case userSecret = "\u{f21b}"
case userTimes = "\u{f235}"
case users = "\u{f0c0}"
case venus = "\u{f221}"
case venusDouble = "\u{f226}"
case venusMars = "\u{f228}"
case viacoin = "\u{f237}"
case viadeo = "\u{f2a9}"
case viadeoSquare = "\u{f2aa}"
case videoCamera = "\u{f03d}"
case vimeo = "\u{f27d}"
case vimeoSquare = "\u{f194}"
case vine = "\u{f1ca}"
case vk = "\u{f189}"
case volumeControlPhone = "\u{f2a0}"
case volumeDown = "\u{f027}"
case volumeOff = "\u{f026}"
case volumeUp = "\u{f028}"
case warning = "\u{f071}A"
case wechat = "\u{f1d7}A"
case weibo = "\u{f18a}"
case weixin = "\u{f1d7}"
case whatsapp = "\u{f232}"
case wheelchair = "\u{f193}"
case wheelchairAlt = "\u{f29b}"
case wifi = "\u{f1eb}"
case wikipediaW = "\u{f266}"
case windows = "\u{f17a}"
case won = "\u{f159}A"
case wordpress = "\u{f19a}"
case wpbeginner = "\u{f297}"
case wpforms = "\u{f298}"
case wrench = "\u{f0ad}"
case xing = "\u{f168}"
case xingSquare = "\u{f169}"
case yCombinator = "\u{f23b}"
case yCombinatorSquare = "\u{f1d4}A"
case yahoo = "\u{f19e}"
case yc = "\u{f23b}A"
case ycSquare = "\u{f1d4}B"
case yelp = "\u{f1e9}"
case yen = "\u{f157}C"
case yoast = "\u{f2b1}"
case youTube = "\u{f167}"
case youTubePlay = "\u{f16a}"
case youTubeSquare = "\u{f166}"
/// Get a FontAwesome string from the given CSS icon code. Icon code can be found here: http://fontawesome.io/icons/
///
/// - parameter code: The preferred icon name.
/// - returns: FontAwesome icon.
public static func fromCode(_ code: String) -> FontAwesome? {
guard let raw = FontAwesomeIcons[code], let icon = FontAwesome(rawValue: raw) else {
return nil
}
return icon
}
}
/// An array of FontAwesome icon codes.
public let FontAwesomeIcons = [
"fa-500px": "\u{f26e}",
"fa-adjust": "\u{f042}",
"fa-adn": "\u{f170}",
"fa-align-center": "\u{f037}",
"fa-align-justify": "\u{f039}",
"fa-align-left": "\u{f036}",
"fa-align-right": "\u{f038}",
"fa-amazon": "\u{f270}",
"fa-ambulance": "\u{f0f9}",
"fa-american-sign-language-interpreting": "\u{f2a3}",
"fa-anchor": "\u{f13d}",
"fa-android": "\u{f17b}",
"fa-angellist": "\u{f209}",
"fa-angle-double-down": "\u{f103}",
"fa-angle-double-left": "\u{f100}",
"fa-angle-double-right": "\u{f101}",
"fa-angle-double-up": "\u{f102}",
"fa-angle-down": "\u{f107}",
"fa-angle-left": "\u{f104}",
"fa-angle-right": "\u{f105}",
"fa-angle-up": "\u{f106}",
"fa-apple": "\u{f179}",
"fa-archive": "\u{f187}",
"fa-area-chart": "\u{f1fe}",
"fa-arrow-circle-down": "\u{f0ab}",
"fa-arrow-circle-left": "\u{f0a8}",
"fa-arrow-circle-o-down": "\u{f01a}",
"fa-arrow-circle-o-left": "\u{f190}",
"fa-arrow-circle-o-right": "\u{f18e}",
"fa-arrow-circle-o-up": "\u{f01b}",
"fa-arrow-circle-right": "\u{f0a9}",
"fa-arrow-circle-up": "\u{f0aa}",
"fa-arrow-down": "\u{f063}",
"fa-arrow-left": "\u{f060}",
"fa-arrow-right": "\u{f061}",
"fa-arrow-up": "\u{f062}",
"fa-arrows": "\u{f047}",
"fa-arrows-alt": "\u{f0b2}",
"fa-arrows-h": "\u{f07e}",
"fa-arrows-v": "\u{f07d}",
"fa-asl-interpreting": "\u{f2a3}",
"fa-assistive-listening-systems": "\u{f2a2}",
"fa-asterisk": "\u{f069}",
"fa-at": "\u{f1fa}",
"fa-audio-description": "\u{f29e}",
"fa-automobile": "\u{f1b9}",
"fa-backward": "\u{f04a}",
"fa-balance-scale": "\u{f24e}",
"fa-ban": "\u{f05e}",
"fa-bank": "\u{f19c}",
"fa-bar-chart": "\u{f080}",
"fa-bar-chart-o": "\u{f080}",
"fa-barcode": "\u{f02a}",
"fa-bars": "\u{f0c9}",
"fa-battery-0": "\u{f244}",
"fa-battery-1": "\u{f243}",
"fa-battery-2": "\u{f242}",
"fa-battery-3": "\u{f241}",
"fa-battery-4": "\u{f240}",
"fa-battery-empty": "\u{f244}",
"fa-battery-full": "\u{f240}",
"fa-battery-half": "\u{f242}",
"fa-battery-quarter": "\u{f243}",
"fa-battery-three-quarters": "\u{f241}",
"fa-bed": "\u{f236}",
"fa-beer": "\u{f0fc}",
"fa-behance": "\u{f1b4}",
"fa-behance-square": "\u{f1b5}",
"fa-bell": "\u{f0f3}",
"fa-bell-o": "\u{f0a2}",
"fa-bell-slash": "\u{f1f6}",
"fa-bell-slash-o": "\u{f1f7}",
"fa-bicycle": "\u{f206}",
"fa-binoculars": "\u{f1e5}",
"fa-birthday-cake": "\u{f1fd}",
"fa-bitbucket": "\u{f171}",
"fa-bitbucket-square": "\u{f172}",
"fa-bitcoin": "\u{f15a}",
"fa-black-tie": "\u{f27e}",
"fa-blind": "\u{f29d}",
"fa-bluetooth": "\u{f293}",
"fa-bluetooth-b": "\u{f294}",
"fa-bold": "\u{f032}",
"fa-bolt": "\u{f0e7}",
"fa-bomb": "\u{f1e2}",
"fa-book": "\u{f02d}",
"fa-bookmark": "\u{f02e}",
"fa-bookmark-o": "\u{f097}",
"fa-braille": "\u{f2a1}",
"fa-briefcase": "\u{f0b1}",
"fa-btc": "\u{f15a}",
"fa-bug": "\u{f188}",
"fa-building": "\u{f1ad}",
"fa-building-o": "\u{f0f7}",
"fa-bullhorn": "\u{f0a1}",
"fa-bullseye": "\u{f140}",
"fa-bus": "\u{f207}",
"fa-buysellads": "\u{f20d}",
"fa-cab": "\u{f1ba}",
"fa-calculator": "\u{f1ec}",
"fa-calendar": "\u{f073}",
"fa-calendar-check-o": "\u{f274}",
"fa-calendar-minus-o": "\u{f272}",
"fa-calendar-o": "\u{f133}",
"fa-calendar-plus-o": "\u{f271}",
"fa-calendar-times-o": "\u{f273}",
"fa-camera": "\u{f030}",
"fa-camera-retro": "\u{f083}",
"fa-car": "\u{f1b9}",
"fa-caret-down": "\u{f0d7}",
"fa-caret-left": "\u{f0d9}",
"fa-caret-right": "\u{f0da}",
"fa-caret-square-o-down": "\u{f150}",
"fa-caret-square-o-left": "\u{f191}",
"fa-caret-square-o-right": "\u{f152}",
"fa-caret-square-o-up": "\u{f151}",
"fa-caret-up": "\u{f0d8}",
"fa-cart-arrow-down": "\u{f218}",
"fa-cart-plus": "\u{f217}",
"fa-cc": "\u{f20a}",
"fa-cc-amex": "\u{f1f3}",
"fa-cc-diners-club": "\u{f24c}",
"fa-cc-discover": "\u{f1f2}",
"fa-cc-jcb": "\u{f24b}",
"fa-cc-mastercard": "\u{f1f1}",
"fa-cc-paypal": "\u{f1f4}",
"fa-cc-stripe": "\u{f1f5}",
"fa-cc-visa": "\u{f1f0}",
"fa-certificate": "\u{f0a3}",
"fa-chain": "\u{f0c1}",
"fa-chain-broken": "\u{f127}",
"fa-check": "\u{f00c}",
"fa-check-circle": "\u{f058}",
"fa-check-circle-o": "\u{f05d}",
"fa-check-square": "\u{f14a}",
"fa-check-square-o": "\u{f046}",
"fa-chevron-circle-down": "\u{f13a}",
"fa-chevron-circle-left": "\u{f137}",
"fa-chevron-circle-right": "\u{f138}",
"fa-chevron-circle-up": "\u{f139}",
"fa-chevron-down": "\u{f078}",
"fa-chevron-left": "\u{f053}",
"fa-chevron-right": "\u{f054}",
"fa-chevron-up": "\u{f077}",
"fa-child": "\u{f1ae}",
"fa-chrome": "\u{f268}",
"fa-circle": "\u{f111}",
"fa-circle-o": "\u{f10c}",
"fa-circle-o-notch": "\u{f1ce}",
"fa-circle-thin": "\u{f1db}",
"fa-clipboard": "\u{f0ea}",
"fa-clock-o": "\u{f017}",
"fa-clone": "\u{f24d}",
"fa-close": "\u{f00d}",
"fa-cloud": "\u{f0c2}",
"fa-cloud-download": "\u{f0ed}",
"fa-cloud-upload": "\u{f0ee}",
"fa-cny": "\u{f157}",
"fa-code": "\u{f121}",
"fa-code-fork": "\u{f126}",
"fa-codepen": "\u{f1cb}",
"fa-codiepie": "\u{f284}",
"fa-coffee": "\u{f0f4}",
"fa-cog": "\u{f013}",
"fa-cogs": "\u{f085}",
"fa-columns": "\u{f0db}",
"fa-comment": "\u{f075}",
"fa-comment-o": "\u{f0e5}",
"fa-commenting": "\u{f27a}",
"fa-commenting-o": "\u{f27b}",
"fa-comments": "\u{f086}",
"fa-comments-o": "\u{f0e6}",
"fa-compass": "\u{f14e}",
"fa-compress": "\u{f066}",
"fa-connectdevelop": "\u{f20e}",
"fa-contao": "\u{f26d}",
"fa-copy": "\u{f0c5}",
"fa-copyright": "\u{f1f9}",
"fa-creative-commons": "\u{f25e}",
"fa-credit-card": "\u{f09d}",
"fa-credit-card-alt": "\u{f283}",
"fa-crop": "\u{f125}",
"fa-crosshairs": "\u{f05b}",
"fa-css3": "\u{f13c}",
"fa-cube": "\u{f1b2}",
"fa-cubes": "\u{f1b3}",
"fa-cut": "\u{f0c4}",
"fa-cutlery": "\u{f0f5}",
"fa-dashboard": "\u{f0e4}",
"fa-dashcube": "\u{f210}",
"fa-database": "\u{f1c0}",
"fa-deaf": "\u{f2a4}",
"fa-deafness": "\u{f2a4}",
"fa-dedent": "\u{f03b}",
"fa-delicious": "\u{f1a5}",
"fa-desktop": "\u{f108}",
"fa-deviantart": "\u{f1bd}",
"fa-diamond": "\u{f219}",
"fa-digg": "\u{f1a6}",
"fa-dollar": "\u{f155}",
"fa-dot-circle-o": "\u{f192}",
"fa-download": "\u{f019}",
"fa-dribbble": "\u{f17d}",
"fa-dropbox": "\u{f16b}",
"fa-drupal": "\u{f1a9}",
"fa-edge": "\u{f282}",
"fa-edit": "\u{f044}",
"fa-eject": "\u{f052}",
"fa-ellipsis-h": "\u{f141}",
"fa-ellipsis-v": "\u{f142}",
"fa-empire": "\u{f1d1}",
"fa-envelope": "\u{f0e0}",
"fa-envelope-o": "\u{f003}",
"fa-envelope-square": "\u{f199}",
"fa-envira": "\u{f299}",
"fa-eraser": "\u{f12d}",
"fa-eur": "\u{f153}",
"fa-euro": "\u{f153}",
"fa-exchange": "\u{f0ec}",
"fa-exclamation": "\u{f12a}",
"fa-exclamation-circle": "\u{f06a}",
"fa-exclamation-triangle": "\u{f071}",
"fa-expand": "\u{f065}",
"fa-expeditedssl": "\u{f23e}",
"fa-external-link": "\u{f08e}",
"fa-external-link-square": "\u{f14c}",
"fa-eye": "\u{f06e}",
"fa-eye-slash": "\u{f070}",
"fa-eyedropper": "\u{f1fb}",
"fa-fa": "\u{f2b4}",
"fa-facebook": "\u{f09a}",
"fa-facebook-f": "\u{f09a}",
"fa-facebook-official": "\u{f230}",
"fa-facebook-square": "\u{f082}",
"fa-fast-backward": "\u{f049}",
"fa-fast-forward": "\u{f050}",
"fa-fax": "\u{f1ac}",
"fa-feed": "\u{f09e}",
"fa-female": "\u{f182}",
"fa-fighter-jet": "\u{f0fb}",
"fa-file": "\u{f15b}",
"fa-file-archive-o": "\u{f1c6}",
"fa-file-audio-o": "\u{f1c7}",
"fa-file-code-o": "\u{f1c9}",
"fa-file-excel-o": "\u{f1c3}",
"fa-file-image-o": "\u{f1c5}",
"fa-file-movie-o": "\u{f1c8}",
"fa-file-o": "\u{f016}",
"fa-file-pdf-o": "\u{f1c1}",
"fa-file-photo-o": "\u{f1c5}",
"fa-file-picture-o": "\u{f1c5}",
"fa-file-powerpoint-o": "\u{f1c4}",
"fa-file-sound-o": "\u{f1c7}",
"fa-file-text": "\u{f15c}",
"fa-file-text-o": "\u{f0f6}",
"fa-file-video-o": "\u{f1c8}",
"fa-file-word-o": "\u{f1c2}",
"fa-file-zip-o": "\u{f1c6}",
"fa-files-o": "\u{f0c5}",
"fa-film": "\u{f008}",
"fa-filter": "\u{f0b0}",
"fa-fire": "\u{f06d}",
"fa-fire-extinguisher": "\u{f134}",
"fa-firefox": "\u{f269}",
"fa-first-order": "\u{f2b0}",
"fa-flag": "\u{f024}",
"fa-flag-checkered": "\u{f11e}",
"fa-flag-o": "\u{f11d}",
"fa-flash": "\u{f0e7}",
"fa-flask": "\u{f0c3}",
"fa-flickr": "\u{f16e}",
"fa-floppy-o": "\u{f0c7}",
"fa-folder": "\u{f07b}",
"fa-folder-o": "\u{f114}",
"fa-folder-open": "\u{f07c}",
"fa-folder-open-o": "\u{f115}",
"fa-font": "\u{f031}",
"fa-font-awesome": "\u{f2b4}",
"fa-fonticons": "\u{f280}",
"fa-fort-awesome": "\u{f286}",
"fa-forumbee": "\u{f211}",
"fa-forward": "\u{f04e}",
"fa-foursquare": "\u{f180}",
"fa-frown-o": "\u{f119}",
"fa-futbol-o": "\u{f1e3}",
"fa-gamepad": "\u{f11b}",
"fa-gavel": "\u{f0e3}",
"fa-gbp": "\u{f154}",
"fa-ge": "\u{f1d1}",
"fa-gear": "\u{f013}",
"fa-gears": "\u{f085}",
"fa-genderless": "\u{f22d}",
"fa-get-pocket": "\u{f265}",
"fa-gg": "\u{f260}",
"fa-gg-circle": "\u{f261}",
"fa-gift": "\u{f06b}",
"fa-git": "\u{f1d3}",
"fa-git-square": "\u{f1d2}",
"fa-github": "\u{f09b}",
"fa-github-alt": "\u{f113}",
"fa-github-square": "\u{f092}",
"fa-gitlab": "\u{f296}",
"fa-gittip": "\u{f184}",
"fa-glass": "\u{f000}",
"fa-glide": "\u{f2a5}",
"fa-glide-g": "\u{f2a6}",
"fa-globe": "\u{f0ac}",
"fa-google": "\u{f1a0}",
"fa-google-plus": "\u{f0d5}",
"fa-google-plus-circle": "\u{f2b3}",
"fa-google-plus-official": "\u{f2b3}",
"fa-google-plus-square": "\u{f0d4}",
"fa-google-wallet": "\u{f1ee}",
"fa-graduation-cap": "\u{f19d}",
"fa-gratipay": "\u{f184}",
"fa-group": "\u{f0c0}",
"fa-h-square": "\u{f0fd}",
"fa-hacker-news": "\u{f1d4}",
"fa-hand-grab-o": "\u{f255}",
"fa-hand-lizard-o": "\u{f258}",
"fa-hand-o-down": "\u{f0a7}",
"fa-hand-o-left": "\u{f0a5}",
"fa-hand-o-right": "\u{f0a4}",
"fa-hand-o-up": "\u{f0a6}",
"fa-hand-paper-o": "\u{f256}",
"fa-hand-peace-o": "\u{f25b}",
"fa-hand-pointer-o": "\u{f25a}",
"fa-hand-rock-o": "\u{f255}",
"fa-hand-scissors-o": "\u{f257}",
"fa-hand-spock-o": "\u{f259}",
"fa-hand-stop-o": "\u{f256}",
"fa-hard-of-hearing": "\u{f2a4}",
"fa-hashtag": "\u{f292}",
"fa-hdd-o": "\u{f0a0}",
"fa-header": "\u{f1dc}",
"fa-headphones": "\u{f025}",
"fa-heart": "\u{f004}",
"fa-heart-o": "\u{f08a}",
"fa-heartbeat": "\u{f21e}",
"fa-history": "\u{f1da}",
"fa-home": "\u{f015}",
"fa-hospital-o": "\u{f0f8}",
"fa-hotel": "\u{f236}",
"fa-hourglass": "\u{f254}",
"fa-hourglass-1": "\u{f251}",
"fa-hourglass-2": "\u{f252}",
"fa-hourglass-3": "\u{f253}",
"fa-hourglass-end": "\u{f253}",
"fa-hourglass-half": "\u{f252}",
"fa-hourglass-o": "\u{f250}",
"fa-hourglass-start": "\u{f251}",
"fa-houzz": "\u{f27c}",
"fa-html5": "\u{f13b}",
"fa-i-cursor": "\u{f246}",
"fa-ils": "\u{f20b}",
"fa-image": "\u{f03e}",
"fa-inbox": "\u{f01c}",
"fa-indent": "\u{f03c}",
"fa-industry": "\u{f275}",
"fa-info": "\u{f129}",
"fa-info-circle": "\u{f05a}",
"fa-inr": "\u{f156}",
"fa-instagram": "\u{f16d}",
"fa-institution": "\u{f19c}",
"fa-internet-explorer": "\u{f26b}",
"fa-intersex": "\u{f224}",
"fa-ioxhost": "\u{f208}",
"fa-italic": "\u{f033}",
"fa-joomla": "\u{f1aa}",
"fa-jpy": "\u{f157}",
"fa-jsfiddle": "\u{f1cc}",
"fa-key": "\u{f084}",
"fa-keyboard-o": "\u{f11c}",
"fa-krw": "\u{f159}",
"fa-language": "\u{f1ab}",
"fa-laptop": "\u{f109}",
"fa-lastfm": "\u{f202}",
"fa-lastfm-square": "\u{f203}",
"fa-leaf": "\u{f06c}",
"fa-leanpub": "\u{f212}",
"fa-legal": "\u{f0e3}",
"fa-lemon-o": "\u{f094}",
"fa-level-down": "\u{f149}",
"fa-level-up": "\u{f148}",
"fa-life-bouy": "\u{f1cd}",
"fa-life-buoy": "\u{f1cd}",
"fa-life-ring": "\u{f1cd}",
"fa-life-saver": "\u{f1cd}",
"fa-lightbulb-o": "\u{f0eb}",
"fa-line-chart": "\u{f201}",
"fa-link": "\u{f0c1}",
"fa-linkedin": "\u{f0e1}",
"fa-linkedin-square": "\u{f08c}",
"fa-linux": "\u{f17c}",
"fa-list": "\u{f03a}",
"fa-list-alt": "\u{f022}",
"fa-list-ol": "\u{f0cb}",
"fa-list-ul": "\u{f0ca}",
"fa-location-arrow": "\u{f124}",
"fa-lock": "\u{f023}",
"fa-long-arrow-down": "\u{f175}",
"fa-long-arrow-left": "\u{f177}",
"fa-long-arrow-right": "\u{f178}",
"fa-long-arrow-up": "\u{f176}",
"fa-low-vision": "\u{f2a8}",
"fa-magic": "\u{f0d0}",
"fa-magnet": "\u{f076}",
"fa-mail-forward": "\u{f064}",
"fa-mail-reply": "\u{f112}",
"fa-mail-reply-all": "\u{f122}",
"fa-male": "\u{f183}",
"fa-map": "\u{f279}",
"fa-map-marker": "\u{f041}",
"fa-map-o": "\u{f278}",
"fa-map-pin": "\u{f276}",
"fa-map-signs": "\u{f277}",
"fa-mars": "\u{f222}",
"fa-mars-double": "\u{f227}",
"fa-mars-stroke": "\u{f229}",
"fa-mars-stroke-h": "\u{f22b}",
"fa-mars-stroke-v": "\u{f22a}",
"fa-maxcdn": "\u{f136}",
"fa-meanpath": "\u{f20c}",
"fa-medium": "\u{f23a}",
"fa-medkit": "\u{f0fa}",
"fa-meh-o": "\u{f11a}",
"fa-mercury": "\u{f223}",
"fa-microphone": "\u{f130}",
"fa-microphone-slash": "\u{f131}",
"fa-minus": "\u{f068}",
"fa-minus-circle": "\u{f056}",
"fa-minus-square": "\u{f146}",
"fa-minus-square-o": "\u{f147}",
"fa-mixcloud": "\u{f289}",
"fa-mobile": "\u{f10b}",
"fa-mobile-phone": "\u{f10b}",
"fa-modx": "\u{f285}",
"fa-money": "\u{f0d6}",
"fa-moon-o": "\u{f186}",
"fa-mortar-board": "\u{f19d}",
"fa-motorcycle": "\u{f21c}",
"fa-mouse-pointer": "\u{f245}",
"fa-music": "\u{f001}",
"fa-navicon": "\u{f0c9}",
"fa-neuter": "\u{f22c}",
"fa-newspaper-o": "\u{f1ea}",
"fa-object-group": "\u{f247}",
"fa-object-ungroup": "\u{f248}",
"fa-odnoklassniki": "\u{f263}",
"fa-odnoklassniki-square": "\u{f264}",
"fa-opencart": "\u{f23d}",
"fa-openid": "\u{f19b}",
"fa-opera": "\u{f26a}",
"fa-optin-monster": "\u{f23c}",
"fa-outdent": "\u{f03b}",
"fa-pagelines": "\u{f18c}",
"fa-paint-brush": "\u{f1fc}",
"fa-paper-plane": "\u{f1d8}",
"fa-paper-plane-o": "\u{f1d9}",
"fa-paperclip": "\u{f0c6}",
"fa-paragraph": "\u{f1dd}",
"fa-paste": "\u{f0ea}",
"fa-pause": "\u{f04c}",
"fa-pause-circle": "\u{f28b}",
"fa-pause-circle-o": "\u{f28c}",
"fa-paw": "\u{f1b0}",
"fa-paypal": "\u{f1ed}",
"fa-pencil": "\u{f040}",
"fa-pencil-square": "\u{f14b}",
"fa-pencil-square-o": "\u{f044}",
"fa-percent": "\u{f295}",
"fa-phone": "\u{f095}",
"fa-phone-square": "\u{f098}",
"fa-photo": "\u{f03e}",
"fa-picture-o": "\u{f03e}",
"fa-pie-chart": "\u{f200}",
"fa-pied-piper": "\u{f2ae}",
"fa-pied-piper-alt": "\u{f1a8}",
"fa-pied-piper-pp": "\u{f1a7}",
"fa-pinterest": "\u{f0d2}",
"fa-pinterest-p": "\u{f231}",
"fa-pinterest-square": "\u{f0d3}",
"fa-plane": "\u{f072}",
"fa-play": "\u{f04b}",
"fa-play-circle": "\u{f144}",
"fa-play-circle-o": "\u{f01d}",
"fa-plug": "\u{f1e6}",
"fa-plus": "\u{f067}",
"fa-plus-circle": "\u{f055}",
"fa-plus-square": "\u{f0fe}",
"fa-plus-square-o": "\u{f196}",
"fa-power-off": "\u{f011}",
"fa-print": "\u{f02f}",
"fa-product-hunt": "\u{f288}",
"fa-puzzle-piece": "\u{f12e}",
"fa-qq": "\u{f1d6}",
"fa-qrcode": "\u{f029}",
"fa-question": "\u{f128}",
"fa-question-circle": "\u{f059}",
"fa-question-circle-o": "\u{f29c}",
"fa-quote-left": "\u{f10d}",
"fa-quote-right": "\u{f10e}",
"fa-ra": "\u{f1d0}",
"fa-random": "\u{f074}",
"fa-rebel": "\u{f1d0}",
"fa-recycle": "\u{f1b8}",
"fa-reddit": "\u{f1a1}",
"fa-reddit-alien": "\u{f281}",
"fa-reddit-square": "\u{f1a2}",
"fa-refresh": "\u{f021}",
"fa-registered": "\u{f25d}",
"fa-remove": "\u{f00d}",
"fa-renren": "\u{f18b}",
"fa-reorder": "\u{f0c9}",
"fa-repeat": "\u{f01e}",
"fa-reply": "\u{f112}",
"fa-reply-all": "\u{f122}",
"fa-resistance": "\u{f1d0}",
"fa-retweet": "\u{f079}",
"fa-rmb": "\u{f157}",
"fa-road": "\u{f018}",
"fa-rocket": "\u{f135}",
"fa-rotate-left": "\u{f0e2}",
"fa-rotate-right": "\u{f01e}",
"fa-rouble": "\u{f158}",
"fa-rss": "\u{f09e}",
"fa-rss-square": "\u{f143}",
"fa-rub": "\u{f158}",
"fa-ruble": "\u{f158}",
"fa-rupee": "\u{f156}",
"fa-safari": "\u{f267}",
"fa-save": "\u{f0c7}",
"fa-scissors": "\u{f0c4}",
"fa-scribd": "\u{f28a}",
"fa-search": "\u{f002}",
"fa-search-minus": "\u{f010}",
"fa-search-plus": "\u{f00e}",
"fa-sellsy": "\u{f213}",
"fa-send": "\u{f1d8}",
"fa-send-o": "\u{f1d9}",
"fa-server": "\u{f233}",
"fa-share": "\u{f064}",
"fa-share-alt": "\u{f1e0}",
"fa-share-alt-square": "\u{f1e1}",
"fa-share-square": "\u{f14d}",
"fa-share-square-o": "\u{f045}",
"fa-shekel": "\u{f20b}",
"fa-sheqel": "\u{f20b}",
"fa-shield": "\u{f132}",
"fa-ship": "\u{f21a}",
"fa-shirtsinbulk": "\u{f214}",
"fa-shopping-bag": "\u{f290}",
"fa-shopping-basket": "\u{f291}",
"fa-shopping-cart": "\u{f07a}",
"fa-sign-in": "\u{f090}",
"fa-sign-language": "\u{f2a7}",
"fa-sign-out": "\u{f08b}",
"fa-signal": "\u{f012}",
"fa-signing": "\u{f2a7}",
"fa-simplybuilt": "\u{f215}",
"fa-sitemap": "\u{f0e8}",
"fa-skyatlas": "\u{f216}",
"fa-skype": "\u{f17e}",
"fa-slack": "\u{f198}",
"fa-sliders": "\u{f1de}",
"fa-slideshare": "\u{f1e7}",
"fa-smile-o": "\u{f118}",
"fa-snapchat": "\u{f2ab}",
"fa-snapchat-ghost": "\u{f2ac}",
"fa-snapchat-square": "\u{f2ad}",
"fa-soccer-ball-o": "\u{f1e3}",
"fa-sort": "\u{f0dc}",
"fa-sort-alpha-asc": "\u{f15d}",
"fa-sort-alpha-desc": "\u{f15e}",
"fa-sort-amount-asc": "\u{f160}",
"fa-sort-amount-desc": "\u{f161}",
"fa-sort-asc": "\u{f0de}",
"fa-sort-desc": "\u{f0dd}",
"fa-sort-down": "\u{f0dd}",
"fa-sort-numeric-asc": "\u{f162}",
"fa-sort-numeric-desc": "\u{f163}",
"fa-sort-up": "\u{f0de}",
"fa-soundcloud": "\u{f1be}",
"fa-space-shuttle": "\u{f197}",
"fa-spinner": "\u{f110}",
"fa-spoon": "\u{f1b1}",
"fa-spotify": "\u{f1bc}",
"fa-square": "\u{f0c8}",
"fa-square-o": "\u{f096}",
"fa-stack-exchange": "\u{f18d}",
"fa-stack-overflow": "\u{f16c}",
"fa-star": "\u{f005}",
"fa-star-half": "\u{f089}",
"fa-star-half-empty": "\u{f123}",
"fa-star-half-full": "\u{f123}",
"fa-star-half-o": "\u{f123}",
"fa-star-o": "\u{f006}",
"fa-steam": "\u{f1b6}",
"fa-steam-square": "\u{f1b7}",
"fa-step-backward": "\u{f048}",
"fa-step-forward": "\u{f051}",
"fa-stethoscope": "\u{f0f1}",
"fa-sticky-note": "\u{f249}",
"fa-sticky-note-o": "\u{f24a}",
"fa-stop": "\u{f04d}",
"fa-stop-circle": "\u{f28d}",
"fa-stop-circle-o": "\u{f28e}",
"fa-street-view": "\u{f21d}",
"fa-strikethrough": "\u{f0cc}",
"fa-stumbleupon": "\u{f1a4}",
"fa-stumbleupon-circle": "\u{f1a3}",
"fa-subscript": "\u{f12c}",
"fa-subway": "\u{f239}",
"fa-suitcase": "\u{f0f2}",
"fa-sun-o": "\u{f185}",
"fa-superscript": "\u{f12b}",
"fa-support": "\u{f1cd}",
"fa-table": "\u{f0ce}",
"fa-tablet": "\u{f10a}",
"fa-tachometer": "\u{f0e4}",
"fa-tag": "\u{f02b}",
"fa-tags": "\u{f02c}",
"fa-tasks": "\u{f0ae}",
"fa-taxi": "\u{f1ba}",
"fa-television": "\u{f26c}",
"fa-tencent-weibo": "\u{f1d5}",
"fa-terminal": "\u{f120}",
"fa-text-height": "\u{f034}",
"fa-text-width": "\u{f035}",
"fa-th": "\u{f00a}",
"fa-th-large": "\u{f009}",
"fa-th-list": "\u{f00b}",
"fa-themeisle": "\u{f2b2}",
"fa-thumb-tack": "\u{f08d}",
"fa-thumbs-down": "\u{f165}",
"fa-thumbs-o-down": "\u{f088}",
"fa-thumbs-o-up": "\u{f087}",
"fa-thumbs-up": "\u{f164}",
"fa-ticket": "\u{f145}",
"fa-times": "\u{f00d}",
"fa-times-circle": "\u{f057}",
"fa-times-circle-o": "\u{f05c}",
"fa-tint": "\u{f043}",
"fa-toggle-down": "\u{f150}",
"fa-toggle-left": "\u{f191}",
"fa-toggle-off": "\u{f204}",
"fa-toggle-on": "\u{f205}",
"fa-toggle-right": "\u{f152}",
"fa-toggle-up": "\u{f151}",
"fa-trademark": "\u{f25c}",
"fa-train": "\u{f238}",
"fa-transgender": "\u{f224}",
"fa-transgender-alt": "\u{f225}",
"fa-trash": "\u{f1f8}",
"fa-trash-o": "\u{f014}",
"fa-tree": "\u{f1bb}",
"fa-trello": "\u{f181}",
"fa-tripadvisor": "\u{f262}",
"fa-trophy": "\u{f091}",
"fa-truck": "\u{f0d1}",
"fa-try": "\u{f195}",
"fa-tty": "\u{f1e4}",
"fa-tumblr": "\u{f173}",
"fa-tumblr-square": "\u{f174}",
"fa-turkish-lira": "\u{f195}",
"fa-tv": "\u{f26c}",
"fa-twitch": "\u{f1e8}",
"fa-twitter": "\u{f099}",
"fa-twitter-square": "\u{f081}",
"fa-umbrella": "\u{f0e9}",
"fa-underline": "\u{f0cd}",
"fa-undo": "\u{f0e2}",
"fa-universal-access": "\u{f29a}",
"fa-university": "\u{f19c}",
"fa-unlink": "\u{f127}",
"fa-unlock": "\u{f09c}",
"fa-unlock-alt": "\u{f13e}",
"fa-unsorted": "\u{f0dc}",
"fa-upload": "\u{f093}",
"fa-usb": "\u{f287}",
"fa-usd": "\u{f155}",
"fa-user": "\u{f007}",
"fa-user-md": "\u{f0f0}",
"fa-user-plus": "\u{f234}",
"fa-user-secret": "\u{f21b}",
"fa-user-times": "\u{f235}",
"fa-users": "\u{f0c0}",
"fa-venus": "\u{f221}",
"fa-venus-double": "\u{f226}",
"fa-venus-mars": "\u{f228}",
"fa-viacoin": "\u{f237}",
"fa-viadeo": "\u{f2a9}",
"fa-viadeo-square": "\u{f2aa}",
"fa-video-camera": "\u{f03d}",
"fa-vimeo": "\u{f27d}",
"fa-vimeo-square": "\u{f194}",
"fa-vine": "\u{f1ca}",
"fa-vk": "\u{f189}",
"fa-volume-control-phone": "\u{f2a0}",
"fa-volume-down": "\u{f027}",
"fa-volume-off": "\u{f026}",
"fa-volume-up": "\u{f028}",
"fa-warning": "\u{f071}",
"fa-wechat": "\u{f1d7}",
"fa-weibo": "\u{f18a}",
"fa-weixin": "\u{f1d7}",
"fa-whatsapp": "\u{f232}",
"fa-wheelchair": "\u{f193}",
"fa-wheelchair-alt": "\u{f29b}",
"fa-wifi": "\u{f1eb}",
"fa-wikipedia-w": "\u{f266}",
"fa-windows": "\u{f17a}",
"fa-won": "\u{f159}",
"fa-wordpress": "\u{f19a}",
"fa-wpbeginner": "\u{f297}",
"fa-wpforms": "\u{f298}",
"fa-wrench": "\u{f0ad}",
"fa-xing": "\u{f168}",
"fa-xing-square": "\u{f169}",
"fa-y-combinator": "\u{f23b}",
"fa-y-combinator-square": "\u{f1d4}",
"fa-yahoo": "\u{f19e}",
"fa-yc": "\u{f23b}",
"fa-yc-square": "\u{f1d4}",
"fa-yelp": "\u{f1e9}",
"fa-yen": "\u{f157}",
"fa-yoast": "\u{f2b1}",
"fa-youtube": "\u{f167}",
"fa-youtube-play": "\u{f16a}",
"fa-youtube-square": "\u{f166}"
]
|
apache-2.0
|
ce24aa3640e5068dde8255b18aa435d3
| 31.098601 | 120 | 0.52555 | 2.456409 | false | false | false | false |
squarefrog/TraktTopTen
|
TraktTopTen/Models/CollectionViewDataSource.swift
|
1
|
1453
|
//
// CollectionViewDataSource.swift
// TraktTopTen
//
// Created by Paul Williamson on 05/04/2015.
// Copyright (c) 2015 Paul Williamson. All rights reserved.
//
import UIKit
class CollectionViewDataSource : NSObject, UICollectionViewDataSource {
private var items = [MediaItem]()
private var collectionView: UICollectionView
init(collectionView: UICollectionView) {
self.collectionView = collectionView
}
func updateData(items: [MediaItem]) {
self.items = items;
collectionView.reloadData()
}
func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return self.items.count
}
func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return 1
}
func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier("Cell", forIndexPath: indexPath) as! MediaItemCell
let movie = self.items[indexPath.row]
cell.textLabel.text = "\(movie.title)"
if let url = movie.banner {
cell.imageView.hnk_setImageFromURL(url)
}
return cell
}
func mediaItemForIndexPath(indexPath: NSIndexPath) -> MediaItem {
return items[indexPath.item]
}
}
|
mit
|
96e779858e64c980c8d540298189eede
| 28.06 | 130 | 0.669649 | 5.483019 | false | false | false | false |
arvedviehweger/swift
|
benchmark/single-source/DropLast.swift
|
1
|
6049
|
//===--- DropLast.swift ---------------------------------------*- swift -*-===//
//
// 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
//
//===----------------------------------------------------------------------===//
////////////////////////////////////////////////////////////////////////////////
// WARNING: This file is manually generated from .gyb template and should not
// be directly modified. Instead, make changes to DropLast.swift.gyb and run
// scripts/generate_harness/generate_harness.py to regenerate this file.
////////////////////////////////////////////////////////////////////////////////
import TestsUtils
let sequenceCount = 4096
let prefixCount = 1024
let dropCount = sequenceCount - prefixCount
let sumCount = prefixCount * (prefixCount - 1) / 2
@inline(never)
public func run_DropLastCountableRange(_ N: Int) {
let s = 0..<sequenceCount
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastCountableRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastSequence(_ N: Int) {
let s = sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastSequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySequence(_ N: Int) {
let s = AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySequence: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySeqCntRange(_ N: Int) {
let s = AnySequence(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySeqCntRange: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIter(_ N: Int) {
let s = AnySequence((0..<sequenceCount).makeIterator())
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySeqCRangeIter: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnyCollection(_ N: Int) {
let s = AnyCollection(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnyCollection: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastArray(_ N: Int) {
let s = Array(0..<sequenceCount)
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastArray: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastCountableRangeLazy(_ N: Int) {
let s = (0..<sequenceCount).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastCountableRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastSequenceLazy(_ N: Int) {
let s = (sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil }).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastSequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySequenceLazy(_ N: Int) {
let s = (AnySequence(sequence(first: 0) { $0 < sequenceCount - 1 ? $0 &+ 1 : nil })).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySequenceLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySeqCntRangeLazy(_ N: Int) {
let s = (AnySequence(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySeqCntRangeLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnySeqCRangeIterLazy(_ N: Int) {
let s = (AnySequence((0..<sequenceCount).makeIterator())).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnySeqCRangeIterLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastAnyCollectionLazy(_ N: Int) {
let s = (AnyCollection(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastAnyCollectionLazy: \(result) != \(sumCount)")
}
}
@inline(never)
public func run_DropLastArrayLazy(_ N: Int) {
let s = (Array(0..<sequenceCount)).lazy
for _ in 1...20*N {
var result = 0
for element in s.dropLast(dropCount) {
result += element
}
CheckResults(result == sumCount,
"IncorrectResults in DropLastArrayLazy: \(result) != \(sumCount)")
}
}
|
apache-2.0
|
06b49e2af89aa153397470865b97a0eb
| 30.341969 | 91 | 0.620102 | 3.880051 | false | false | false | false |
chenchangqing/travelMapMvvm
|
travelMapMvvm/travelMapMvvm/Views/Cell/POICell.swift
|
1
|
1404
|
//
// POICell.swift
// travelMap
//
// Created by green on 15/6/10.
// Copyright (c) 2015年 com.city8. All rights reserved.
//
import UIKit
import ReactiveCocoa
class POICell: UITableViewCell, ReactiveView {
@IBOutlet weak var poiPic: UIImageView!
@IBOutlet weak var star: RatingBar!
@IBOutlet weak var score: UILabel!
@IBOutlet weak var poiName: UILabel!
private var poiImageViewModel = ImageViewModel(urlString: nil)
// MARK: - init
override func awakeFromNib() {
super.awakeFromNib()
// Observe
RACObserve(poiImageViewModel, "image") ~> RAC(poiPic,"image")
self.rac_prepareForReuseSignal.subscribeNext { (any:AnyObject!) -> Void in
self.poiPic.image = nil
}
}
// MARK: - ReactiveView
func bindViewModel(viewModel: AnyObject) {
if let viewModel = viewModel as? POIModel {
if let level=viewModel.level {
self.star.rating = CGFloat(level.index+1)
}
score.text = viewModel.score
poiName.text = viewModel.poiName
// 加载小编头像图片
poiImageViewModel.urlString = viewModel.poiPicUrl
poiImageViewModel.downloadImageCommand.execute(nil)
}
}
}
|
apache-2.0
|
40e8d97e884c56a349fdc49e9eafd570
| 24.2 | 82 | 0.568543 | 4.746575 | false | false | false | false |
xedin/swift
|
test/Parse/type_expr.swift
|
1
|
14260
|
// RUN: %target-typecheck-verify-swift -swift-version 4
// not ready: dont_run: %target-typecheck-verify-swift -enable-astscope-lookup -swift-version 4
// Types in expression contexts must be followed by a member access or
// constructor call.
struct Foo {
struct Bar {
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int = 0
static func meth() {}
func instMeth() {}
}
protocol Zim {
associatedtype Zang
init()
// TODO class var prop: Int { get }
static func meth() {} // expected-error{{protocol methods must not have bodies}}
func instMeth() {} // expected-error{{protocol methods must not have bodies}}
}
protocol Bad {
init() {} // expected-error{{protocol initializers must not have bodies}}
}
struct Gen<T> {
struct Bar {
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
init() {}
static var prop: Int { return 0 }
static func meth() {}
func instMeth() {}
}
func unqualifiedType() {
_ = Foo.self
_ = Foo.self
_ = Foo()
_ = Foo.prop
_ = Foo.meth
let _ : () = Foo.meth()
_ = Foo.instMeth
_ = Foo // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{10-10=()}} expected-note{{use '.self'}} {{10-10=.self}}
_ = Foo.dynamicType // expected-error {{type 'Foo' has no member 'dynamicType'}}
// expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{10-22=)}}
_ = Bad // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}{{10-10=.self}}
}
func qualifiedType() {
_ = Foo.Bar.self
let _ : Foo.Bar.Type = Foo.Bar.self
let _ : Foo.Protocol = Foo.self // expected-error{{cannot use 'Protocol' with non-protocol type 'Foo'}}
_ = Foo.Bar()
_ = Foo.Bar.prop
_ = Foo.Bar.meth
let _ : () = Foo.Bar.meth()
_ = Foo.Bar.instMeth
_ = Foo.Bar // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{14-14=()}} expected-note{{use '.self'}} {{14-14=.self}}
_ = Foo.Bar.dynamicType // expected-error {{type 'Foo.Bar' has no member 'dynamicType'}}
// expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{14-26=)}}
}
// We allow '.Type' in expr context
func metaType() {
let _ = Foo.Type.self
let _ = Foo.Type.self
let _ = Foo.Type // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1 {{use '.self' to reference the type object}}
let _ = type(of: Foo.Type) // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1 {{use '.self' to reference the type object}}
}
func genType() {
_ = Gen<Foo>.self
_ = Gen<Foo>()
_ = Gen<Foo>.prop
_ = Gen<Foo>.meth
let _ : () = Gen<Foo>.meth()
_ = Gen<Foo>.instMeth
_ = Gen<Foo> // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{use '.self' to reference the type object}}
// expected-note@-2{{add arguments after the type to construct a value of the type}}
}
func genQualifiedType() {
_ = Gen<Foo>.Bar.self
_ = Gen<Foo>.Bar()
_ = Gen<Foo>.Bar.prop
_ = Gen<Foo>.Bar.meth
let _ : () = Gen<Foo>.Bar.meth()
_ = Gen<Foo>.Bar.instMeth
_ = Gen<Foo>.Bar // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{add arguments after the type to construct a value of the type}}
// expected-note@-2{{use '.self' to reference the type object}}
_ = Gen<Foo>.Bar.dynamicType // expected-error {{type 'Gen<Foo>.Bar' has no member 'dynamicType'}}
// expected-error@-1 {{'.dynamicType' is deprecated. Use 'type(of: ...)' instead}} {{7-7=type(of: }} {{19-31=)}}
}
func typeOfShadowing() {
// Try to shadow type(of:)
func type<T>(of t: T.Type, flag: Bool) -> T.Type {
return t
}
func type<T, U>(of t: T.Type, _ : U) -> T.Type {
return t
}
func type<T>(_ t: T.Type) -> T.Type {
return t
}
func type<T>(fo t: T.Type) -> T.Type {
return t
}
// TODO: Errors need improving here.
_ = type(of: Gen<Foo>.Bar) // expected-error{{argument labels '(of:)' do not match any available overloads}}
// expected-note@-1{{overloads for 'type' exist with these partially matching parameter lists: (T.Type), (fo: T.Type)}}
_ = type(Gen<Foo>.Bar) // expected-error{{expected member name or constructor call after type name}}
// expected-note@-1{{add arguments after the type to construct a value of the type}}
// expected-note@-2{{use '.self' to reference the type object}}
_ = type(of: Gen<Foo>.Bar.self, flag: false) // No error here.
_ = type(fo: Foo.Bar.self) // No error here.
_ = type(of: Foo.Bar.self, [1, 2, 3]) // No error here.
}
func archetype<T: Zim>(_: T) {
_ = T.self
_ = T()
// TODO let prop = T.prop
_ = T.meth
let _ : () = T.meth()
_ = T // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{8-8=()}} expected-note{{use '.self'}} {{8-8=.self}}
}
func assocType<T: Zim>(_: T) where T.Zang: Zim {
_ = T.Zang.self
_ = T.Zang()
// TODO _ = T.Zang.prop
_ = T.Zang.meth
let _ : () = T.Zang.meth()
_ = T.Zang // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{13-13=()}} expected-note{{use '.self'}} {{13-13=.self}}
}
class B {
class func baseMethod() {}
}
class D: B {
class func derivedMethod() {}
}
func derivedType() {
let _: B.Type = D.self
_ = D.baseMethod
let _ : () = D.baseMethod()
let _: D.Type = D.self
_ = D.derivedMethod
let _ : () = D.derivedMethod()
let _: B.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
let _: D.Type = D // expected-error{{expected member name or constructor call after type name}} expected-note{{add arguments}} {{20-20=()}} expected-note{{use '.self'}} {{20-20=.self}}
}
// Referencing a nonexistent member or constructor should not trigger errors
// about the type expression.
func nonexistentMember() {
let cons = Foo("this constructor does not exist") // expected-error{{argument passed to call that takes no arguments}}
let prop = Foo.nonexistent // expected-error{{type 'Foo' has no member 'nonexistent'}}
let meth = Foo.nonexistent() // expected-error{{type 'Foo' has no member 'nonexistent'}}
}
protocol P {}
func meta_metatypes() {
let _: P.Protocol = P.self
_ = P.Type.self
_ = P.Protocol.self
_ = P.Protocol.Protocol.self // expected-error{{cannot use 'Protocol' with non-protocol type 'P.Protocol'}}
_ = P.Protocol.Type.self
_ = B.Type.self
}
class E {
private init() {}
}
func inAccessibleInit() {
_ = E // expected-error {{expected member name or constructor call after type name}} expected-note {{use '.self'}} {{8-8=.self}}
}
enum F: Int {
case A, B
}
struct G {
var x: Int
}
func implicitInit() {
_ = F // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}}
_ = G // expected-error {{expected member name or constructor call after type name}} expected-note {{add arguments}} {{8-8=()}} expected-note {{use '.self'}} {{8-8=.self}}
}
// https://bugs.swift.org/browse/SR-502
func testFunctionCollectionTypes() {
_ = [(Int) -> Int]()
_ = [(Int, Int) -> Int]()
_ = [(x: Int, y: Int) -> Int]()
// Make sure associativity is correct
let a = [(Int) -> (Int) -> Int]()
let b: Int = a[0](5)(4)
_ = [String: (Int) -> Int]()
_ = [String: (Int, Int) -> Int]()
_ = [1 -> Int]() // expected-error {{expected type before '->'}}
_ = [Int -> 1]() // expected-error {{expected type after '->'}}
// expected-error@-1 {{single argument function types require parentheses}}
// Should parse () as void type when before or after arrow
_ = [() -> Int]()
_ = [(Int) -> ()]()
_ = 2 + () -> Int // expected-error {{expected type before '->'}}
_ = () -> (Int, Int).2 // expected-error {{expected type after '->'}}
_ = (Int) -> Int // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}}
_ = @convention(c) () -> Int // expected-error{{expected member name or constructor call after type name}} expected-note{{use '.self' to reference the type object}}
_ = 1 + (@convention(c) () -> Int).self // expected-error{{binary operator '+' cannot be applied to operands of type 'Int' and '(@convention(c) () -> Int).Type'}} // expected-note {{expected an argument list of type '(Int, Int)'}}
_ = (@autoclosure () -> Int) -> (Int, Int).2 // expected-error {{expected type after '->'}}
_ = ((@autoclosure () -> Int) -> (Int, Int)).1 // expected-error {{type '(@autoclosure () -> Int) -> (Int, Int)' has no member '1'}}
_ = ((inout Int) -> Void).self
_ = [(Int) throws -> Int]()
_ = [@convention(swift) (Int) throws -> Int]().count
_ = [(inout Int) throws -> (inout () -> Void) -> Void]().count
_ = [String: (@autoclosure (Int) -> Int32) -> Void]().keys // expected-error {{argument type of @autoclosure parameter must be '()'}}
let _ = [(Int) -> throws Int]() // expected-error{{'throws' may only occur before '->'}}
let _ = [Int throws Int](); // expected-error{{'throws' may only occur before '->'}} expected-error {{consecutive statements on a line must be separated by ';'}}
}
protocol P1 {}
protocol P2 {}
protocol P3 {}
func compositionType() {
_ = P1 & P2 // expected-error {{expected member name or constructor call after type name}} expected-note{{use '.self'}} {{7-7=(}} {{14-14=).self}}
_ = P1 & P2.self // expected-error {{binary operator '&' cannot be applied to operands of type 'P1.Protocol' and 'P2.Protocol'}} expected-note {{overloads}}
_ = (P1 & P2).self // Ok.
_ = (P1 & (P2)).self // FIXME: OK? while `typealias P = P1 & (P2)` is rejected.
_ = (P1 & (P2, P3)).self // expected-error {{non-protocol, non-class type '(P2, P3)' cannot be used within a protocol-constrained type}}
_ = (P1 & Int).self // expected-error {{non-protocol, non-class type 'Int' cannot be used within a protocol-constrained type}}
_ = (P1? & P2).self // expected-error {{non-protocol, non-class type 'P1?' cannot be used within a protocol-constrained type}}
_ = (P1 & P2.Type).self // expected-error {{non-protocol, non-class type 'P2.Type' cannot be used within a protocol-constrained type}}
_ = P1 & P2 -> P3
// expected-error @-1 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}}
// expected-error @-2 {{expected member name or constructor call after type name}}
// expected-note @-3 {{use '.self'}} {{7-7=(}} {{20-20=).self}}
_ = P1 & P2 -> P3 & P1 -> Int
// expected-error @-1 {{single argument function types require parentheses}} {{18-18=(}} {{25-25=)}}
// expected-error @-2 {{single argument function types require parentheses}} {{7-7=(}} {{14-14=)}}
// expected-error @-3 {{expected member name or constructor call after type name}}
// expected-note @-4 {{use '.self'}} {{7-7=(}} {{32-32=).self}}
_ = (() -> P1 & P2).self // Ok
_ = (P1 & P2 -> P3 & P2).self // expected-error {{single argument function types require parentheses}} {{8-8=(}} {{15-15=)}}
_ = ((P1 & P2) -> (P3 & P2) -> P1 & Any).self // Ok
}
func complexSequence() {
// (assign_expr
// (discard_assignment_expr)
// (try_expr
// (type_expr typerepr='P1 & P2 throws -> P3 & P1')))
_ = try P1 & P2 throws -> P3 & P1
// expected-warning @-1 {{no calls to throwing functions occur within 'try' expression}}
// expected-error @-2 {{single argument function types require parentheses}} {{none}} {{11-11=(}} {{18-18=)}}
// expected-error @-3 {{expected member name or constructor call after type name}}
// expected-note @-4 {{use '.self' to reference the type object}} {{11-11=(}} {{36-36=).self}}
}
func takesVoid(f: Void -> ()) {} // expected-error {{single argument function types require parentheses}} {{19-23=()}}
func takesOneArg<T>(_: T.Type) {}
func takesTwoArgs<T>(_: T.Type, _: Int) {}
func testMissingSelf() {
// None of these were not caught in Swift 3.
// See test/Compatibility/type_expr.swift.
takesOneArg(Int)
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
takesOneArg(Swift.Int)
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
takesTwoArgs(Int, 0)
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
takesTwoArgs(Swift.Int, 0)
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
Swift.Int // expected-warning {{expression of type 'Int.Type' is unused}}
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
_ = Swift.Int
// expected-error@-1 {{expected member name or constructor call after type name}}
// expected-note@-2 {{add arguments after the type to construct a value of the type}}
// expected-note@-3 {{use '.self' to reference the type object}}
}
|
apache-2.0
|
0683fe0b54b06745e14fd4612baf82d4
| 40.333333 | 232 | 0.623562 | 3.489112 | false | false | false | false |
HabitRPG/habitrpg-ios
|
HabitRPG/UI/TaskSetupViewController.swift
|
1
|
13010
|
//
// TaskSetupViewController.swift
// Habitica
//
// Created by Phillip on 01.08.17.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import UIKit
import Habitica_Models
import ReactiveSwift
enum SetupTaskCategory {
case work, exercise, health, school, team, chores, creativity
//siwftlint:disable:next identifier_name
func createSampleHabit(_ text: String, tagId: String?, positive: Bool, negative: Bool, taskRepository: TaskRepository) -> TaskProtocol {
let task = taskRepository.getNewTask()
task.text = text
task.up = positive
task.down = negative
task.type = "habit"
if let id = tagId {
task.tags = [taskRepository.getNewTag(id: id)]
}
return task
}
func createSampleDaily(_ text: String, tagId: String?, notes: String, taskRepository: TaskRepository) -> TaskProtocol {
let task = taskRepository.getNewTask()
task.text = text
task.notes = notes
task.startDate = Date()
task.type = "daily"
if let id = tagId {
task.tags = [taskRepository.getNewTag(id: id)]
}
return task
}
func createSampleToDo(_ text: String, tagId: String?, notes: String, taskRepository: TaskRepository) -> TaskProtocol {
let task = taskRepository.getNewTask()
task.text = text
task.type = "todo"
task.notes = notes
if let id = tagId {
task.tags = [taskRepository.getNewTag(id: id)]
}
return task
}
func getTasks(tagId: String?, taskRepository: TaskRepository) -> [TaskProtocol] {
switch self {
case .work:
return [
createSampleHabit(L10n.Tasks.Examples.workHabit, tagId: tagId, positive: true, negative: false, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.workDailyText, tagId: tagId, notes: L10n.Tasks.Examples.workDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.workTodoText, tagId: tagId, notes: L10n.Tasks.Examples.workTodoNotes, taskRepository: taskRepository)
]
case .exercise:
return [
createSampleHabit(L10n.Tasks.Examples.exerciseHabit, tagId: tagId, positive: true, negative: false, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.exerciseDailyText, tagId: tagId, notes: L10n.Tasks.Examples.exerciseDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.exerciseTodoText, tagId: tagId, notes: L10n.Tasks.Examples.exerciseTodoNotes, taskRepository: taskRepository)
]
case .health:
return [
createSampleHabit(L10n.Tasks.Examples.healthHabit, tagId: tagId, positive: true, negative: true, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.healthDailyText, tagId: tagId, notes: L10n.Tasks.Examples.healthDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.healthTodoText, tagId: tagId, notes: L10n.Tasks.Examples.healthTodoNotes, taskRepository: taskRepository)
]
case .school:
return [
createSampleHabit(L10n.Tasks.Examples.schoolHabit, tagId: tagId, positive: true, negative: true, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.schoolDailyText, tagId: tagId, notes: L10n.Tasks.Examples.schoolDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.schoolTodoText, tagId: tagId, notes: L10n.Tasks.Examples.schoolTodoNotes, taskRepository: taskRepository)
]
case .team:
return [
createSampleHabit(L10n.Tasks.Examples.teamHabit, tagId: tagId, positive: true, negative: false, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.teamDailyText, tagId: tagId, notes: L10n.Tasks.Examples.teamDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.teamTodoText, tagId: tagId, notes: L10n.Tasks.Examples.teamTodoNotes, taskRepository: taskRepository)
]
case .chores:
return [
createSampleHabit(L10n.Tasks.Examples.choresHabit, tagId: tagId, positive: true, negative: false, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.choresDailyText, tagId: tagId, notes: L10n.Tasks.Examples.choresDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.choresTodoText, tagId: tagId, notes: L10n.Tasks.Examples.choresTodoNotes, taskRepository: taskRepository)
]
case .creativity:
return [
createSampleHabit(L10n.Tasks.Examples.creativityHabit, tagId: tagId, positive: true, negative: false, taskRepository: taskRepository),
createSampleDaily(L10n.Tasks.Examples.creativityDailyText, tagId: tagId, notes: L10n.Tasks.Examples.creativityDailyNotes, taskRepository: taskRepository),
createSampleToDo(L10n.Tasks.Examples.creativityTodoText, tagId: tagId, notes: L10n.Tasks.Examples.creativityTodoNotes, taskRepository: taskRepository)
]
}
}
func getTag(taskRepository: TaskRepository) -> TagProtocol {
let tag = taskRepository.getNewTag()
switch self {
case .work:
tag.text = L10n.Tasks.work
case .exercise:
tag.text = L10n.Tasks.exercise
case .health:
tag.text = L10n.Tasks.health
case .school:
tag.text = L10n.Tasks.school
case .team:
tag.text = L10n.Tasks.team
case .chores:
tag.text = L10n.Tasks.chores
case .creativity:
tag.text = L10n.Tasks.creativity
}
return tag
}
}
class TaskSetupViewController: UIViewController, TypingTextViewController, Themeable {
@IBOutlet weak var avatarView: AvatarView!
@IBOutlet weak var workCategoryButton: UIButton!
@IBOutlet weak var exerciseCategoryButton: UIButton!
@IBOutlet weak var healthCategoryButton: UIButton!
@IBOutlet weak var schoolCategoryButton: UIButton!
@IBOutlet weak var teamCategoryButton: UIButton!
@IBOutlet weak var choresCategoryButtton: UIButton!
@IBOutlet weak var creativityCategoryButton: UIButton!
@IBOutlet weak var speechBubbleView: SpeechbubbleView!
@IBOutlet weak var containerHeight: NSLayoutConstraint!
let buttonBackground = #imageLiteral(resourceName: "DiamondButton").resizableImage(withCapInsets: UIEdgeInsets(top: 18, left: 15, bottom: 18, right: 15)).withRenderingMode(.alwaysTemplate)
private let userRepository = UserRepository()
private let disposable = ScopedDisposable(CompositeDisposable())
var user: UserProtocol? {
didSet {
if let user = self.user {
avatarView.avatar = AvatarViewModel(avatar: user)
}
}
}
public var selectedCategories: [SetupTaskCategory] = []
override func viewDidLoad() {
super.viewDidLoad()
speechBubbleView.text = L10n.Intro.taskSetupSpeechbubble
ThemeService.shared.addThemeable(themable: self)
avatarView.showBackground = false
avatarView.showMount = false
avatarView.showPet = false
avatarView.size = .regular
disposable.inner.add(userRepository.getUser().on(value: {[weak self]user in
self?.user = user
}).start())
initButtons()
if view.frame.size.height <= 568 {
containerHeight.constant = 205
}
}
func applyTheme(theme: Theme) {
view.backgroundColor = theme.windowBackgroundColor
}
func initButtons() {
workCategoryButton.setTitle(L10n.Tasks.work, for: .normal)
exerciseCategoryButton.setTitle(L10n.Tasks.exercise, for: .normal)
healthCategoryButton.setTitle(L10n.Tasks.health, for: .normal)
schoolCategoryButton.setTitle(L10n.Tasks.school, for: .normal)
teamCategoryButton.setTitle(L10n.Tasks.team, for: .normal)
choresCategoryButtton.setTitle(L10n.Tasks.chores, for: .normal)
creativityCategoryButton.setTitle(L10n.Tasks.creativity, for: .normal)
workCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
exerciseCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
healthCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
schoolCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
teamCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
choresCategoryButtton.setBackgroundImage(buttonBackground, for: .normal)
creativityCategoryButton.setBackgroundImage(buttonBackground, for: .normal)
workCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
exerciseCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
healthCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
schoolCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
teamCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
choresCategoryButtton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
creativityCategoryButton.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(toggleButton(_:))))
updateButtonBackgrounds()
}
@objc
func toggleButton(_ sender: UIGestureRecognizer) {
if let selectedCategory = getCategoryFor(view: sender.view) {
if selectedCategories.contains(selectedCategory) {
if let index = selectedCategories.firstIndex(of: selectedCategory) {
selectedCategories.remove(at: index)
}
} else {
selectedCategories.append(selectedCategory)
}
}
updateButtonBackgrounds()
}
private func getCategoryFor(view: UIView?) -> SetupTaskCategory? {
if let button = view as? UIButton {
switch button {
case workCategoryButton:
return .work
case exerciseCategoryButton:
return .exercise
case healthCategoryButton:
return .health
case schoolCategoryButton:
return .school
case teamCategoryButton:
return .team
case choresCategoryButtton:
return .chores
case creativityCategoryButton:
return .creativity
default:
return nil
}
}
return nil
}
func updateButtonBackgrounds() {
updateButton(workCategoryButton)
updateButton(exerciseCategoryButton)
updateButton(healthCategoryButton)
updateButton(schoolCategoryButton)
updateButton(teamCategoryButton)
updateButton(choresCategoryButtton)
updateButton(creativityCategoryButton)
}
func updateButton(_ button: UIButton) {
if isSelected(button) {
button.tintColor = .white
button.setTitleColor(UIColor.purple300, for: .normal)
button.setImage(#imageLiteral(resourceName: "checkmark_small"), for: .normal)
} else {
button.tintColor = UIColor.purple50
button.setTitleColor(.white, for: .normal)
button.setImage(nil, for: .normal)
}
}
func isSelected(_ button: UIButton) -> Bool {
switch button {
case workCategoryButton:
return selectedCategories.contains(.work)
case exerciseCategoryButton:
return selectedCategories.contains(.exercise)
case healthCategoryButton:
return selectedCategories.contains(.health)
case schoolCategoryButton:
return selectedCategories.contains(.school)
case teamCategoryButton:
return selectedCategories.contains(.team)
case choresCategoryButtton:
return selectedCategories.contains(.chores)
case creativityCategoryButton:
return selectedCategories.contains(.creativity)
default:
return false
}
}
func startTyping() {
speechBubbleView.animateTextView()
if let user = self.user {
avatarView.avatar = AvatarViewModel(avatar: user)
}
}
}
|
gpl-3.0
|
23510d0330a294ba983b0d6318eec791
| 43.55137 | 192 | 0.661696 | 4.689618 | false | false | false | false |
rodrigoDyT/todo-mobile-ios
|
PowerTodo/Pods/SwipyCell/Source/SwipyCell.swift
|
1
|
17099
|
//
// SwipyCell.swift
// SwipyCell
//
// Created by Moritz Sternemann on 17.01.16.
// Copyright © 2016 Moritz Sternemann. All rights reserved.
//
import UIKit
public protocol SwipyCellDelegate {
func swipeableTableViewCellDidStartSwiping(_ cell: SwipyCell)
func swipeableTableViewCellDidEndSwiping(_ cell: SwipyCell)
func swipeableTableViewCell(_ cell: SwipyCell, didSwipeWithPercentage percentage: CGFloat)
}
public class SwipyCell: UITableViewCell {
fileprivate typealias `Self` = SwipyCell
static let msStop1 = 0.25 // Percentage limit to trigger the first action
static let msStop2 = 0.75 // Percentage limit to trigger the second action
static let msBounceAmplitude = 20.0 // Maximum bounce amplitude whe using the switch mode
static let msDamping = 0.6 // Damping of the spring animation
static let msVelocity = 0.9 // Velocity of the spring animation
static let msAnimationDuration = 0.4 // Duration of the animation
static let msBounceDuration1 = 0.2 // Duration of the first part of the bounce animation
static let msBounceDuration2 = 0.1 // Duration of the second part of the bounce animation
static let msDurationLowLimit = 0.25 // Lowest duration when swiping the cell because we try to simulate velocity
static let msDurationHighLimit = 0.1 // Highest duration when swiping the cell because we try to simulate velocity
public typealias MSSwipeCompletionBlock = (SwipyCell, SwipyCellState, SwipyCellMode) -> ()
public var delegate: SwipyCellDelegate?
var direction: SwipyCellDirection!
var currentPercentage: CGFloat!
var isExited: Bool!
var panGestureRecognizer: UIPanGestureRecognizer!
var contentScreenshotView: UIImageView?
var colorIndicatorView: UIView!
var slidingView: UIView!
var activeView: UIView!
var dragging: Bool!
var shouldDrag: Bool!
public var shouldAnimateIcons: Bool!
public var firstTrigger: CGFloat!
public var secondTrigger: CGFloat!
var damping: CGFloat!
var velocity: CGFloat!
var animationDuration: TimeInterval!
public var defaultColor: UIColor!
var completionBlock1: MSSwipeCompletionBlock!
var completionBlock2: MSSwipeCompletionBlock!
var completionBlock3: MSSwipeCompletionBlock!
var completionBlock4: MSSwipeCompletionBlock!
var modeForState1: SwipyCellMode!
var modeForState2: SwipyCellMode!
var modeForState3: SwipyCellMode!
var modeForState4: SwipyCellMode!
var color1: UIColor!
var color2: UIColor!
var color3: UIColor!
var color4: UIColor!
var view1: UIView!
var view2: UIView!
var view3: UIView!
var view4: UIView!
// MARK: - Initialization
override public init(style: UITableViewCellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.initializer()
}
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
self.initializer()
}
func initializer() {
initDefaults()
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: #selector(SwipyCell.handlePanGestureRecognizer(_:)))
addGestureRecognizer(panGestureRecognizer)
panGestureRecognizer.delegate = self
}
func initDefaults() {
isExited = false
dragging = false
shouldDrag = true
shouldAnimateIcons = true
firstTrigger = CGFloat(Self.msStop1)
secondTrigger = CGFloat(Self.msStop2)
damping = CGFloat(Self.msDamping)
velocity = CGFloat(Self.msVelocity)
animationDuration = Self.msAnimationDuration
defaultColor = UIColor.white
modeForState1 = .none
modeForState2 = .none
modeForState3 = .none
modeForState4 = .none
color1 = nil
color2 = nil
color3 = nil
color4 = nil
activeView = nil
view1 = nil
view2 = nil
view3 = nil
view4 = nil
}
// MARK: - Prepare reuse
override public func prepareForReuse() {
super.prepareForReuse()
uninstallSwipingView()
initDefaults()
}
// MARK: - View manipulation
func setupSwipingView() {
if contentScreenshotView != nil {
return
}
let isContentViewBackgroundClear = (contentView.backgroundColor != nil)
if isContentViewBackgroundClear {
let isBackgroundClear = (backgroundColor == UIColor.clear)
contentView.backgroundColor = isBackgroundClear ? UIColor.white : backgroundColor
}
let contentViewScreenshotImage = imageWithView(self)
if isContentViewBackgroundClear {
contentView.backgroundColor = nil
}
colorIndicatorView = UIView(frame: self.bounds)
colorIndicatorView.autoresizingMask = [.flexibleHeight, .flexibleWidth]
addSubview(colorIndicatorView)
slidingView = UIView()
slidingView.contentMode = .center
colorIndicatorView.addSubview(slidingView)
contentScreenshotView = UIImageView(image: contentViewScreenshotImage)
addSubview(contentScreenshotView!)
}
func uninstallSwipingView() {
if contentScreenshotView == nil {
return
}
slidingView.removeFromSuperview()
slidingView = nil
colorIndicatorView.removeFromSuperview()
colorIndicatorView = nil
contentScreenshotView!.removeFromSuperview()
contentScreenshotView = nil
}
func setViewOfSlidingView(_ slidingView: UIView) {
let subviews = self.slidingView.subviews
_ = subviews.map { view in
view.removeFromSuperview()
}
self.slidingView.addSubview(slidingView)
}
// MARK: - Swipe configuration
public func setSwipeGesture(_ view: UIView, color: UIColor, mode: SwipyCellMode, state: SwipyCellState, completionHandler: @escaping MSSwipeCompletionBlock) {
if state.contains(.state1) {
completionBlock1 = completionHandler
view1 = view
color1 = color
modeForState1 = mode
}
if state.contains(.state2) {
completionBlock2 = completionHandler
view2 = view
color2 = color
modeForState2 = mode
}
if state.contains(.state3) {
completionBlock3 = completionHandler
view3 = view
color3 = color
modeForState3 = mode
}
if state.contains(.state4) {
completionBlock4 = completionHandler
view4 = view
color4 = color
modeForState4 = mode
}
}
// MARK: - Handle gestures
func handlePanGestureRecognizer(_ gesture: UIPanGestureRecognizer) {
if (shouldDrag == false || isExited == true) {
return
}
let state = gesture.state
let translation = gesture.translation(in: self)
let velocity = gesture.velocity(in: self)
var percentage: CGFloat = 0.0
if let contentScreenshotView = contentScreenshotView {
percentage = percentageWithOffset(contentScreenshotView.frame.minX, relativeToWidth: self.bounds.width)
}
let animationDuration = animationDurationWithVelocity(velocity)
direction = directionWithPercentage(percentage)
if (state == .began || state == .changed) {
dragging = true
setupSwipingView()
let center = CGPoint(x: contentScreenshotView!.center.x + translation.x, y: contentScreenshotView!.center.y)
contentScreenshotView!.center = center
animateWithOffset(contentScreenshotView!.frame.minX)
gesture.setTranslation(CGPoint.zero, in: self)
delegate?.swipeableTableViewCell(self, didSwipeWithPercentage: percentage)
} else if (state == .ended || state == .cancelled) {
dragging = false
activeView = viewWithPercentage(percentage)
currentPercentage = percentage
let cellState = stateWithPercentage(percentage)
var cellMode: SwipyCellMode = .none
if (cellState == .state1 && modeForState1 != nil) {
cellMode = modeForState1
} else if (cellState == .state2 && modeForState2 != nil) {
cellMode = modeForState2
} else if (cellState == .state3 && modeForState3 != nil) {
cellMode = modeForState3
} else if (cellState == .state4 && modeForState4 != nil) {
cellMode = modeForState4
}
if (cellMode == .exit && direction != .center) {
moveWithDuration(animationDuration, direction: direction)
} else {
swipeToOrigin {
self.executeCompletionBlock()
}
}
delegate?.swipeableTableViewCellDidEndSwiping(self)
}
}
// MARK: - UIGestureRecognizerDelegate
override public func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
guard let g = gestureRecognizer as? UIPanGestureRecognizer else { return false }
let point = g.velocity(in: self)
if fabs(point.x) > fabs(point.y) {
if point.x < 0 && modeForState3 == nil && modeForState4 == nil {
return false
}
if point.x > 0 && modeForState1 == nil && modeForState2 == nil {
return false
}
delegate?.swipeableTableViewCellDidStartSwiping(self)
return true
}
return false
}
// MARK: - Percentage
func offsetWithPercentage(_ percentage: CGFloat, relateiveToWidth width: CGFloat) -> CGFloat {
var offset = percentage * width
if (offset < -width) {
offset = -width
} else if (offset > width) {
offset = width
}
return offset
}
func percentageWithOffset(_ offset: CGFloat, relativeToWidth width: CGFloat) -> CGFloat {
var percentage = offset / width
if (percentage < -1.0) {
percentage = -1.0
} else if (percentage > 1.0) {
percentage = 1.0
}
return percentage
}
func animationDurationWithVelocity(_ velocity: CGPoint) -> TimeInterval {
let width = bounds.width
let animationDurationDiff = Self.msDurationHighLimit - Self.msDurationLowLimit
var horizontalVelocity = velocity.x
if horizontalVelocity < -width {
horizontalVelocity = -width
} else if horizontalVelocity > width {
horizontalVelocity = width
}
return TimeInterval(Self.msDurationHighLimit + Self.msDurationLowLimit - fabs((Double(horizontalVelocity / width) * animationDurationDiff)))
}
func directionWithPercentage(_ percentage: CGFloat) -> SwipyCellDirection {
if percentage < 0 {
return .left
} else if percentage > 0 {
return .right
} else {
return .center
}
}
func viewWithPercentage(_ percentage: CGFloat) -> UIView? {
var view: UIView?
if percentage >= 0 && modeForState1 != nil {
view = view1
}
if percentage >= secondTrigger! && modeForState2 != nil {
view = view2
}
if percentage < 0 && modeForState3 != nil {
view = view3
}
if percentage <= -secondTrigger && modeForState4 != nil {
view = view4
}
return view
}
func alphaWithPercentage(_ percentage: CGFloat) -> CGFloat {
var alpha: CGFloat = 1.0
if percentage >= 0 && percentage < firstTrigger! {
alpha = percentage / firstTrigger
} else if percentage < 0 && percentage > -firstTrigger {
alpha = fabs(percentage / firstTrigger)
}
return alpha
}
func colorWithPercentage(_ percentage: CGFloat) -> UIColor {
var color = defaultColor ?? UIColor.clear
if percentage > 0 && modeForState1 != nil {
color = color1
}
if percentage > secondTrigger! && modeForState2 != nil {
color = color2
}
if percentage < 0 && modeForState3 != nil {
color = color3
}
if percentage <= -secondTrigger && modeForState4 != nil {
color = color4
}
return color
}
func stateWithPercentage(_ percentage: CGFloat) -> SwipyCellState {
var state: SwipyCellState = .none
if percentage >= firstTrigger! && modeForState1 != nil {
state = .state1
}
if percentage >= secondTrigger! && modeForState2 != nil {
state = .state2
}
if percentage <= -firstTrigger && modeForState3 != nil {
state = .state3
}
if percentage <= -secondTrigger && modeForState4 != nil {
state = .state4
}
return state
}
// MARK: - Movement
func animateWithOffset(_ offset: CGFloat) {
let percentage = percentageWithOffset(offset, relativeToWidth: bounds.width)
let view = viewWithPercentage(percentage)
if let v = view {
setViewOfSlidingView(v)
slidingView.alpha = alphaWithPercentage(percentage)
slideViewWithPercentage(percentage, view: v, isDragging: shouldAnimateIcons)
}
let color = colorWithPercentage(percentage)
colorIndicatorView.backgroundColor = color
}
func slideViewWithPercentage(_ percentage: CGFloat, view: UIView?, isDragging: Bool) {
guard let view = view else { return }
var position = CGPoint.zero
position.y = bounds.height / 2.0
if isDragging {
if percentage >= 0 && percentage < firstTrigger! {
position.x = offsetWithPercentage((firstTrigger / 2), relateiveToWidth: bounds.width)
} else if percentage >= firstTrigger! {
position.x = offsetWithPercentage(percentage - (firstTrigger / 2), relateiveToWidth: bounds.width)
} else if percentage < 0 && percentage >= -firstTrigger {
position.x = bounds.width - offsetWithPercentage((firstTrigger / 2), relateiveToWidth: bounds.width)
} else if percentage < -firstTrigger {
position.x = bounds.width + offsetWithPercentage(percentage + (firstTrigger / 2), relateiveToWidth: bounds.width)
}
} else {
if direction == .right {
position.x = offsetWithPercentage((firstTrigger / 2.0), relateiveToWidth: bounds.width)
} else if direction == .left {
position.x = bounds.width - offsetWithPercentage((firstTrigger / 2.0), relateiveToWidth: bounds.width)
} else {
return
}
}
let activeViewSize = view.bounds.size
var activeViewFrame = CGRect(x: position.x - activeViewSize.width / 2.0,
y: position.y - activeViewSize.height / 2.0,
width: activeViewSize.width, height: activeViewSize.height)
activeViewFrame = activeViewFrame.integral
slidingView.frame = activeViewFrame
}
func moveWithDuration(_ duration: TimeInterval, direction: SwipyCellDirection) {
isExited = true
var origin: CGFloat = 0.0
if direction == .left {
origin = -bounds.width
} else if direction == .right {
origin = bounds.width
}
let percentage = percentageWithOffset(origin, relativeToWidth: bounds.width)
var frame = contentScreenshotView!.frame
frame.origin.x = origin
let color = colorWithPercentage(currentPercentage)
colorIndicatorView.backgroundColor = color
UIView.animate(withDuration: duration, delay: 0, options: [.curveEaseOut, .allowUserInteraction], animations: {
self.contentScreenshotView!.frame = frame
self.slidingView.alpha = 0
self.slideViewWithPercentage(percentage, view: self.activeView, isDragging: self.shouldAnimateIcons)
}, completion: { finished in
self.executeCompletionBlock()
})
}
open func swipeToOrigin(_ completionHandler: @escaping () -> ()) {
UIView.animate(withDuration: animationDuration, delay: 0, usingSpringWithDamping: damping, initialSpringVelocity: velocity, options: UIViewAnimationOptions(), animations: {
var frame = self.contentScreenshotView!.frame
frame.origin.x = 0
self.contentScreenshotView!.frame = frame
self.colorIndicatorView.backgroundColor = self.defaultColor
self.slidingView.alpha = 0
self.slideViewWithPercentage(0, view: self.activeView, isDragging: false)
}, completion: { finished in
self.isExited = false
self.uninstallSwipingView()
if finished {
completionHandler()
}
})
}
// MARK: - Utilities
func imageWithView(_ view: UIView) -> UIImage {
let scale = UIScreen.main.scale
UIGraphicsBeginImageContextWithOptions(view.bounds.size, false, scale)
view.layer.render(in: UIGraphicsGetCurrentContext()!)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image!
}
// MARK: - Completion block
func executeCompletionBlock() {
let state: SwipyCellState = stateWithPercentage(currentPercentage)
var mode: SwipyCellMode = .none
var completionBlock: MSSwipeCompletionBlock?
if state == .state1 {
mode = modeForState1
completionBlock = completionBlock1
} else if state == .state2 {
mode = modeForState2
completionBlock = completionBlock2
} else if state == .state3 {
mode = modeForState3
completionBlock = completionBlock3
} else if state == .state4 {
mode = modeForState4
completionBlock = completionBlock4
}
if completionBlock != nil {
completionBlock!(self, state, mode)
}
}
}
|
mit
|
e72b7d97b04cb4d3614c3fc7cecd74c1
| 29.532143 | 176 | 0.668499 | 4.624831 | false | false | false | false |
ftiff/SplashBuddy
|
SplashBuddy/Views/Main/MainViewController.swift
|
1
|
13669
|
// SplashBuddy
/*
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 Cocoa
import WebKit
class MainViewController: NSViewController, NSTableViewDataSource {
private let evaluationJavascript = """
function sb() {
var sbValues = {}; // Init empty array
/*
-----------------------
| Input Processing |
-----------------------
Supported inputs:
- Single Checkbox
- Group Checkbox
- Radio
- Text
*/
var sbItems = document.getElementsByTagName('input');
for (var i = 0; i < sbItems.length; i++) {
// Input items that are text type
var currentItem = sbItems.item(i);
if (currentItem.type == "text") {
sbValues[currentItem.name] = currentItem.value;
}
// Input items that are checkbox
else if (currentItem.type == "checkbox") {
// Checks if more than one checkbox is in a group.
if (document.getElementsByName(currentItem.name).length > 1) {
var checkboxElements = document.getElementsByName(currentItem.name);
// Begin processing checkbox items
for (var x = 0; x < checkboxElements.length; x++) {
if (checkboxElements.item(x).checked) {
sbValues[checkboxElements.item(x).name] = checkboxElements.item(x).value;
} else {
console.log("Not checked"); // for debugging
}
}
// End processing items
} else {
// Single checkbox detected
if (currentItem.getAttribute('sbbool') == "true") {
if (currentItem.checked) sbValues[currentItem.name] = "TRUE";
else sbValues[currentItem.name] = "FALSE";
} else {
if (currentItem.checked) sbValues[currentItem.name] = currentItem.value;
}
}
}
// Input items that are radios
else if (currentItem.type == "radio") {
if (document.getElementsByName(currentItem.name).length > 1) {
var radioElements = document.getElementsByName(currentItem.name);
// Begin processing for radio elements
for (var x = 0; x < radioElements.length; x++) {
if (radioElements.item(x).checked) {
sbValues[radioElements.item(x).name] = radioElements.item(x).value;
} else {
console.log("Not selected");
}
}
// End processing items
} else {
if (currentItem.getAttribute('sbbool') == "true") {
if (currentItem.checked) sbValues[currentItem.name] = "TRUE";
else sbValues[currentItem.name] = "FALSE";
} else {
if (currentItem.checked) sbValues[currentItem.name] = currentItem.value
}
}
} else {
console.log(currentItem.type);
}
}
/*
---------------------
| Select processing |
---------------------
Processes the Select elements for the selected Option tag
*/
sbItems = document.getElementsByTagName('select');
for (var i = 0; i < sbItems.length; i++) {
if (sbItems.item(i).options[sbItems.item(i).selectedIndex] != undefined) {
var value = sbItems.item(i).options[sbItems.item(i).selectedIndex].getAttribute('value');
if (value != undefined && value != "") sbValues[sbItems.item(i).name] = value;
}
}
/*
---------------------
| Requirement Check |
---------------------
Checks to see if the required elements are filled by the "sbReq" attribute
*/
var reqElements = document.querySelectorAll('[sbReq=true]');
for (var i = 0; i < reqElements.length; i++) {
var key = sbValues[reqElements.item(i).name];
if (key == null || key == undefined || key == "") {
throw "Not all required elements filled out";
} else {
console.log("Value for " + reqElements.item(i).name + " found with " + key);
}
}
return sbValues;
}
JSON.stringify(sb());
"""
@IBOutlet var mainView: NSView!
@IBOutlet var webView: WKWebView!
// @IBOutlet weak var sideBarView: NSView!
@IBOutlet weak var sideBarProgressIndicator: NSProgressIndicator!
@IBOutlet weak var sideBarContinueButton: NSButton!
@IBOutlet weak var activeStatusLabel: NSTextField!
@IBOutlet weak var sideBarView: NSVisualEffectView!
// @IBOutlet weak var bottomView: NSView!
// @IBOutlet weak var bottomProgressIndicator: NSProgressIndicator!
// @IBOutlet weak var bottomContinueButton: NSButton!
// @IBOutlet weak var bottomStatusLabel: NSTextField!
// weak var activeView: NSView!
// weak var activeProgressIndicator: NSProgressIndicator!
// weak var activeContinueButton: NSButton!
// weak var activeStatusLabel: NSTextField!
// Predicate used by Storyboard to filter which software to display
@objc let predicate = NSPredicate(format: "displayToUser = true")
private let enterKeyJS = """
window.onload = function() {
document.body.onkeydown = function(e){
if ( e.keyCode == "13" ) {
window.location.href = "formdone://";
}
}
}
"""
internal func formEnterKey() {
self.evalForm(self.sendButton!)
}
override func awakeFromNib() {
// https://developer.apple.com/library/content/qa/qa1871/_index.html
if self.representedObject == nil {
self.representedObject = SoftwareArray.sharedInstance
}
}
override func viewWillAppear() {
super.viewWillAppear()
// Setup the view
if Preferences.sharedInstance.background {
self.mainView.layer?.backgroundColor = NSColor.windowBackgroundColor.cgColor
self.mainView.layer?.cornerRadius = 10
self.mainView.layer?.shadowRadius = 2
self.mainView.layer?.borderWidth = 0.2
}
// Setup the web view
self.webView.layer?.isOpaque = true
// Setup the initial state of objects
self.setupInstalling()
// Setup the Continue Button
self.sideBarContinueButton.title = Preferences.sharedInstance.continueAction.localizedName
// Setup the Notifications
NotificationCenter.default.addObserver(self,
selector: #selector(MainViewController.errorWhileInstalling),
name: SoftwareArray.StateNotification.errorWhileInstalling.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(MainViewController.canContinue),
name: SoftwareArray.StateNotification.canContinue.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(MainViewController.doneInstalling),
name: SoftwareArray.StateNotification.doneInstalling.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(MainViewController.resetStatusLabel),
name: SoftwareArray.StateNotification.processing.notification,
object: nil)
NotificationCenter.default.addObserver(self,
selector: #selector(MainViewController.allSuccess),
name: SoftwareArray.StateNotification.allSuccess.notification,
object: nil)
// Setup insider error observer
Preferences.sharedInstance.addObserver(self, forKeyPath: "insiderError", options: [.new], context: nil)
}
override func viewDidAppear() {
// Display the html file
if Preferences.sharedInstance.form != nil && !Preferences.sharedInstance.formDone {
guard let form = Preferences.sharedInstance.form else {
return
}
DispatchQueue.main.async {
self.sendButton.isHidden = false
}
self.webView.loadFileURL(form, allowingReadAccessTo: Preferences.sharedInstance.assetPath)
Log.write(string: "Injecting Javascript.", cat: "UserInput", level: .debug)
self.webView.evaluateJavaScript(self.enterKeyJS, completionHandler: nil)
} else if let html = Preferences.sharedInstance.html {
if Preferences.sharedInstance.formDone {
Log.write(string: "Form already completed.", cat: "UserInput", level: .debug)
}
self.webView.loadFileURL(html, allowingReadAccessTo: Preferences.sharedInstance.assetPath)
} else {
self.webView.loadHTMLString(NSLocalizedString("error.create_missing_bundle"), baseURL: nil)
}
}
@IBOutlet weak var sendButton: NSButton!
@IBAction func evalForm(_ sender: Any) {
webView.evaluateJavaScript(evaluationJavascript) { (data: Any?, error: Error?) in
if error != nil {
Log.write(string: "Error getting User Input", cat: "UserInput", level: .error)
return
}
guard let jsonString = data as? String else {
Log.write(string: "Cannot read User Input data", cat: "UserInput", level: .error)
return
}
guard let jsonData = jsonString.data(using: .utf8) else {
Log.write(string: "Cannot cast User Input to data", cat: "UserInput", level: .error)
return
}
guard let obj = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? NSDictionary else {
return
}
for item in obj {
Log.write(string: "Writing value to \(item.key) with value of \(item.value)", cat: "UserInput", level: .debug)
FileManager.default.createFile(atPath: "\(item.key).txt", contents: (item.value as? String ?? "").data(using: .utf8), attributes: nil)
}
DispatchQueue.main.async {
self.sendButton.isHidden = true
if let html = Preferences.sharedInstance.html {
self.webView.loadFileURL(html, allowingReadAccessTo: Preferences.sharedInstance.assetPath)
} else {
self.webView.loadHTMLString(NSLocalizedString("error.create_missing_bundle"), baseURL: nil)
}
}
Log.write(string: "DONE: Form Javascript Evaluation", cat: "UI", level: .debug)
Log.write(string: "Form complete, writing to .SplashBuddyFormDone", cat: "UI", level: .debug)
Preferences.sharedInstance.formDone = true
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "insiderError" {
checkForInsiderError()
}
}
func checkForInsiderError() {
// The async after a second is here only to handle the case where the error flag is changed before the error messages are set.
DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + .seconds(1)) {
guard let window = self.view.window else { return }
if Preferences.sharedInstance.insiderError {
let alert = NSAlert()
alert.alertStyle = .critical
alert.messageText = Preferences.sharedInstance.insiderErrorMessage
alert.informativeText = Preferences.sharedInstance.insiderErrorInfo
alert.addButton(withTitle: "Quit")
alert.beginSheetModal(for: window) { (_) in
self.pressedContinueButton(self)
}
}
}
}
}
|
apache-2.0
|
f17e2e6aeaaa4324fcb8eebc5d176487
| 42.670927 | 151 | 0.54181 | 5.407041 | false | false | false | false |
CodeInventorGroup/CIComponentKit
|
Sources/CICExtensions/UIControl+CIKit.swift
|
1
|
1167
|
//
// UIControl+Callback.swift
// CIComponentKit
//
// Created by ManoBoo on 2017/10/14.
// Copyright © 2017年 club.codeinventor. All rights reserved.
//
import UIKit
private var controlHandlerKey: Int8 = 0
extension UIControl {
public func addHandler(for controlEvents: UIControl.Event, handler: @escaping (UIControl) -> Void) {
if let oldTarget = objc_getAssociatedObject(self, &controlHandlerKey) as? CIComponentKitTarget<UIControl> {
self.removeTarget(oldTarget, action: #selector(oldTarget.sendNext), for: controlEvents)
}
let target = CIComponentKitTarget<UIControl>(handler)
objc_setAssociatedObject(self, &controlHandlerKey, target, .OBJC_ASSOCIATION_RETAIN)
self.addTarget(target, action: #selector(target.sendNext), for: controlEvents)
}
}
internal final class CIComponentKitTarget<Value>: NSObject {
private let action: (Value) -> Void
internal init(_ action: @escaping (Value) -> Void) {
self.action = action
}
@objc
internal func sendNext(_ receiver: Any?) {
if let receiver = receiver as? Value {
action(receiver)
}
}
}
|
mit
|
744d17f49aadb446e2482d7875d4b07c
| 29.631579 | 115 | 0.680412 | 4.055749 | false | false | false | false |
vazteam/ProperMediaView
|
Classes/ProperMedia.swift
|
1
|
2805
|
//
// ProperMediaObject.swift
// ProperMediaViewDemo
//
// Created by Murawaki on 2017/03/30.
// Copyright © 2017年 Murawaki. All rights reserved.
//
import Foundation
import UIKit
public protocol ProperMedia {
var placeHolder: UIImage? { get }
var thumbnailImageUrl: URL { get }
var mediaUrl: URL { get }
var isMovie: Bool { get }
}
public struct ProperImage: ProperMedia {
public var placeHolder: UIImage?
public var thumbnailImageUrl: URL
public var mediaUrl: URL
public var isMovie: Bool
public init(thumbnailUrl: URL, originalImageUrl: URL, placeHolder: UIImage? = nil) {
self.thumbnailImageUrl = thumbnailUrl
self.mediaUrl = originalImageUrl
self.isMovie = false
}
public init(thumbnailUrlStr: String, originalImageUrlStr: String, placeHolder: UIImage? = nil) {
if let thumbnailUrl = URL(string: thumbnailUrlStr) {
self.thumbnailImageUrl = thumbnailUrl
} else {
self.thumbnailImageUrl = URL(string: "https://www.google.co.jp/logos/doodles/2017/sergei-diaghilevs-145th-birthday-5691313237262336-hp.jpg")!
print("thumbnailUrlStr is could'n convert URL")
}
if let originalImageUrl = URL(string: originalImageUrlStr) {
self.mediaUrl = originalImageUrl
} else {
self.mediaUrl = URL(string: "https://www.google.co.jp/logos/doodles/2017/sergei-diaghilevs-145th-birthday-5691313237262336-hp.jpg")!
print("originalImageUrlStr is could'n convert URL")
}
self.isMovie = false
}
}
public struct ProperMovie: ProperMedia {
public var placeHolder: UIImage?
public var thumbnailImageUrl: URL
public var mediaUrl: URL
public var isMovie: Bool
public init(thumbnailUrl: URL, movieUrl: URL, placeHolder: UIImage? = nil) {
self.thumbnailImageUrl = thumbnailUrl
self.mediaUrl = movieUrl
self.isMovie = true
}
public init(thumbnailUrlStr: String, movieUrlStr: String, placeHolder: UIImage? = nil) {
if let thumbnailUrl = URL(string: thumbnailUrlStr) {
self.thumbnailImageUrl = thumbnailUrl
} else {
self.thumbnailImageUrl = URL(string: "https://www.google.co.jp/logos/doodles/2017/sergei-diaghilevs-145th-birthday-5691313237262336-hp.jpg")!
print("thumbnailUrlStr is could'n convert URL")
}
if let movieUrl = URL(string: movieUrlStr) {
self.mediaUrl = movieUrl
} else {
self.mediaUrl = URL(string: "https://www.google.co.jp/logos/doodles/2017/sergei-diaghilevs-145th-birthday-5691313237262336-hp.jpg")!
print("movieUrlStr is could'n convert URL")
}
self.isMovie = true
}
}
|
mit
|
273f21a958c780c5547de91c27da152e
| 34.025 | 153 | 0.653462 | 3.952045 | false | false | false | false |
justaninja/clients_list
|
ClientsList/ClientsList/InputViewController.swift
|
1
|
2287
|
//
// InputViewController.swift
// ClientsList
//
// Created by Konstantin Khokhlov on 06.07.17.
// Copyright © 2017 Konstantin Khokhlov. All rights reserved.
//
import UIKit
import CoreLocation
class InputViewController: UIViewController {
// MARK: - Outlets
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var dateTextField: UITextField!
@IBOutlet weak var locationTextField: UITextField!
@IBOutlet weak var addressTextField: UITextField!
@IBOutlet weak var infoTextField: UITextField!
@IBOutlet weak var saveButton: UIButton!
@IBOutlet weak var cancelButton: UIButton!
// MARK: - Properties
lazy var geocoder = CLGeocoder()
var clientsManager: ClientsManager?
let dateFormatter: DateFormatter = {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MM/dd/yyyy"
return dateFormatter
}()
// MARK: - Methods
/// Saves a new client to the current clients array.
@IBAction func save() {
guard let nameString = nameTextField.text, nameString.characters.count > 0 else { return }
let date: Date?
if let dateText = dateTextField.text, dateText.characters.count > 0 {
date = dateFormatter.date(from: dateText)
} else {
date = nil
}
let infoString = infoTextField.text
if let locationName = locationTextField.text, locationName.characters.count > 0 {
if let address = addressTextField.text, address.characters.count > 0 {
geocoder.geocodeAddressString(address) { [unowned self] (placeMarks, _) in
let placeMark = placeMarks?.first
let client = Client(name: nameString, info: infoString,
timestamp: date?.timeIntervalSince1970,
location: Location(name: locationName, coordinate: placeMark?.location?.coordinate))
self.clientsManager?.add(client)
}
}
} else {
let client = Client(name: nameString, info: infoString, timestamp: date?.timeIntervalSince1970, location: nil)
self.clientsManager?.add(client)
}
dismiss(animated: true)
}
}
|
mit
|
0f07a7917a8623abde1db76ce4c419d1
| 32.130435 | 124 | 0.629484 | 5.102679 | false | false | false | false |
ajohnson388/rss-reader
|
RSS Reader/RSS Reader/EditableFeedViewController.swift
|
1
|
4710
|
//
// EditableFeedViewController.swift
// RSS Reader
//
// Created by Andrew Johnson on 9/5/16.
// Copyright © 2016 Andrew Johnson. All rights reserved.
//
import Foundation
import UIKit
/**
A view controller responsible for editing and creating feeds. This controller is segued via modal and
should be embedded inside of a navigation controller. The save button does not become enabled until
a change is made and the required fields are satisfied.
*/
final class EditableFeedViewController: UITableViewController {
// MARK: Fields
private var saveButton = UIBarButtonItem(barButtonSystemItem: .save, target: nil, action: nil)
private var cancelButton = UIBarButtonItem(barButtonSystemItem: .cancel, target: nil, action: nil)
private var feed: Feed {
didSet {
let validTitle = feed.title != nil || feed.title != ""
let validUrl = feed.url != nil
saveButton.isEnabled = validTitle && validUrl
}
}
// Initializers
init(feed: Feed?) {
self.feed = feed ?? Feed()
super.init(style: .grouped)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: View Setup
private func setupCancelButton() {
cancelButton.target = self
cancelButton.action = #selector(cancelTapped(_:))
navigationItem.leftBarButtonItem = cancelButton
}
private func setupSaveButton() {
saveButton.target = self
saveButton.action = #selector(saveTapped(_:))
saveButton.isEnabled = false
navigationItem.rightBarButtonItem = saveButton
}
// MARK: UIViewController LifeCycle Callbacks
override func viewDidLoad() {
super.viewDidLoad()
setupCancelButton()
setupSaveButton()
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
resignFirstResponder() // TODO - Does this actually work?
}
// MARK: Button Actions
func cancelTapped(_ sender: UIBarButtonItem) {
dismiss(animated: true, completion: nil)
}
func saveTapped(_ sender: UIBarButtonItem) {
guard feed.url != nil && feed.title != nil else { return }
_ = DBService.sharedInstance.save(feed) // TODO - prompt error
dismiss(animated: true, completion: nil)
}
// MARK: UITableView DataSource
override func numberOfSections(in tableView: UITableView) -> Int {
return 2 // Text fields and selection field
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
if section == 0 {
return 3 // Title, subtitle, url
} else {
return 1 // Category
}
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
// Text fields
if (indexPath as NSIndexPath).section == 0 {
let reuseId = "text_field_cell"
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) as? TextFieldTableViewCell ?? TextFieldTableViewCell(reuseId: reuseId)
let rep: (placeholder: String, text: String?) = {
switch (indexPath as NSIndexPath).row {
case 0: return ("Title", feed.title)
case 1: return ("Subtitle", feed.subtitle)
case 2: return ("Url", feed.url?.absoluteString)
default: return ("", nil)
}
}()
cell.textField.placeholder = rep.placeholder
cell.textField.text = rep.text
cell.textField.autocapitalizationType = .none
cell.textField.autocorrectionType = .no
return cell
// Selection fields
} else {
let reuseId = "selection_cell"
let cell = tableView.dequeueReusableCell(withIdentifier: reuseId) ?? UITableViewCell(style: .value1, reuseIdentifier: reuseId)
cell.selectionStyle = .blue
cell.accessoryType = .disclosureIndicator
cell.textLabel?.text = "Category"
cell.detailTextLabel?.text = feed.category
return cell
}
}
// MARK: UITableView Delegate
override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true) // Button click effect
// Selection fields
if (indexPath as NSIndexPath).section == 1 {
// TODO
}
}
}
|
apache-2.0
|
c38f7111624585a8675c9e7008170979
| 31.253425 | 148 | 0.610533 | 5.320904 | false | false | false | false |
hearther/ZipArchive
|
SwiftExample/SwiftExample/ViewController.swift
|
1
|
3162
|
//
// ViewController.swift
// SwiftExample
//
// Created by Sean Soper on 10/23/15.
//
//
import UIKit
#if UseCarthage
import ZipArchive
#else
import SSZipArchive
#endif
class ViewController: UIViewController {
@IBOutlet weak var zipButton: UIButton!
@IBOutlet weak var unzipButton: UIButton!
@IBOutlet weak var resetButton: UIButton!
@IBOutlet weak var file1: UILabel!
@IBOutlet weak var file2: UILabel!
@IBOutlet weak var file3: UILabel!
var zipPath: String?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
file1.text = ""
file2.text = ""
file3.text = ""
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: IBAction
@IBAction func zipPressed(_: UIButton) {
let sampleDataPath = Bundle.main.bundleURL.appendingPathComponent("Sample Data").path
zipPath = tempZipPath()
let success = SSZipArchive.createZipFile(atPath: zipPath!, withContentsOfDirectory: sampleDataPath)
if success {
unzipButton.isEnabled = true
zipButton.isEnabled = false
}
}
@IBAction func unzipPressed(_: UIButton) {
guard let zipPath = self.zipPath else {
return
}
guard let unzipPath = tempUnzipPath() else {
return
}
let success = SSZipArchive.unzipFile(atPath: zipPath, toDestination: unzipPath)
if !success {
return
}
var items: [String]
do {
items = try FileManager.default.contentsOfDirectory(atPath: unzipPath)
} catch {
return
}
for (index, item) in items.enumerated() {
switch index {
case 0:
file1.text = item
case 1:
file2.text = item
case 2:
file3.text = item
default:
print("Went beyond index of assumed files")
}
}
unzipButton.isEnabled = false
resetButton.isEnabled = true
}
@IBAction func resetPressed(_: UIButton) {
file1.text = ""
file2.text = ""
file3.text = ""
zipButton.isEnabled = true
unzipButton.isEnabled = false
resetButton.isEnabled = false
}
// MARK: Private
func tempZipPath() -> String {
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
path += "/\(UUID().uuidString).zip"
return path
}
func tempUnzipPath() -> String? {
var path = NSSearchPathForDirectoriesInDomains(.cachesDirectory, .userDomainMask, true)[0]
path += "/\(UUID().uuidString)"
let url = URL(fileURLWithPath: path)
do {
try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true, attributes: nil)
} catch {
return nil
}
return url.path
}
}
|
mit
|
84108892ce4865eddbb08ffbb38d458f
| 24.095238 | 112 | 0.582543 | 4.902326 | false | false | false | false |
Ethenyl/JAMFKit
|
JamfKit/Sources/Models/User.swift
|
1
|
6062
|
//
// Copyright © 2017-present JamfKit. All rights reserved.
// Licensed under the MIT License. See LICENSE file in the project root for full license information.
//
/// Represents a Jamf user and contains the identification properties that are required to contact the actual user and identify the hardware devices assigned to him / her.
@objc(JMFKUser)
public final class User: BaseObject, Endpoint {
// MARK: - Constants
public static let Endpoint = "users"
static let FullNameKey = "full_name"
static let EmailKey = "email"
static let EmailAddressKey = "email_address"
static let PhoneNumberKey = "phone_number"
static let PositionKey = "position"
static let EnableCustomPhotoURLKey = "enable_custom_photo_url"
static let CustomPhotoURLKey = "custom_photo_url"
static let SitesKey = "sites"
// MARK: - Properties
@objc
public var fullName = ""
@objc
public var email = ""
@objc
public var emailAddress = ""
@objc
public var phoneNumber = ""
@objc
public var position = ""
@objc
public var enableCustomPhotoURL = false
@objc
public var customPhotoURL = ""
@objc
public var sites = [Site]()
public override var description: String {
let baseDescription = super.description
if !fullName.isEmpty {
return "\(baseDescription)[\(self.fullName)]"
}
return baseDescription
}
// MARK: - Initialization
public required init?(json: [String: Any], node: String = "") {
fullName = json[User.FullNameKey] as? String ?? ""
email = json[User.EmailKey] as? String ?? ""
emailAddress = json[User.EmailAddressKey] as? String ?? ""
phoneNumber = json[User.PhoneNumberKey] as? String ?? ""
position = json[User.PositionKey] as? String ?? ""
enableCustomPhotoURL = json[User.EnableCustomPhotoURLKey] as? Bool ?? false
customPhotoURL = json[User.CustomPhotoURLKey] as? String ?? ""
var sites = [Site]()
if let rawSites = json[User.SitesKey] as? [[String: Any]] {
sites = rawSites.compactMap { Site(json: $0) }
} else if
let rawSite = json[User.SitesKey] as? [String: Any],
let site = Site(json: rawSite) {
sites.append(site)
}
self.sites = sites
super.init(json: json)
}
public override init?(identifier: UInt, name: String) {
super.init(identifier: identifier, name: name)
}
public override func toJSON() -> [String: Any] {
var json = super.toJSON()
json[User.FullNameKey] = fullName
json[User.EmailKey] = email
json[User.EmailAddressKey] = emailAddress
json[User.PhoneNumberKey] = phoneNumber
json[User.PositionKey] = position
json[User.EnableCustomPhotoURLKey] = enableCustomPhotoURL
json[User.CustomPhotoURLKey] = customPhotoURL
if !sites.isEmpty {
json[User.SitesKey] = sites.map { site -> [String: [String: Any]] in
return ["site": site.toJSON()]
}
}
return json
}
}
// MARK: - Creatable
extension User: Creatable {
public func createRequest() -> URLRequest? {
return getCreateRequest()
}
}
// MARK: - Readable
extension User: Readable {
public static func readAllRequest() -> URLRequest? {
return getReadAllRequest()
}
public static func readRequest(identifier: String) -> URLRequest? {
return getReadRequest(identifier: identifier)
}
public func readRequest() -> URLRequest? {
return getReadRequest()
}
/// Returns a GET **URLRequest** based on the supplied name.
public static func readRequest(name: String) -> URLRequest? {
return getReadRequest(name: name)
}
/// Returns a GET **URLRequest** based on the email.
public func readRequestWithName() -> URLRequest? {
return getReadRequestWithName()
}
/// Returns a GET **URLRequest** based on the supplied email.
public static func readRequest(email: String) -> URLRequest? {
return SessionManager.instance.readRequest(for: self, key: User.EmailKey, value: email)
}
/// Returns a GET **URLRequest** based on the email.
public func readRequestWithEmail() -> URLRequest? {
return User.readRequest(email: email)
}
}
// MARK: - Updatable
extension User: Updatable {
public func updateRequest() -> URLRequest? {
return getUpdateRequest()
}
/// Returns a PUT **URLRequest** based on the name.
public func updateRequestWithName() -> URLRequest? {
return getUpdateRequestWithName()
}
/// Returns a PUT **URLRequest** based on the email.
public func updateRequestWithEmail() -> URLRequest? {
return SessionManager.instance.updateRequest(for: self, key: User.EmailKey, value: email)
}
}
// MARK: - Deletable
extension User: Deletable {
public static func deleteRequest(identifier: String) -> URLRequest? {
return getDeleteRequest(identifier: identifier)
}
public func deleteRequest() -> URLRequest? {
return getDeleteRequest()
}
/// Returns a DELETE **URLRequest** based on the supplied name.
public static func deleteRequest(name: String) -> URLRequest? {
return SessionManager.instance.deleteRequest(for: self, key: BaseObject.CodingKeys.name.rawValue, value: name)
}
/// Returns a DELETE **URLRequest** based on the name.
public func deleteRequestWithName() -> URLRequest? {
return User.deleteRequest(name: name)
}
/// Returns a DELETE **URLRequest** based on the supplied email.
public static func deleteRequest(email: String) -> URLRequest? {
return SessionManager.instance.deleteRequest(for: self, key: User.EmailKey, value: email)
}
/// Returns a DELETE **URLRequest** based on the email.
public func deleteRequestWithEmail() -> URLRequest? {
return User.deleteRequest(email: email)
}
}
|
mit
|
5e9e911d74be4c731ec4e58338035f7c
| 28.710784 | 171 | 0.643458 | 4.482988 | false | false | false | false |
timfuqua/Bourgeoisie
|
Bourgeoisie/Pods/Buckets/Source/Queue.swift
|
1
|
3463
|
//
// Queue.swift
// Buckets
//
// Created by Mauricio Santos on 2/19/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// A queue is a First-In-First-Out (FIFO) collection,
/// the first element added to the queue will be the first one
/// to be removed.
///
/// The `enqueue` and `dequeue` operations run in amortized constant time.
///
/// Conforms to `SequenceType`, `ArrayLiteralConvertible`,
/// `Printable`, `DebugPrintable` and `ReconstructableSequence`.
public struct Queue<T> {
// MARK: Creating a Queue
/// Constructs an empty queue.
public init() {}
/// Constructs a queue from a sequence, such as an array.
/// The elements will be enqueued from first to last.
public init<S: SequenceType where S.Generator.Element == T>(_ elements: S){
items = CircularArray(elements)
}
// MARK: Querying a Queue
/// Number of elements stored in the queue.
public var count : Int {
return items.count
}
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return count == 0
}
/// The front element in the queue, or `nil` if the queue is empty.
public var first: T? {
return items.first
}
// MARK: Adding and Removing Elements
/// Inserts an element into the back of the queue.
public mutating func enqueue(element: T) {
items.append(element)
}
/// Retrieves and removes the front element of the queue.
///
/// - returns: The front element, or `nil` if the queue is empty.
public mutating func dequeue() -> T? {
return items.removeFirst()
}
/// Removes all the elements from the queue, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepCapacity keep: Bool = true) {
items.removeAll(keepCapacity: keep)
}
// MARK: Private Properties and Helper Methods
/// Internal structure holding the elements.
private var items = CircularArray<T>()
}
extension Queue: SequenceType {
// MARK: SequenceType Protocol Conformance
/// Provides for-in loop functionality. Generates elements in FIFO order.
///
/// - returns: A generator over the elements.
public func generate() -> AnyGenerator<T> {
return items.generate()
}
}
extension Queue: ArrayLiteralConvertible {
// MARK: ArrayLiteralConvertible Protocol Conformance
/// Constructs a queue using an array literal.
/// The elements will be enqueued from first to last.
/// `let queue: Queue<Int> = [1,2,3]`
public init(arrayLiteral elements: T...) {
self.init(elements)
}
}
extension Queue: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the queue.
public var description: String {
return "[" + map{"\($0)"}.joinWithSeparator(", ") + "]"
}
}
// MARK: -
// MARK: Queue Operators
/// Returns `true` if and only if the queues contain the same elements
/// in the same order.
/// The underlying elements must conform to the `Equatable` protocol.
public func ==<U: Equatable>(lhs: Queue<U>, rhs: Queue<U>) -> Bool {
return lhs.items == rhs.items
}
public func !=<U: Equatable>(lhs: Queue<U>, rhs: Queue<U>) -> Bool {
return !(lhs==rhs)
}
|
mit
|
33d1ed434039f26e7d6e310acb06a078
| 27.154472 | 79 | 0.634421 | 4.366961 | false | false | false | false |
fengyu122/YUImageViewer
|
YUImageViewer/YUImageViewerCell.swift
|
1
|
11923
|
//
// YUImageViewerCell.swift
// YUImageViewer
//
// Created by yu on 2017/1/8.
// Copyright © 2017年 yu. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
enum YUImageState {
case downloading
case downloadFinish
case downloadFail
}
protocol YUImageViewerCellProtocol:NSObjectProtocol {
func imageViewerCell(singleTapActionAt index:Int)
func imageViewerCell(longPressActionAt index:Int, image:UIImage?)
func imageViewerCell(downloadImageAt index:Int , imageView:UIImageView , complete:@escaping DownloadCompleteBlock)
}
class YUImageViewerCell: UICollectionViewCell,UIScrollViewDelegate {
weak var delegate:YUImageViewerCellProtocol?
var index:Int!
private var state:YUImageState!
{
didSet
{
switch state! {
case .downloadFail,.downloading:
downloadingOrFailAction()
case .downloadFinish:
downloadFinishAction()
}
}
}
private lazy var scrollView:UIScrollView={
[unowned self] in
let scrollView=UIScrollView(frame:self.contentView.bounds)
scrollView.bouncesZoom=true
scrollView.delegate=self
scrollView.contentInset=UIEdgeInsets.zero
scrollView.minimumZoomScale=self.minimumZoomScale
scrollView.maximumZoomScale=self.maximumZoomScale
scrollView.addSubview(self.imageView)
scrollView.showsHorizontalScrollIndicator=false
scrollView.showsVerticalScrollIndicator=false
let singleTapGestureRecognizer=UITapGestureRecognizer.init(target: self, action: #selector(YUImageViewerCell.singleTapGestureRecognizerHandle(_:)))
let doubleTapGestureRecognizer=UITapGestureRecognizer.init(target: self, action: #selector(YUImageViewerCell.doubleTapGestureRecognizerHandle(_:)))
let longPressGestureRecognize=UILongPressGestureRecognizer.init(target: self, action: #selector(YUImageViewerCell.longPressGestureRecognizerHandle(_:)))
doubleTapGestureRecognizer.numberOfTapsRequired=2
singleTapGestureRecognizer.require(toFail: doubleTapGestureRecognizer)
scrollView.addGestureRecognizer(singleTapGestureRecognizer)
scrollView.addGestureRecognizer(doubleTapGestureRecognizer)
scrollView.addGestureRecognizer(longPressGestureRecognize)
return scrollView
}()
var model:YUImageViewerModel!
{
didSet
{
minimumZoomScale=model.minimumZoomScale
if model.orientation != UIDevice.current.orientation
{
model.orientation=UIDevice.current.orientation
}
imageView.image=model.placeholder
self.downloadImage()
}
}
private func downloadingOrFailAction()
{
scrollView.maximumZoomScale=minimumZoomScale
scrollView.setZoomScale(minimumZoomScale, animated: false)
scrollView.setContentOffset(CGPoint.zero, animated: false)
YULoadingView.dismissAll(in: self)
if state == YUImageState.downloading
{
let _=YULoadingView.show(in: self)
}
}
private func downloadFinishAction()
{
YULoadingView.dismissAll(in: self)
if let scale=model.scale
{
scrollView.zoomScale=scale
}else
{
scrollView.setZoomScale(minimumZoomScale, animated: false)
model.scale=minimumZoomScale
}
if let contentOffset=model.contentOffset
{
scrollView.setContentOffset(contentOffset, animated: false)
}else
{
scrollView.setContentOffset(CGPoint.zero, animated: false)
}
}
lazy var completeDownloadBlock:DownloadCompleteBlock={
[weak self] (sucess) in
if Thread.current == Thread.main
{
if sucess
{
self?.state=YUImageState.downloadFinish
}else
{
self?.state=YUImageState.downloadFail
}
}else
{
DispatchQueue.main.async(execute: {
[weak self] in
if sucess
{
self?.state=YUImageState.downloadFinish
}else
{
self?.state=YUImageState.downloadFail
}
})
}
}
private func downloadImage()
{
state=YUImageState.downloading
delegate?.imageViewerCell(downloadImageAt: index, imageView: imageView, complete: completeDownloadBlock)
}
var minimumZoomScale:CGFloat = 1.0
{
didSet
{
scrollView.minimumZoomScale=minimumZoomScale
}
}
var maximumZoomScale:CGFloat = 2.0
{
didSet
{
scrollView.maximumZoomScale=maximumZoomScale
}
}
private lazy var imageView:UIImageView={
[unowned self] in
let imageView=UIImageView.init()
imageView.addObserver(self, forKeyPath: "image", options: .new, context: nil)
imageView.contentMode=UIViewContentMode.scaleAspectFit
imageView.isUserInteractionEnabled=true
return imageView
}()
@objc func longPressGestureRecognizerHandle(_ longPressGestureRecognize: UILongPressGestureRecognizer)
{
if longPressGestureRecognize.state == UIGestureRecognizerState.began,state == YUImageState.downloadFinish
{
self.delegate?.imageViewerCell(longPressActionAt: index,image:imageView.image)
}
}
@objc func singleTapGestureRecognizerHandle(_ tapGestureRecognizer:UITapGestureRecognizer)
{
self.delegate?.imageViewerCell(singleTapActionAt: index)
}
@objc func doubleTapGestureRecognizerHandle(_ tapGestureRecognizer:UITapGestureRecognizer)
{
if state != YUImageState.downloadFinish
{
return
}
let zoomScale=scrollView.zoomScale
let location=tapGestureRecognizer.location(in: self.scrollView)
if zoomScale <= minimumZoomScale
{
scrollView.zoom(to: CGRect.init(x: location.x, y: location.y, width: 1, height: 1), animated: true)
}else
{
scrollView.setZoomScale(minimumZoomScale, animated: true)
}
}
override init(frame: CGRect) {
super.init(frame: frame)
contentView.addSubview(scrollView)
NotificationCenter.default.addObserver(self, selector: #selector(YUImageViewerCell.rotateScreenAction(_:)), name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
private func setImageViewPosition()
{
let centerX=scrollView.contentSize.width > scrollView.bounds.size.width ? scrollView.contentSize.width/2 : scrollView.center.x
let centerY=scrollView.contentSize.height > scrollView.bounds.size.height ? scrollView.contentSize.height/2 : scrollView.center.y
imageView.center=CGPoint.init(x: centerX, y: centerY)
}
func viewForZooming(in scrollView: UIScrollView) -> UIView? {
return imageView
}
func scrollViewDidZoom(_ scrollView: UIScrollView) {
if state != YUImageState.downloadFinish
{
return
}
model.scale=scrollView.zoomScale
setImageViewPosition()
}
override func prepareForReuse() {
super.prepareForReuse()
if state != YUImageState.downloadFinish
{
return
}
let offset=scrollView.contentOffset
let maxWidth=scrollView.contentSize.width-scrollView.bounds.width
let maxHeight=scrollView.contentSize.height-scrollView.bounds.height
var x=offset.x > maxWidth ? maxWidth : offset.x
x=x < 0 ? 0 : x
var y=offset.y > maxHeight ? maxHeight : offset.y
y=y < 0 ? 0 : y
model.contentOffset=CGPoint.init(x: x, y: y)
}
override func layoutSubviews() {
super.layoutSubviews()
scrollView.frame=contentView.bounds
}
private func layout(image:UIImage?)
{
if let image=imageView.image
{
let imageWidth=image.size.width
let imageHeight=image.size.height
let scrollViewWidth=scrollView.bounds.width
let scrollViewHeight=scrollView.bounds.height
var multiple:CGFloat!
if scrollViewWidth < scrollViewHeight
{
imageView.bounds=CGRect.init(x: 0, y: 0, width: scrollViewWidth, height: imageHeight*(scrollViewWidth/imageWidth))
multiple=scrollViewHeight/imageView.bounds.height
}else
{
imageView.bounds=CGRect.init(x: 0, y: 0, width: imageWidth*(scrollViewHeight/imageHeight), height: scrollViewHeight)
multiple=scrollViewWidth/imageView.bounds.width
}
if multiple > 2
{
maximumZoomScale=multiple
}else
{
maximumZoomScale=2
}
scrollView.contentSize=imageView.bounds.size
setImageViewPosition()
}
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
self.layout(image: imageView.image)
}
private func restoreState()
{
switch state! {
case .downloadFail,.downloading:
downloadingOrFailAction()
case .downloadFinish:
downloadFinishAction()
}
}
@objc func rotateScreenAction(_ notification:Notification)
{
let device = UIDevice.current
switch device.orientation {
case .landscapeLeft where scrollView.frame.height > scrollView.frame.width,
.landscapeRight where scrollView.frame.height > scrollView.frame.width,
.portrait where scrollView.frame.width > scrollView.frame.height:
scrollView.frame=CGRect.init(origin: scrollView.frame.origin, size: CGSize.init(width: scrollView.frame.height, height: scrollView.frame.width))
default:
break
}
model.orientation=device.orientation
imageView.willChangeValue(forKey: "image")
imageView.didChangeValue(forKey: "image")
restoreState()
}
deinit {
imageView.removeObserver(self, forKeyPath: "image")
NotificationCenter.default.removeObserver(self, name: NSNotification.Name.UIDeviceOrientationDidChange, object: nil)
}
}
|
mit
|
2420e7efdeaa10b3775e8cd2b0085615
| 34.47619 | 184 | 0.643624 | 5.388788 | false | false | false | false |
pikachu987/PKCAlertView
|
PKCAlertView/Classes/PKCButtonView.swift
|
1
|
5631
|
//Copyright (c) 2017 pikachu987 <[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
class PKCButtonView: UIView {
private var lastButtonGroupView: PKCButtonGrouopView?
private var bottomConst: NSLayoutConstraint?
public init() {
super.init(frame: CGRect.zero)
self.translatesAutoresizingMaskIntoConstraints = false
self.clipsToBounds = true
let buttonViewHeightConst = NSLayoutConstraint(
item: self,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .height,
multiplier: 1,
constant: 44)
buttonViewHeightConst.priority = UILayoutPriority.init(999)
self.addConstraint(buttonViewHeightConst)
}
private override init(frame: CGRect) {
super.init(frame: frame)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
func addButtonGroupView(_ text: String, textColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(text, textColor: textColor, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
func addButtonGroupView(_ leftText: String, leftColor: UIColor, rightText: String, rightColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(leftText, leftColor: leftColor, rightText: rightText, rightColor: rightColor, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
func addButtonGroupView(_ leftText: String, leftColor: UIColor, centerText: String, centerColor: UIColor, rightText: String, rightColor: UIColor, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(leftText, leftColor: leftColor, centerText: centerText, centerColor: centerColor, rightText: rightText, rightColor: rightColor, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
func addButtonGroupView(_ defaultButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(defaultButton, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
func addButtonGroupView(_ leftButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(leftButton, rightButton: rightButton, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
func addButtonGroupView(_ leftButton: PKCAlertButton, centerButton: PKCAlertButton, rightButton: PKCAlertButton, handler: ((PKCAlertButtonType, String) -> Void)? = nil) -> PKCButtonGrouopView{
let buttonGroupView = PKCButtonGrouopView(leftButton, centerButton: centerButton, rightButton: rightButton, handler: handler)
self.addButtonGroupView(buttonGroupView)
return buttonGroupView
}
private func addButtonGroupView(_ buttonGroupView: PKCButtonGrouopView){
self.addSubview(buttonGroupView)
self.addConstraints(buttonGroupView.horizontalLayout())
if let bottomConst = self.bottomConst, let lastButtonGroupView = self.lastButtonGroupView{
let topConst = NSLayoutConstraint(item: lastButtonGroupView, attribute: .bottom, relatedBy: .equal, toItem: buttonGroupView, attribute: .top, multiplier: 1, constant: 0)
self.addConstraint(topConst)
bottomConst.isActive = false
}else{
let topConst = NSLayoutConstraint(item: self, attribute: .top, relatedBy: .equal, toItem: buttonGroupView, attribute: .top, multiplier: 1, constant: 0)
self.addConstraint(topConst)
}
let bottomConst = NSLayoutConstraint(item: self, attribute: .bottom, relatedBy: .equal, toItem: buttonGroupView, attribute: .bottom, multiplier: 1, constant: 0)
self.addConstraint(bottomConst)
self.bottomConst = bottomConst
self.lastButtonGroupView = buttonGroupView
}
}
|
mit
|
b968c5301ba4d07c213c31123da32cd0
| 41.984733 | 229 | 0.70254 | 4.696414 | false | false | false | false |
vapor/vapor
|
Sources/Vapor/Utilities/Extendable.swift
|
1
|
3239
|
/// Types conforming to `Extendable` can have stored properties added in extension by using the `Extend` struct.
///
/// final cass MyType: Extendable { ... }
/// extension MyType {
/// var foo: Int {
/// get { return extend.get(\MyType.foo, default: 0) }
/// set { extend.set(\MyType.foo, to: newValue) }
/// }
/// }
///
public protocol Extendable: AnyObject {
/// Arbitrary property storage. See `Extend` and `Extendable`.
var extend: Extend { get set }
}
/// A wrapper around a simple [String: Any] storage dictionary used to implement `Extendable`.
///
/// final cass MyType: Extendable { ... }
/// extension MyType {
/// var foo: Int {
/// get { return extend.get(\MyType.foo, default: 0) }
/// set { extend.set(\MyType.foo, to: newValue) }
/// }
/// }
///
/// - note: `Extend` conforms to Codable, but will yield an empty dictionary.
/// Extensions are used for convenience and should not be encoded or decoded.
public struct Extend: Codable, ExpressibleByDictionaryLiteral {
/// The internal storage.
public var storage: [String: Any]
/// Create a new extend.
public init() {
storage = [:]
}
/// See `Codable`.
public func encode(to encoder: Encoder) throws {
// skip
}
/// See `Codable`.
public init(from decoder: Decoder) throws {
// skip
storage = [:]
}
/// See `ExpressibleByDictionaryLiteral`.
public init(dictionaryLiteral elements: (String, Any)...) {
self.init()
for (key, value) in elements {
self[key] = value
}
}
/// Gets a value from the `Extend` storage falling back to the default value if it does not exist
/// or cannot be casted to `T`.
///
/// `KeyPath`-based alternative to `get(_:default:)`.
///
/// let foo: Foo = extend.get(\MyType.Foo, default: defaultFoo)
///
public func get<T>(_ key: AnyKeyPath, `default` d: T) -> T {
return get(key.hashValue.description, default: d)
}
/// Set a value to the `Extend` storage.
///
/// `KeyPath`-based alternative to `set(_:to:)`.
///
/// extend.set(\MyType.Foo, to: foo)
///
public mutating func set<T>(_ key: AnyKeyPath, to newValue: T) {
set(key.hashValue.description, to: newValue)
}
/// Gets a value from the `Extend` storage falling back to the default value if it does not exist
/// or cannot be casted to `T`.
///
/// let foo: Foo = extend.get("foo", default: defaultFoo)
///
public func get<T>(_ key: String, `default` d: T) -> T {
return self[key] as? T ?? d
}
/// Set a value to the `Extend` storage.
///
/// extend.set("foo", to: foo)
///
public mutating func set<T>(_ key: String, to newValue: T) {
return self[key] = newValue
}
/// Allow subscripting by `String` key. This is a type-erased alternative to
/// the `get(_:default:)` and `set(:to:)` methods.
///
/// extend["foo"]
///
public subscript(_ key: String) -> Any? {
get { return storage[key] }
set { storage[key] = newValue }
}
}
|
mit
|
23a5aea00872d68b2527d55cf4114b8b
| 30.446602 | 112 | 0.563137 | 3.988916 | false | false | false | false |
jjjjaren/jCode
|
jCode/Classes/Protocols/DataAccessProtocol.swift
|
1
|
1088
|
//
// DataAccessProtocol.swift
// ResearchKit-Demo-1
//
// Created by Jaren Hamblin on 8/23/16.
// Copyright © 2016 Jaren Hamblin. All rights reserved.
//
import Foundation
public protocol DataAccessProtocol {
func fetch<T: AnyObject>(_ entityName: String, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, limit: Int?, completionHandler: ([T]) -> Void)
func fetchFirst<T: AnyObject>(_ entityName: String, predicate: NSPredicate?, sortDescriptors: [NSSortDescriptor]?, completionHandler: (T?) -> Void)
func update<T: AnyObject>(_ object: T)
func delete<T: AnyObject>(_ object: T, completionHandler: (Bool) -> Void)
func save(_ completionHandler: (Bool) -> Void)
}
extension DataAccessProtocol {
func fetch<T : AnyObject>(_ entityName: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, limit: Int? = nil, completionHandler: ([T]) -> Void) {}
func fetchFirst<T: AnyObject>(_ entityName: String, predicate: NSPredicate? = nil, sortDescriptors: [NSSortDescriptor]? = nil, completionHandler: (T?) -> Void) {}
}
|
mit
|
232eb5e0ed8a48a323272f21b67bc511
| 48.409091 | 182 | 0.707452 | 4.164751 | false | false | false | false |
coach-plus/ios
|
Pods/SwiftDate/Sources/SwiftDate/DateInRegion/DateInRegion+Compare.swift
|
1
|
11745
|
//
// SwiftDate
// Parse, validate, manipulate, and display dates, time and timezones in Swift
//
// Created by Daniele Margutti
// - Web: https://www.danielemargutti.com
// - Twitter: https://twitter.com/danielemargutti
// - Mail: [email protected]
//
// Copyright © 2019 Daniele Margutti. Licensed under MIT License.
//
import Foundation
// MARK: - Comparing DateInRegion
public func == (lhs: DateInRegion, rhs: DateInRegion) -> Bool {
return (lhs.date.timeIntervalSince1970 == rhs.date.timeIntervalSince1970)
}
public func <= (lhs: DateInRegion, rhs: DateInRegion) -> Bool {
let result = lhs.date.compare(rhs.date)
return (result == .orderedAscending || result == .orderedSame)
}
public func >= (lhs: DateInRegion, rhs: DateInRegion) -> Bool {
let result = lhs.date.compare(rhs.date)
return (result == .orderedDescending || result == .orderedSame)
}
public func < (lhs: DateInRegion, rhs: DateInRegion) -> Bool {
return lhs.date.compare(rhs.date) == .orderedAscending
}
public func > (lhs: DateInRegion, rhs: DateInRegion) -> Bool {
return lhs.date.compare(rhs.date) == .orderedDescending
}
// The type of comparison to do against today's date or with the suplied date.
///
/// - isToday: hecks if date today.
/// - isTomorrow: Checks if date is tomorrow.
/// - isYesterday: Checks if date is yesterday.
/// - isSameDay: Compares date days
/// - isThisWeek: Checks if date is in this week.
/// - isNextWeek: Checks if date is in next week.
/// - isLastWeek: Checks if date is in last week.
/// - isSameWeek: Compares date weeks
/// - isThisMonth: Checks if date is in this month.
/// - isNextMonth: Checks if date is in next month.
/// - isLastMonth: Checks if date is in last month.
/// - isSameMonth: Compares date months
/// - isThisYear: Checks if date is in this year.
/// - isNextYear: Checks if date is in next year.
/// - isLastYear: Checks if date is in last year.
/// - isSameYear: Compare date years
/// - isInTheFuture: Checks if it's a future date
/// - isInThePast: Checks if the date has passed
/// - isEarlier: Checks if earlier than date
/// - isLater: Checks if later than date
/// - isWeekday: Checks if it's a weekday
/// - isWeekend: Checks if it's a weekend
/// - isInDST: Indicates whether the represented date uses daylight saving time.
/// - isMorning: Return true if date is in the morning (>=5 - <12)
/// - isAfternoon: Return true if date is in the afternoon (>=12 - <17)
/// - isEvening: Return true if date is in the morning (>=17 - <21)
/// - isNight: Return true if date is in the morning (>=21 - <5)
public enum DateComparisonType {
// Days
case isToday
case isTomorrow
case isYesterday
case isSameDay(_ : DateRepresentable)
// Weeks
case isThisWeek
case isNextWeek
case isLastWeek
case isSameWeek(_: DateRepresentable)
// Months
case isThisMonth
case isNextMonth
case isLastMonth
case isSameMonth(_: DateRepresentable)
// Years
case isThisYear
case isNextYear
case isLastYear
case isSameYear(_: DateRepresentable)
// Relative Time
case isInTheFuture
case isInThePast
case isEarlier(than: DateRepresentable)
case isLater(than: DateRepresentable)
case isWeekday
case isWeekend
// Day time
case isMorning
case isAfternoon
case isEvening
case isNight
// TZ
case isInDST
}
public extension DateInRegion {
/// Decides whether a DATE is "close by" another one passed in parameter,
/// where "Being close" is measured using a precision argument
/// which is initialized a 300 seconds, or 5 minutes.
///
/// - Parameters:
/// - refDate: reference date compare against to.
/// - precision: The precision of the comparison (default is 5 minutes, or 300 seconds).
/// - Returns: A boolean; true if close by, false otherwise.
func compareCloseTo(_ refDate: DateInRegion, precision: TimeInterval = 300) -> Bool {
return (abs(date.timeIntervalSince(refDate.date)) <= precision)
}
/// Compare the date with the rule specified in the `compareType` parameter.
///
/// - Parameter compareType: comparison type.
/// - Returns: `true` if comparison succeded, `false` otherwise
func compare(_ compareType: DateComparisonType) -> Bool {
switch compareType {
case .isToday:
return compare(.isSameDay(region.nowInThisRegion()))
case .isTomorrow:
let tomorrow = DateInRegion(region: region).dateByAdding(1, .day)
return compare(.isSameDay(tomorrow))
case .isYesterday:
let yesterday = DateInRegion(region: region).dateByAdding(-1, .day)
return compare(.isSameDay(yesterday))
case .isSameDay(let refDate):
return calendar.isDate(date, inSameDayAs: refDate.date)
case .isThisWeek:
return compare(.isSameWeek(region.nowInThisRegion()))
case .isNextWeek:
let nextWeek = region.nowInThisRegion().dateByAdding(1, .weekOfYear)
return compare(.isSameWeek(nextWeek))
case .isLastWeek:
let lastWeek = region.nowInThisRegion().dateByAdding(-1, .weekOfYear)
return compare(.isSameWeek(lastWeek))
case .isSameWeek(let refDate):
guard weekOfYear == refDate.weekOfYear else {
return false
}
// Ensure time interval is under 1 week
return (abs(date.timeIntervalSince(refDate.date)) < 1.weeks.timeInterval)
case .isThisMonth:
return compare(.isSameMonth(region.nowInThisRegion()))
case .isNextMonth:
let nextMonth = region.nowInThisRegion().dateByAdding(1, .month)
return compare(.isSameMonth(nextMonth))
case .isLastMonth:
let lastMonth = region.nowInThisRegion().dateByAdding(-1, .month)
return compare(.isSameMonth(lastMonth))
case .isSameMonth(let refDate):
return (date.year == refDate.date.year) && (date.month == refDate.date.month)
case .isThisYear:
return compare(.isSameYear(region.nowInThisRegion()))
case .isNextYear:
let nextYear = region.nowInThisRegion().dateByAdding(1, .year)
return compare(.isSameYear(nextYear))
case .isLastYear:
let lastYear = region.nowInThisRegion().dateByAdding(-1, .year)
return compare(.isSameYear(lastYear))
case .isSameYear(let refDate):
return (date.year == refDate.date.year)
case .isInTheFuture:
return compare(.isLater(than: region.nowInThisRegion()))
case .isInThePast:
return compare(.isEarlier(than: region.nowInThisRegion()))
case .isEarlier(let refDate):
return ((date as NSDate).earlierDate(refDate.date) == date)
case .isLater(let refDate):
return ((date as NSDate).laterDate(refDate.date) == date)
case .isWeekday:
return !compare(.isWeekend)
case .isWeekend:
let range = calendar.maximumRange(of: Calendar.Component.weekday)!
return (weekday == range.lowerBound || weekday == range.upperBound - range.lowerBound)
case .isInDST:
return region.timeZone.isDaylightSavingTime(for: date)
case .isMorning:
return (hour >= 5 && hour < 12)
case .isAfternoon:
return (hour >= 12 && hour < 17)
case .isEvening:
return (hour >= 17 && hour < 21)
case .isNight:
return (hour >= 21 || hour < 5)
}
}
/// Returns a ComparisonResult value that indicates the ordering of two given dates based on
/// their components down to a given unit granularity.
///
/// - parameter date: date to compare.
/// - parameter granularity: The smallest unit that must, along with all larger units
/// - returns: `ComparisonResult`
func compare(toDate refDate: DateInRegion, granularity: Calendar.Component) -> ComparisonResult {
switch granularity {
case .nanosecond:
// There is a possible rounding error using Calendar to compare two dates below the minute granularity
// So we've added this trick and use standard Date compare which return correct results in this case
// https://github.com/malcommac/SwiftDate/issues/346
return date.compare(refDate.date)
default:
return region.calendar.compare(date, to: refDate.date, toGranularity: granularity)
}
}
/// Compares whether the receiver is before/before equal `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - refDate: reference date
/// - orEqual: `true` to also check for equality
/// - granularity: smallest unit that must, along with all larger units, be less for the given dates
/// - Returns: Boolean
func isBeforeDate(_ date: DateInRegion, orEqual: Bool = false, granularity: Calendar.Component) -> Bool {
let result = compare(toDate: date, granularity: granularity)
return (orEqual ? (result == .orderedSame || result == .orderedAscending) : result == .orderedAscending)
}
/// Compares whether the receiver is after `date` based on their components down to a given unit granularity.
///
/// - Parameters:
/// - refDate: reference date
/// - orEqual: `true` to also check for equality
/// - granularity: Smallest unit that must, along with all larger units, be greater for the given dates.
/// - Returns: Boolean
func isAfterDate(_ refDate: DateInRegion, orEqual: Bool = false, granularity: Calendar.Component) -> Bool {
let result = compare(toDate: refDate, granularity: granularity)
return (orEqual ? (result == .orderedSame || result == .orderedDescending) : result == .orderedDescending)
}
/// Compares equality of two given dates based on their components down to a given unit
/// granularity.
///
/// - parameter date: date to compare
/// - parameter granularity: The smallest unit that must, along with all larger units, be equal for the given
/// dates to be considered the same.
///
/// - returns: `true` if the dates are the same down to the given granularity, otherwise `false`
func isInside(date: DateInRegion, granularity: Calendar.Component) -> Bool {
return (compare(toDate: date, granularity: granularity) == .orderedSame)
}
/// Return `true` if receiver data is contained in the range specified by two dates.
///
/// - Parameters:
/// - startDate: range upper bound date
/// - endDate: range lower bound date
/// - orEqual: `true` to also check for equality on date and date2, default is `true`
/// - granularity: smallest unit that must, along with all larger units, be greater
/// - Returns: Boolean
func isInRange(date startDate: DateInRegion, and endDate: DateInRegion, orEqual: Bool = true, granularity: Calendar.Component = .nanosecond) -> Bool {
return isAfterDate(startDate, orEqual: orEqual, granularity: granularity) && isBeforeDate(endDate, orEqual: orEqual, granularity: granularity)
}
// MARK: - Date Earlier/Later
/// Return the earlier of two dates, between self and a given date.
///
/// - Parameter date: The date to compare to self
/// - Returns: The date that is earlier
func earlierDate(_ date: DateInRegion) -> DateInRegion {
return self.date.timeIntervalSince(date.date) <= 0 ? self : date
}
/// Return the later of two dates, between self and a given date.
///
/// - Parameter date: The date to compare to self
/// - Returns: The date that is later
func laterDate(_ date: DateInRegion) -> DateInRegion {
return self.date.timeIntervalSince(date.date) >= 0 ? self : date
}
/// Returns the difference in the calendar component given (like day, month or year)
/// with respect to the other date as a positive integer
func difference(in component: Calendar.Component, from other: DateInRegion) -> Int? {
return self.date.difference(in: component, from: other.date)
}
/// Returns the differences in the calendar components given (like day, month and year)
/// with respect to the other date as dictionary with the calendar component as the key
/// and the diffrence as a positive integer as the value
func differences(in components: Set<Calendar.Component>, from other: DateInRegion) -> [Calendar.Component: Int] {
return self.date.differences(in: components, from: other.date)
}
}
|
mit
|
1f4a3acc3ee27eeca3fb3bd6b0d92ff4
| 35.02454 | 151 | 0.711853 | 3.931704 | false | false | false | false |
kronik/ScalePicker
|
ScalePicker/SlidePicker.swift
|
2
|
25702
|
//
// SlidePicker.swift
// Dmitry Klimkin
//
// Created by Dmitry Klimkin on 12/11/15.
// Copyright © 2016 Dmitry Klimkin. All rights reserved.
//
import Foundation
import UIKit
public protocol SlidePickerDelegate {
func didSelectValue(value: CGFloat)
func didChangeContentOffset(offset: CGFloat, progress: CGFloat)
func didBeginChangingValue()
func didEndChangingValue()
}
public typealias CompleteHandler = (()->Void)
@IBDesignable
public class SlidePicker: UIView, UICollectionViewDelegateFlowLayout, UICollectionViewDataSource {
public var delegate: SlidePickerDelegate?
@IBInspectable
public var gradientMaskEnabled: Bool = false {
didSet {
layer.mask = gradientMaskEnabled ? maskLayer : nil
layoutSubviews()
}
}
@IBInspectable
public var invertValues: Bool = false {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var fillSides: Bool = false {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var allTicksWithSameSize: Bool = false {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var blockedUI: Bool = false {
didSet {
uiBlockView.removeFromSuperview()
if blockedUI {
addSubview(uiBlockView)
}
layoutSubviews()
}
}
@IBInspectable
public var showPlusForPositiveValues: Bool = true {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var snapEnabled: Bool = true
@IBInspectable
public var fireValuesOnScrollEnabled: Bool = true
@IBInspectable
public var showTickLabels: Bool = true {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var highlightCenterTick: Bool = true {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var bounces: Bool = false {
didSet {
collectionView.bounces = bounces
}
}
@IBInspectable
public var spaceBetweenTicks: CGFloat = 20.0 {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var centerViewOffsetY: CGFloat = 0.0 {
didSet {
layoutSubviews()
}
}
private let cellId = "collectionViewCellId"
private var flowLayout = SlidePickerFlowLayout()
private var collectionView: UICollectionView!
private var tickValue: CGFloat = 1.0
private var maskLayer: CALayer!
private var maskLeftLayer: CAGradientLayer!
private var maskRightLayer: CAGradientLayer!
private var uiBlockView: UIView!
private var reloadTimer: NSTimer?
public var centerView: UIView? {
didSet {
if let centerView = centerView {
centerViewOffsetY = 0.0
addSubview(centerView)
}
}
}
public var values: [CGFloat]? {
didSet {
guard let values = values where values.count > 1 else { return; }
updateSectionsCount()
requestCollectionViewReloading()
}
}
@IBInspectable
public var tickColor: UIColor = UIColor.whiteColor() {
didSet {
requestCollectionViewReloading()
}
}
private var sectionsCount: Int = 0 {
didSet {
requestCollectionViewReloading()
}
}
@IBInspectable
public var minValue: CGFloat = 0.0 {
didSet {
updateSectionsCount()
}
}
@IBInspectable
public var maxValue: CGFloat = 0.0 {
didSet {
updateSectionsCount()
}
}
private func updateSectionsCount() {
guard minValue < maxValue else {
return
}
if let values = values {
var sections = (values.count / Int(numberOfTicksBetweenValues + 1)) + 2
if values.count % Int(numberOfTicksBetweenValues + 1) > 0 {
sections += 1
}
sectionsCount = sections
} else {
let items = maxValue - minValue + 1.0
if items > 1 {
sectionsCount = Int(items) + 2
} else {
sectionsCount = 0
}
}
}
@IBInspectable
public var numberOfTicksBetweenValues: UInt = 2 {
didSet {
tickValue = 1.0 / CGFloat(numberOfTicksBetweenValues + 1)
updateSectionsCount()
}
}
public var currentTransform: CGAffineTransform = CGAffineTransformIdentity {
didSet {
requestCollectionViewReloading()
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public func commonInit() {
userInteractionEnabled = true
flowLayout.scrollDirection = .Horizontal
flowLayout.minimumInteritemSpacing = 0.0
flowLayout.minimumLineSpacing = 0.0
collectionView = UICollectionView(frame: frame, collectionViewLayout: flowLayout)
collectionView.delegate = self
collectionView.dataSource = self
collectionView.backgroundColor = UIColor.clearColor()
collectionView.showsHorizontalScrollIndicator = false
collectionView.bounces = false
collectionView.allowsSelection = false
collectionView.delaysContentTouches = true
collectionView.registerClass(SlidePickerCell.self, forCellWithReuseIdentifier: cellId)
addSubview(collectionView)
maskLayer = CALayer()
maskLayer.frame = CGRectZero
maskLayer.backgroundColor = UIColor.clearColor().CGColor
maskLeftLayer = CAGradientLayer()
maskLeftLayer.frame = maskLayer.bounds
maskLeftLayer.colors = [UIColor.blackColor().colorWithAlphaComponent(0.0).CGColor, UIColor.blackColor().CGColor]
maskLeftLayer.startPoint = CGPointMake(0.1, 0.0)
maskLeftLayer.endPoint = CGPointMake(0.9, 0.0)
maskRightLayer = CAGradientLayer()
maskRightLayer.frame = maskLayer.bounds
maskRightLayer.colors = [UIColor.blackColor().CGColor, UIColor.blackColor().colorWithAlphaComponent(0.0).CGColor]
maskRightLayer.startPoint = CGPointMake(0.1, 0.0)
maskRightLayer.endPoint = CGPointMake(0.9, 0.0)
maskLayer.addSublayer(maskLeftLayer)
maskLayer.addSublayer(maskRightLayer)
uiBlockView = UIView(frame: self.bounds)
}
private func requestCollectionViewReloading() {
reloadTimer?.invalidate()
reloadTimer = NSTimer.scheduledTimerWithTimeInterval(0.1, target: self, selector: #selector(SlidePicker.reloadCollectionView), userInfo: nil, repeats: false)
}
func reloadCollectionView() {
reloadTimer?.invalidate()
collectionView.reloadData()
}
public override func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = bounds
centerView?.center = CGPointMake(frame.size.width / 2,
centerViewOffsetY + (frame.size.height / 2) - 2)
if gradientMaskEnabled {
let gradientMaskWidth = frame.size.width / 2
maskLayer.frame = CGRect(x: 0, y: 0, width: frame.size.width, height: frame.size.height)
maskLeftLayer.frame = CGRect(x: 0, y: 0, width: gradientMaskWidth, height: frame.size.height)
maskRightLayer.frame = CGRect(x: frame.size.width - gradientMaskWidth, y: 0, width: gradientMaskWidth, height: frame.size.height)
} else {
maskLayer.frame = CGRectZero
maskLeftLayer.frame = maskLayer.bounds
maskRightLayer.frame = maskLayer.bounds
}
uiBlockView.frame = bounds
}
public override func prepareForInterfaceBuilder() {
super.prepareForInterfaceBuilder()
layoutSubviews()
}
public func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
guard sectionsCount > 2 else {
return CGSizeZero
}
let regularCellSize = CGSizeMake(spaceBetweenTicks, bounds.height)
if (indexPath.section == 0) || (indexPath.section == (sectionsCount - 1)) {
if fillSides {
let sideItems = (Int(frame.size.width / spaceBetweenTicks) + 2) / 2
if (indexPath.section == 0 && indexPath.row == 0) ||
(indexPath.section == sectionsCount - 1 && indexPath.row == sideItems - 1) {
return CGSizeMake((spaceBetweenTicks / 2) - SlidePickerCell.strokeWidth, bounds.height)
} else {
return regularCellSize
}
} else {
return CGSizeMake((bounds.width / 2) - (spaceBetweenTicks / 2), bounds.height)
}
}
return regularCellSize
}
public func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
guard sectionsCount > 2 else {
return 0
}
if (section == 0) || (section >= (sectionsCount - 1)) {
let sideItems = Int(frame.size.width / spaceBetweenTicks) + 2
return fillSides ? sideItems / 2 : 1
} else {
if let values = values {
let elements = (section - 1) * Int(numberOfTicksBetweenValues + 1)
let rows = values.count - elements
if rows > 0 {
return min(rows, Int(numberOfTicksBetweenValues + 1))
} else {
return 0
}
} else {
if section >= (sectionsCount - 2) {
return 1
} else {
return Int(numberOfTicksBetweenValues) + 1
}
}
}
}
public func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCellWithReuseIdentifier(cellId, forIndexPath: indexPath) as! SlidePickerCell
cell.indexPath = indexPath
cell.tickColor = tickColor
cell.showTickLabels = showTickLabels
cell.highlightTick = false
cell.currentTransform = currentTransform
cell.showPlusForPositiveValues = showPlusForPositiveValues
if indexPath.section == 0 {
cell.updateValue(invertValues ? CGFloat.max : CGFloat.min, type: fillSides ? .BigStroke : .Empty)
} else if indexPath.section == sectionsCount - 1 {
cell.updateValue(invertValues ? CGFloat.min : CGFloat.max, type: fillSides ? .BigStroke : .Empty)
} else {
if let values = values {
cell.highlightTick = false
let index = (indexPath.section - 1) * Int(numberOfTicksBetweenValues + 1) + indexPath.row
let currentValue = values[index]
cell.updateValue(currentValue, type: allTicksWithSameSize || indexPath.row == 0 ? .BigStroke : .SmallStroke)
} else {
let currentValue = invertValues ? maxValue - CGFloat(indexPath.section - 1) : minValue + CGFloat(indexPath.section - 1)
if indexPath.row == 0 {
if highlightCenterTick {
cell.highlightTick = (currentValue == ((maxValue - minValue) * 0.5 + minValue))
} else {
cell.highlightTick = false
}
cell.updateValue(currentValue, type: .BigStroke)
} else {
let value = invertValues ? currentValue - tickValue * CGFloat(indexPath.row) : currentValue + tickValue * CGFloat(indexPath.row)
cell.showTickLabels = allTicksWithSameSize ? false : showTickLabels
cell.updateValue(value, type: allTicksWithSameSize ? .BigStroke : .SmallStroke)
}
}
}
return cell
}
public func numberOfSectionsInCollectionView(collectionView: UICollectionView) -> Int {
return sectionsCount
}
public func updateCurrentProgress() {
let offset = collectionView.contentOffset.x
let contentSize = collectionView.contentSize.width
if offset <= 0 {
delegate?.didChangeContentOffset(offset, progress: 0)
} else if offset >= contentSize - frame.size.width {
delegate?.didChangeContentOffset(offset - contentSize + frame.size.width, progress: 1)
} else {
delegate?.didChangeContentOffset(0, progress: offset / (collectionView.contentSize.width - frame.size.width))
}
}
public func scrollToValue(value: CGFloat, animated: Bool, reload: Bool = true, complete: CompleteHandler? = nil) {
var indexPath: NSIndexPath?
guard sectionsCount > 0 else {
return
}
if let values = values {
var valueIndex = 0
for index in 0..<values.count {
if value == values[index] {
valueIndex = index
break
}
}
let section = (valueIndex / Int(numberOfTicksBetweenValues + 1))
let row = valueIndex - (section * Int(numberOfTicksBetweenValues + 1))
indexPath = NSIndexPath(forRow: row, inSection: section + 1)
let cell = collectionView(collectionView, cellForItemAtIndexPath: indexPath!) as? SlidePickerCell
if let cell = cell where cell.value == value {
delegate?.didSelectValue(cell.value)
collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .CenteredHorizontally, animated: animated)
complete?()
}
} else {
if snapEnabled {
for i in 1..<sectionsCount {
let itemsCount = self.collectionView(collectionView, numberOfItemsInSection: i)
for j in 0..<itemsCount {
indexPath = NSIndexPath(forRow: j, inSection: i)
let cell = collectionView(collectionView, cellForItemAtIndexPath: indexPath!) as? SlidePickerCell
if let cell = cell where cell.value == value {
delegate?.didSelectValue(cell.value)
collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .CenteredHorizontally, animated: animated)
complete?()
break
}
}
}
} else {
var time: CGFloat = 0.0
if reload {
time = 0.5
collectionView.reloadData()
}
let popTime = dispatch_time(DISPATCH_TIME_NOW, Int64(time * CGFloat(NSEC_PER_SEC)))
dispatch_after(popTime, dispatch_get_main_queue()) {
let absoluteValue = value - self.minValue
let percent = absoluteValue / (self.maxValue - self.minValue)
let absolutePercent = self.invertValues ? (1.0 - percent) : percent
let offsetX = absolutePercent * (self.collectionView.contentSize.width - self.bounds.width)
self.collectionView.contentOffset = CGPointMake(offsetX, self.collectionView.contentOffset.y)
complete?()
}
}
}
}
public func increaseValue() {
let point = CGPointMake(collectionView.center.x + collectionView.contentOffset.x + spaceBetweenTicks * 2 / 3,
collectionView.center.y + collectionView.contentOffset.y)
scrollToNearestCellAtPoint(point)
}
public func decreaseValue() {
let point = CGPointMake(collectionView.center.x + collectionView.contentOffset.x - spaceBetweenTicks * 2 / 3,
collectionView.center.y + collectionView.contentOffset.y)
scrollToNearestCellAtPoint(point)
}
private func updateSelectedValue(tryToSnap: Bool) {
if snapEnabled {
let initialPinchPoint = CGPointMake(collectionView.center.x + collectionView.contentOffset.x,
collectionView.center.y + collectionView.contentOffset.y)
scrollToNearestCellAtPoint(initialPinchPoint, skipScroll: fireValuesOnScrollEnabled && !tryToSnap)
} else {
let percent = collectionView.contentOffset.x / (collectionView.contentSize.width - bounds.width)
let absoluteValue = percent * (maxValue - minValue)
let currentValue = invertValues ? min(max(maxValue - absoluteValue, minValue), maxValue) : max(min(absoluteValue + minValue, maxValue), minValue)
delegate?.didSelectValue(currentValue)
}
}
private func scrollToNearestCellAtPoint(point: CGPoint, skipScroll: Bool = false) {
var centerCell: SlidePickerCell?
let indexPath = collectionView.indexPathForItemAtPoint(point)
if let iPath = indexPath {
if (iPath.section == 0) || (iPath.section == (sectionsCount - 1)) {
return
}
centerCell = self.collectionView(collectionView, cellForItemAtIndexPath: iPath) as? SlidePickerCell
}
guard let cell = centerCell else {
return
}
delegate?.didSelectValue(cell.value)
if !skipScroll {
collectionView.scrollToItemAtIndexPath(indexPath!, atScrollPosition: .CenteredHorizontally, animated: true)
}
}
}
public enum SlidePickerCellType {
case Empty
case BigStroke
case SmallStroke
}
public class SlidePickerCell: UICollectionViewCell {
public static var signWidth: CGFloat = {
let sign = "-"
let maximumTextSize = CGSizeMake(100, 100)
let textString = sign as NSString
let font = UIFont.systemFontOfSize(12.0)
let rect = textString.boundingRectWithSize(maximumTextSize, options: .UsesLineFragmentOrigin,
attributes: [NSFontAttributeName: font], context: nil)
return (rect.width / 2) + 1
}()
public static let strokeWidth: CGFloat = 1.5
public var showTickLabels = true
public var showPlusForPositiveValues = true
public var highlightTick = false
private var type = SlidePickerCellType.Empty
public var value: CGFloat = 0.0 {
didSet {
let strValue = String(format: "%0.0f", value)
if value > 0.00001 && showPlusForPositiveValues {
valueLabel.text = "+" + strValue
} else {
valueLabel.text = strValue
}
}
}
public var indexPath: NSIndexPath?
private let strokeView = UIView()
private let valueLabel = UILabel()
private let strokeWidth: CGFloat = SlidePickerCell.strokeWidth
private var bigStrokePaddind: CGFloat = 4.0
private var smallStrokePaddind: CGFloat = 8.0
public var currentTransform: CGAffineTransform = CGAffineTransformIdentity {
didSet {
valueLabel.transform = currentTransform
}
}
public var tickColor = UIColor.whiteColor() {
didSet {
strokeView.backgroundColor = tickColor
valueLabel.textColor = tickColor
}
}
public override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
public override func prepareForReuse() {
super.prepareForReuse()
strokeView.alpha = 0.0
valueLabel.alpha = 0.0
indexPath = nil
}
public func updateValue(value: CGFloat, type: SlidePickerCellType) {
self.value = value
self.type = type
layoutSubviews()
}
private func commonInit() {
strokeView.backgroundColor = UIColor.whiteColor()
strokeView.alpha = 0.0
strokeView.layer.masksToBounds = true
strokeView.layer.cornerRadius = strokeWidth / 2
valueLabel.textAlignment = .Center
valueLabel.font = UIFont.systemFontOfSize(12.0)
valueLabel.textColor = UIColor.whiteColor()
valueLabel.alpha = 0.0
contentView.addSubview(strokeView)
contentView.addSubview(valueLabel)
}
public override func layoutSubviews() {
super.layoutSubviews()
let height = frame.size.height
let xShift: CGFloat = (showPlusForPositiveValues && value > 0.0001) || value < -0.0001 ? SlidePickerCell.signWidth : 0.0
switch type {
case .Empty:
strokeView.alpha = 0.0
valueLabel.alpha = 0.0
break
case .BigStroke:
let widthAddition: CGFloat = highlightTick ? 0.5 : 0.0
strokeView.alpha = 1.0
valueLabel.alpha = showTickLabels ? 1.0 : 0.0
if showTickLabels {
valueLabel.frame = CGRectMake(-5 - xShift, 0, frame.size.width + 10, height / 3)
} else {
valueLabel.frame = CGRectZero
}
strokeView.frame = CGRectMake((frame.size.width / 2) - (strokeWidth / 2) - widthAddition,
(height / 3) + bigStrokePaddind, strokeWidth + widthAddition * 2,
(height / 2) - (bigStrokePaddind * 2))
strokeView.layer.cornerRadius = strokeView.frame.width
break
case .SmallStroke:
strokeView.alpha = 1.0
valueLabel.alpha = 0.0
if showTickLabels {
valueLabel.frame = CGRectMake(-xShift, 0, frame.size.width, height / 2)
} else {
valueLabel.frame = CGRectZero
}
strokeView.frame = CGRectMake((frame.size.width / 2) - (strokeWidth / 2),
(height / 3) + smallStrokePaddind, strokeWidth,
(height / 2) - (smallStrokePaddind * 2))
strokeView.layer.cornerRadius = strokeView.frame.width
break
}
}
}
extension SlidePicker: UIScrollViewDelegate {
public func scrollViewWillBeginDecelerating(scrollView: UIScrollView) {
delegate?.didBeginChangingValue()
}
public func scrollViewWillBeginDragging(scrollView: UIScrollView) {
delegate?.didBeginChangingValue()
}
public func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
updateSelectedValue(true)
delegate?.didEndChangingValue()
}
public func scrollViewDidEndDragging(scrollView: UIScrollView, willDecelerate decelerate: Bool) {
updateSelectedValue(true)
delegate?.didEndChangingValue()
}
public func scrollViewDidScroll(scrollView: UIScrollView) {
updateSelectedValue(false)
updateCurrentProgress()
}
}
internal extension UIImage {
internal func tintImage(color: UIColor) -> UIImage {
let scale: CGFloat = 2.0
UIGraphicsBeginImageContextWithOptions(size, false, scale)
let context = UIGraphicsGetCurrentContext()
CGContextTranslateCTM(context, 0, size.height)
CGContextScaleCTM(context, 1.0, -1.0)
let rect = CGRectMake(0, 0, size.width, size.height)
CGContextSetBlendMode(context, .Normal)
CGContextDrawImage(context, rect, CGImage)
CGContextSetBlendMode(context, .SourceIn)
color.setFill()
CGContextFillRect(context, rect)
let coloredImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return coloredImage.imageWithRenderingMode(.AlwaysOriginal)
}
}
|
mit
|
a06c1ae0a025a60c52fd8e190a4a75b8
| 32.728346 | 176 | 0.569394 | 5.579896 | false | false | false | false |
kenwilcox/Instafilter
|
Instafilter/ViewController.swift
|
1
|
4967
|
//
// ViewController.swift
// Instafilter
//
// Created by Kenneth Wilcox on 1/4/16.
// Copyright © 2016 Kenneth Wilcox. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var imageView: UIImageView!
@IBOutlet weak var intensity: UISlider!
var currentImage: UIImage!
var context: CIContext!
var currentFilter: CIFilter!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
title = "Instafilter"
navigationItem.rightBarButtonItem = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: "importPicture")
context = CIContext(options: nil)
currentFilter = CIFilter(name: "CISepiaTone")
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func changeFilter(sender: AnyObject) {
let ac = UIAlertController(title: "Choose filter", message: nil, preferredStyle: .ActionSheet)
ac.addAction(UIAlertAction(title: "CIBumpDistortion", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIGaussianBlur", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIPixellate", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CISepiaTone", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CITwirlDistortion", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIUnsharpMask", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "CIVignette", style: .Default, handler: setFilter))
ac.addAction(UIAlertAction(title: "Cancel", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
@IBAction func save(sender: AnyObject) {
UIImageWriteToSavedPhotosAlbum(imageView.image!, self, "image:didFinishSavingWithError:contextInfo:", nil)
}
@IBAction func intensityChanged(sender: AnyObject) {
applyProcessing()
}
func importPicture() {
let picker = UIImagePickerController()
picker.allowsEditing = true
picker.delegate = self
presentViewController(picker, animated: true, completion: nil)
}
func applyProcessing() {
let inputKeys = currentFilter.inputKeys
if inputKeys.contains(kCIInputIntensityKey) { currentFilter.setValue(intensity.value, forKey: kCIInputIntensityKey) }
if inputKeys.contains(kCIInputRadiusKey) { currentFilter.setValue(intensity.value * 200, forKey: kCIInputRadiusKey) }
if inputKeys.contains(kCIInputScaleKey) { currentFilter.setValue(intensity.value * 10, forKey: kCIInputScaleKey) }
if inputKeys.contains(kCIInputCenterKey) { currentFilter.setValue(CIVector(x: currentImage.size.width / 2, y: currentImage.size.height / 2), forKey: kCIInputCenterKey) }
let cgimg = context.createCGImage(currentFilter.outputImage!, fromRect: currentFilter.outputImage!.extent)
let processedImage = UIImage(CGImage: cgimg)
self.imageView.image = processedImage
}
func setFilter(action: UIAlertAction!) {
currentFilter = CIFilter(name: action.title!)
let beginImage = CIImage(image: currentImage)
currentFilter.setValue(beginImage, forKey: kCIInputImageKey)
applyProcessing()
}
func image(image: UIImage, didFinishSavingWithError error: NSError?, contextInfo:UnsafePointer<Void>) {
if error == nil {
let ac = UIAlertController(title: "Saved!", message: "Your altered image has been saved to your photos.", preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
} else {
let ac = UIAlertController(title: "Save error", message: error?.localizedDescription, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
}
}
extension ViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
var newImage: UIImage
if let possibleImage = info["UIImagePickerControllerEditedImage"] as? UIImage {
newImage = possibleImage
} else if let possibleImage = info["UIImagePickerControllerOriginalImage"] as? UIImage {
newImage = possibleImage
} else {
return
}
dismissViewControllerAnimated(true, completion: nil)
currentImage = newImage
let beginImage = CIImage(image: currentImage)
currentFilter.setValue(beginImage, forKey: kCIInputImageKey)
applyProcessing()
}
func imagePickerControllerDidCancel(picker: UIImagePickerController) {
dismissViewControllerAnimated(true, completion: nil)
}
}
|
mit
|
b3d8a54586587f6e710960aff12219ab
| 40.041322 | 173 | 0.734998 | 4.807357 | false | false | false | false |
mike-wernli/six-scrum-poker
|
six-scrum-poker/ClassicViewController.swift
|
1
|
4808
|
//
// ClassicViewController.swift
// six-scrum-poker
//
// Created by codecamp on 10.06.16.
// Copyright © 2016 six.codecamp16. All rights reserved.
//
import UIKit
class ClassicViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
let detailView = segue.destinationViewController as! ClassicDetailsViewController
NSLog("Segue is: " + segue.identifier!)
if segue.identifier == "showCardQuestion" {
detailView.labelCardText = "?"
//detailView.view.backgroundColor = UIColor(red: 0, green: 165/255, blue: 0, alpha: 1)
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card ?")
} else if segue.identifier == "showCardCoffee" {
detailView.labelCardText = "☕️"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card coffee")
} else if segue.identifier == "showCard0" {
detailView.labelCardText = "0"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 0")
} else if segue.identifier == "showCardHalf" {
detailView.labelCardText = "½"
detailView.view.backgroundColor = UIColor.lightGrayColor()
NSLog("Pressed for Card Half")
} else if segue.identifier == "showCard1" {
detailView.labelCardText = "1"
detailView.view.backgroundColor = UIColor.grayColor()
NSLog("Pressed for Card 1")
} else if segue.identifier == "showCard2" {
detailView.labelCardText = "2"
detailView.view.backgroundColor = UIColor.lightGrayColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 2")
} else if segue.identifier == "showCard3" {
detailView.labelCardText = "3"
detailView.view.backgroundColor = UIColor.greenColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 3")
} else if segue.identifier == "showCard5" {
detailView.labelCardText = "5"
detailView.view.backgroundColor = UIColor.yellowColor().colorWithAlphaComponent(0.75)
detailView.view.opaque = true
NSLog("Pressed for Card 5")
} else if segue.identifier == "showCard8" {
detailView.labelCardText = "8"
detailView.view.backgroundColor = UIColor.orangeColor()
detailView.labelPokerCard.textColor = UIColor.lightGrayColor()
NSLog("Pressed for Card 8")
} else if segue.identifier == "showCard13" {
detailView.labelCardText = "13"
detailView.view.backgroundColor = UIColor.blueColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 13")
} else if segue.identifier == "showCard20" {
detailView.labelCardText = "20"
detailView.view.backgroundColor = UIColor.redColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 20")
} else if segue.identifier == "showCard40" {
detailView.labelCardText = "40"
detailView.view.backgroundColor = UIColor.purpleColor().colorWithAlphaComponent(0.75)
NSLog("Pressed for Card 40")
} else if segue.identifier == "showCard100" {
detailView.labelCardText = "100"
detailView.view.backgroundColor = UIColor.brownColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.hidden = true
detailView.labelPokerCardSmall.hidden = false
NSLog("Pressed for Card 100")
} else if segue.identifier == "showCardInfinity" {
detailView.labelCardText = "∞"
detailView.view.backgroundColor = UIColor.blackColor().colorWithAlphaComponent(0.75)
detailView.labelPokerCard.textColor = UIColor.whiteColor()
NSLog("Pressed for Card Infinity")
} else {
detailView.labelCardText = "na"
}
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
9fe929d18878480a70f78a4c9f105454
| 38.669421 | 106 | 0.627083 | 4.958678 | false | false | false | false |
FraDeliro/ISaMaterialLogIn
|
Example/Pods/Material/Sources/iOS/Bar.swift
|
1
|
8489
|
/*
* Copyright (C) 2015 - 2016, Daniel Dahan and CosmicMind, Inc. <http://cosmicmind.com>.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
*
* * Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
*
* * Redistributions in binary form must reproduce the above copyright notice,
* this list of conditions and the following disclaimer in the documentation
* and/or other materials provided with the distribution.
*
* * Neither the name of CosmicMind nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
import UIKit
@objc(ContentViewAlignment)
public enum ContentViewAlignment: Int {
case full
case center
}
open class Bar: View {
/// Will layout the view.
open var willLayout: Bool {
return 0 < width && 0 < height && nil != superview
}
open override var intrinsicContentSize: CGSize {
return CGSize(width: width, height: height)
}
/// Should center the contentView.
open var contentViewAlignment = ContentViewAlignment.full {
didSet {
layoutSubviews()
}
}
/// A preset wrapper around contentEdgeInsets.
open var contentEdgeInsetsPreset: EdgeInsetsPreset {
get {
return grid.contentEdgeInsetsPreset
}
set(value) {
grid.contentEdgeInsetsPreset = value
}
}
/// A reference to EdgeInsets.
@IBInspectable
open var contentEdgeInsets: EdgeInsets {
get {
return grid.contentEdgeInsets
}
set(value) {
grid.contentEdgeInsets = value
}
}
/// A preset wrapper around interimSpace.
open var interimSpacePreset = InterimSpacePreset.none {
didSet {
interimSpace = InterimSpacePresetToValue(preset: interimSpacePreset)
}
}
/// A wrapper around grid.interimSpace.
@IBInspectable
open var interimSpace: InterimSpace {
get {
return grid.interimSpace
}
set(value) {
grid.interimSpace = value
}
}
/// Grid cell factor.
@IBInspectable
open var gridFactor: CGFloat = 12 {
didSet {
assert(0 < gridFactor, "[Material Error: gridFactor must be greater than 0.]")
layoutSubviews()
}
}
/// ContentView that holds the any desired subviews.
open let contentView = UIView()
/// Left side UIViews.
open var leftViews: [UIView] {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Right side UIViews.
open var rightViews: [UIView] {
didSet {
for v in oldValue {
v.removeFromSuperview()
}
layoutSubviews()
}
}
/// Center UIViews.
open var centerViews: [UIView] {
get {
return contentView.grid.views
}
set(value) {
contentView.grid.views = value
}
}
/**
An initializer that initializes the object with a NSCoder object.
- Parameter aDecoder: A NSCoder instance.
*/
public required init?(coder aDecoder: NSCoder) {
leftViews = []
rightViews = []
super.init(coder: aDecoder)
}
/**
An initializer that initializes the object with a CGRect object.
If AutoLayout is used, it is better to initilize the instance
using the init() initializer.
- Parameter frame: A CGRect instance.
*/
public override init(frame: CGRect) {
leftViews = []
rightViews = []
super.init(frame: frame)
}
/// Convenience initializer.
public convenience init() {
self.init(frame: .zero)
}
/**
A convenience initializer with parameter settings.
- Parameter leftViews: An Array of UIViews that go on the left side.
- Parameter rightViews: An Array of UIViews that go on the right side.
- Parameter centerViews: An Array of UIViews that go in the center.
*/
public convenience init(leftViews: [UIView]? = nil, rightViews: [UIView]? = nil, centerViews: [UIView]? = nil) {
self.init()
self.leftViews = leftViews ?? []
self.rightViews = rightViews ?? []
self.centerViews = centerViews ?? []
}
open override func layoutSubviews() {
super.layoutSubviews()
guard willLayout else {
return
}
guard !grid.deferred else {
return
}
reload()
}
/// Reloads the view.
open func reload() {
var lc = 0
var rc = 0
grid.begin()
grid.views.removeAll()
for v in leftViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
lc += v.grid.columns
grid.views.append(v)
}
grid.views.append(contentView)
for v in rightViews {
if let b = v as? UIButton {
b.contentEdgeInsets = .zero
b.titleEdgeInsets = .zero
}
v.width = v.intrinsicContentSize.width
v.sizeToFit()
v.grid.columns = Int(ceil(v.width / gridFactor)) + 2
rc += v.grid.columns
grid.views.append(v)
}
contentView.grid.begin()
contentView.grid.offset.columns = 0
var l: CGFloat = 0
var r: CGFloat = 0
if .center == contentViewAlignment {
if leftViews.count < rightViews.count {
r = CGFloat(rightViews.count) * interimSpace
l = r
} else {
l = CGFloat(leftViews.count) * interimSpace
r = l
}
}
let p = width - l - r - contentEdgeInsets.left - contentEdgeInsets.right
let columns = Int(ceil(p / gridFactor))
if .center == contentViewAlignment {
if lc < rc {
contentView.grid.columns = columns - 2 * rc
contentView.grid.offset.columns = rc - lc
} else {
contentView.grid.columns = columns - 2 * lc
rightViews.first?.grid.offset.columns = lc - rc
}
} else {
contentView.grid.columns = columns - lc - rc
}
grid.axis.columns = columns
grid.commit()
contentView.grid.commit()
divider.reload()
}
/**
Prepares the view instance when intialized. When subclassing,
it is recommended to override the prepare method
to initialize property values and other setup operations.
The super.prepare method should always be called immediately
when subclassing.
*/
open override func prepare() {
super.prepare()
heightPreset = .normal
autoresizingMask = .flexibleWidth
interimSpacePreset = .interimSpace3
contentEdgeInsetsPreset = .square1
}
}
|
mit
|
e2b3b6368437134ef400e8dc23b3cd98
| 29.102837 | 116 | 0.579574 | 5.101563 | false | false | false | false |
lincolnge/sparsec
|
sparsec/sparsec/proposition.swift
|
1
|
3845
|
//
// proposition.swift
// sparsec
//
// Created by Mars Liu on 15/3/19.
// Copyright (c) 2015年 Dwarf Artisan. All rights reserved.
//
import Foundation
let letters = NSCharacterSet.letterCharacterSet()
let digits = NSCharacterSet.decimalDigitCharacterSet()
let spaces = NSCharacterSet.whitespaceCharacterSet()
let spacesAndNewlines = NSCharacterSet.whitespaceAndNewlineCharacterSet()
let newlines = NSCharacterSet.newlineCharacterSet()
typealias UChr = UnicodeScalar
typealias UStr = String.UnicodeScalarView
func charSet(title:String, charSet:NSCharacterSet)->Parsec<UChr, UStr>.Parser {
let pred = {(c:UnicodeScalar)-> Bool in
return charSet.longCharacterIsMember(c.value)
}
return {(state:BasicState<UStr>)->(UChr?, ParsecStatus) in
var pre = state.next(pred)
switch pre {
case let .Success(value):
return (value, ParsecStatus.Success)
case .Failed:
return (nil, ParsecStatus.Failed("Except \(title) at \(state.pos) but not match."))
case .Eof:
return (nil, ParsecStatus.Failed("Except \(title) but Eof."))
}
}
}
let digit = charSet("digit", digits)
let letter = charSet("letter", letters)
let space = charSet("space", spaces)
let sol = charSet("space or newline", spacesAndNewlines)
let newline = charSet("newline", newlines)
let unsignedFloat = many(digit) >>= {(n:[UChr?]?)->Parsec<String, UStr>.Parser in
return {(state:BasicState<UStr>)->(String?, ParsecStatus) in
var (re, status) = (char(".") >> many1(digit))(state)
switch status {
case .Success:
return ("\(cs2str(n!)).\(cs2str(re!))", ParsecStatus.Success)
case .Failed:
return (nil, status)
}
}
}
let float = try(unsignedFloat) <|> (char("-") >> {(state: BasicState<UStr>)->(String?, ParsecStatus) in
var (re, status) = unsignedFloat(state)
switch status {
case .Success:
return ("-\(re!)", ParsecStatus.Success)
case .Failed:
return (nil, status)
}
})
func char(c:UChr)->Parsec<UChr, UStr>.Parser {
return one(c)
}
let uint = many1(digit) >>= {(x:[UChr?]?)->Parsec<UStr, UStr>.Parser in
return pack(cs2us(x!))
}
let int = option(try(char("-")), nil) >>= {(x:UChr?)->Parsec<UStr, UStr>.Parser in
return {(state:BasicState<UStr>)->(UStr?, ParsecStatus) in
var (re, status) = uint(state)
switch status {
case .Success:
if x == nil {
return (re, ParsecStatus.Success)
}else{
var s:String=""+String(re!)
return (s.unicodeScalars, ParsecStatus.Success)
}
case .Failed:
return (nil, ParsecStatus.Failed("Except a Unsigned Integer token but failed."))
}
}
}
func text(value:String)->Parsec<String, String.UnicodeScalarView>.Parser {
return {(state: BasicState<String.UnicodeScalarView>)->(String?, ParsecStatus) in
var scalars = value.unicodeScalars
for idx in scalars.startIndex...scalars.endIndex {
var re = state.next()
if re == nil {
return (nil, ParsecStatus.Failed("Except Text \(value) but Eof"))
} else {
var rune = re!
if rune != scalars[idx] {
return (nil, ParsecStatus.Failed("Text[\(idx)]:\(scalars[idx]) not match Data[\(state.pos)]:\(rune)"))
}
}
}
return (value, ParsecStatus.Success)
}
}
func cs2us(cs:[UChr?]) -> UStr {
var re = "".unicodeScalars
var values = unbox(cs)
for c in values {
re.append(c)
}
return re
}
func cs2str(cs:[UChr?]) -> String {
var re = "".unicodeScalars
var values = unbox(cs)
for c in values {
re.append(c)
}
return String(re)
}
|
mit
|
84d57c3a914ccbcc2dc0a8b0bd9d2725
| 30 | 122 | 0.59771 | 3.775049 | false | false | false | false |
eurofurence/ef-app_ios
|
Packages/EurofurenceApplication/Sources/EurofurenceApplication/Application/Components/Message Detail/Component/MessageDetailComponentBuilder.swift
|
1
|
1108
|
import ComponentBase
import EurofurenceModel
public class MessageDetailComponentBuilder {
private let messagesService: PrivateMessagesService
private var markdownRenderer: MarkdownRenderer
private var sceneFactory: MessageDetailSceneFactory
public init(messagesService: PrivateMessagesService) {
self.messagesService = messagesService
self.sceneFactory = StoryboardMessageDetailSceneFactory()
self.markdownRenderer = DefaultDownMarkdownRenderer()
}
@discardableResult
public func with(_ sceneFactory: MessageDetailSceneFactory) -> Self {
self.sceneFactory = sceneFactory
return self
}
@discardableResult
public func with(_ markdownRenderer: MarkdownRenderer) -> Self {
self.markdownRenderer = markdownRenderer
return self
}
public func build() -> MessageDetailComponentFactory {
MessageDetailComponentFactoryImpl(
sceneFactory: sceneFactory,
messagesService: messagesService,
markdownRenderer: markdownRenderer
)
}
}
|
mit
|
6b24389ccfb0da8cd1ccc9f71fdea0ac
| 29.777778 | 73 | 0.705776 | 6.121547 | false | false | false | false |
velvetroom/columbus
|
Source/Model/CreateSearch/MCreateSearch+Completer.swift
|
1
|
1939
|
import MapKit
extension MCreateSearch
{
//MARK: private
private func asyncSearchItem(item:MKLocalSearchCompletion)
{
let searchRequest:MKLocalSearchRequest = MKLocalSearchRequest(completion:item)
let search:MKLocalSearch = MKLocalSearch(request:searchRequest)
search.start
{ [weak self] (response:MKLocalSearchResponse?, error:Error?) in
self?.searchItem(
response:response,
error:error)
}
}
private func searchItem(
response:MKLocalSearchResponse?,
error:Error?)
{
guard
error == nil,
let mapItems:[MKMapItem] = response?.mapItems,
let firstItem:MKMapItem = mapItems.first
else
{
return
}
let coordinate:CLLocationCoordinate2D = firstItem.placemark.coordinate
DispatchQueue.main.async
{ [weak self] in
self?.itemFound(coordinate:coordinate)
}
}
private func itemFound(coordinate:CLLocationCoordinate2D)
{
guard
let controller:CCreateSearch = view?.controller as? CCreateSearch
else
{
return
}
controller.itemFound(coordinate:coordinate)
}
//MARK: internal
func complete(string:String)
{
guard
string.isEmpty
else
{
completer.queryFragment = string
return
}
completer.cancel()
updateItems(items:[])
}
func searchItem(item:MKLocalSearchCompletion)
{
DispatchQueue.global(qos:DispatchQoS.QoSClass.background).async
{ [weak self] in
self?.asyncSearchItem(item:item)
}
}
}
|
mit
|
5b96d4ac04fd00fe5be5afea0baab184
| 21.546512 | 86 | 0.527076 | 5.461972 | false | false | false | false |
RocketChat/Rocket.Chat.iOS
|
Rocket.Chat/External/RCEmojiKit/Views/Reaction/ReactorListViewController.swift
|
1
|
1959
|
//
// ReactorListViewController.swift
// Rocket.Chat
//
// Created by Matheus Cardoso on 2/5/18.
// Copyright © 2018 Rocket.Chat. All rights reserved.
//
import Foundation
extension ReactorListViewController: UserActionSheetPresenter {}
final class ReactorListViewController: UIViewController, Closeable {
override var preferredContentSize: CGSize {
set { }
get {
reactorListView.layoutIfNeeded()
let height = min(reactorListView.reactorTableView.contentSize.height, 400)
let width = CGFloat(300)
return CGSize(width: width, height: height)
}
}
var model: ReactorListViewModel = .emptyState {
didSet {
reactorListView?.model = model
}
}
var reactorListView: ReactorListView! {
didSet {
reactorListView.model = model
}
}
override func loadView() {
super.loadView()
reactorListView = ReactorListView(frame: view.frame)
reactorListView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(reactorListView)
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "|-0-[view]-0-|", options: [], metrics: nil, views: ["view": reactorListView]
)
)
view.addConstraints(
NSLayoutConstraint.constraints(
withVisualFormat: "V:|-0-[view]-0-|", options: [], metrics: nil, views: ["view": reactorListView]
)
)
title = NSLocalizedString("reactorlist.title", tableName: "RCEmojiKit", bundle: Bundle.main, value: "", comment: "")
ThemeManager.addObserver(self)
}
override func viewWillAppear(_ animated: Bool) {
// remove title from back button
if self.navigationController?.topViewController == self {
navigationController?.navigationBar.topItem?.title = ""
}
}
}
|
mit
|
4116f381142f6120e46a5e45a65de44b
| 27.794118 | 124 | 0.622063 | 5.046392 | false | false | false | false |
velvetroom/columbus
|
Source/Model/Plans/MPlans+Active.swift
|
1
|
1023
|
import Foundation
extension MPlans
{
//MARK: private
private func activate(
settings:DSettings,
plan:DPlan)
{
guard
settings.activePlan === plan
else
{
saveActivePlan(
settings:settings,
plan:plan)
return
}
saveActivePlan(
settings:settings,
plan:nil)
}
private func saveActivePlan(
settings:DSettings,
plan:DPlan?)
{
settings.activePlan = plan
database?.save
{ [weak self] in
self?.view?.plansLoaded()
}
}
//MARK: internal
func activate(plan:DPlan)
{
guard
let settings:DSettings = self.settings
else
{
return
}
activate(
settings:settings,
plan:plan)
}
}
|
mit
|
9a6e68253d8742daaca5f29f87a9154f
| 16.338983 | 50 | 0.415445 | 5.52973 | false | false | false | false |
nodekit-io/nodekit-windows
|
src/nodekit/NKElectro/common/NKEProtocol/NKE_ProtocolLocalFile.swift
|
1
|
2623
|
/*
* nodekit.io
*
* Copyright (c) 2016 OffGrid Networks. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import Foundation
class NKE_ProtocolLocalFile: NSURLProtocol {
override class func canInitWithRequest(request: NSURLRequest) -> Bool {
if (request.URL!.host == nil) { return false;}
if ((request.URL!.scheme.caseInsensitiveCompare("internal") == NSComparisonResult.OrderedSame)
|| (request.URL!.host?.caseInsensitiveCompare("internal") == NSComparisonResult.OrderedSame)) {
return true
} else {
return false
}
}
override class func canonicalRequestForRequest(request: NSURLRequest) -> NSURLRequest {
return request
}
override class func requestIsCacheEquivalent(a: NSURLRequest?, toRequest: NSURLRequest?) -> Bool {
return false
}
override func startLoading() {
let request: NSURLRequest = self.request
let client: NSURLProtocolClient! = self.client
if (request.URL!.absoluteString == "internal://close") || (request.URL!.absoluteString == "http://internal/close") {
exit(0)
}
log("+URL: \(request.URL!.absoluteString)")
let urlDecode = NKE_ProtocolFileDecode(url: request.URL!)
if (urlDecode.exists()) {
let data: NSData! = NSData(contentsOfFile: urlDecode.resourcePath! as String)
let response: NSURLResponse = NSURLResponse(URL: request.URL!, MIMEType: urlDecode.mimeType as String?, expectedContentLength: data.length, textEncodingName: urlDecode.textEncoding as String?)
client.URLProtocol(self, didReceiveResponse: response, cacheStoragePolicy: NSURLCacheStoragePolicy.AllowedInMemoryOnly)
client.URLProtocol(self, didLoadData: data)
client.URLProtocolDidFinishLoading(self)
} else {
log("!Missing File \(request.URL!)")
client.URLProtocol(self, didFailWithError: NSError(domain: NSURLErrorDomain, code: NSURLErrorFileDoesNotExist, userInfo: nil))
}
}
override func stopLoading() {
}
}
|
apache-2.0
|
ded6d235be4f2e1136c0fd2c3ee82a2b
| 33.973333 | 204 | 0.685093 | 4.812844 | false | false | false | false |
material-components/material-components-ios
|
components/AppBar/tests/unit/AppBarDelegateAccessibilityPerformEscapeTests.swift
|
2
|
2430
|
// Copyright 2020-present the Material Components for iOS authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
import XCTest
import MaterialComponents.MaterialAppBar
private class FakeDelegate: NSObject, MDCAppBarViewControllerAccessibilityPerformEscapeDelegate {
var accessibilityPerformEscapeResult = false
var didInvokeAppBarViewControllerAccessibilityPerformEscape = false
func appBarViewControllerAccessibilityPerformEscape(
_ appBarViewController: MDCAppBarViewController
) -> Bool {
didInvokeAppBarViewControllerAccessibilityPerformEscape = true
return accessibilityPerformEscapeResult
}
}
class AppBarDelegateAccessibilityPerformEscapeTests: XCTestCase {
var appBarViewController: MDCAppBarViewController!
override func setUp() {
super.setUp()
appBarViewController = MDCAppBarViewController()
}
override func tearDown() {
appBarViewController = nil
super.tearDown()
}
func testDefaults() {
XCTAssertNil(appBarViewController.accessibilityPerformEscapeDelegate)
}
func testInvokesDelegateAndReturnsTrueValue() {
// Given
let delegate = FakeDelegate()
delegate.accessibilityPerformEscapeResult = true
appBarViewController.accessibilityPerformEscapeDelegate = delegate
// When
let result = appBarViewController.accessibilityPerformEscape()
// Then
XCTAssertTrue(delegate.didInvokeAppBarViewControllerAccessibilityPerformEscape)
XCTAssertTrue(result)
}
func testInvokesDelegateAndReturnsFalseValue() {
// Given
let delegate = FakeDelegate()
delegate.accessibilityPerformEscapeResult = false
appBarViewController.accessibilityPerformEscapeDelegate = delegate
// When
let result = appBarViewController.accessibilityPerformEscape()
// Then
XCTAssertTrue(delegate.didInvokeAppBarViewControllerAccessibilityPerformEscape)
XCTAssertFalse(result)
}
}
|
apache-2.0
|
8fdedafd0ebce93c9c643236113ab023
| 30.558442 | 97 | 0.785185 | 5.4 | false | true | false | false |
collegboi/DIT-Timetable-iOS
|
Classes Left/TodayViewController.swift
|
1
|
4518
|
//
// TodayViewController.swift
// Classes Left
//
// Created by Timothy Barnard on 20/09/2017.
// Copyright © 2017 Timothy Barnard. All rights reserved.
//
import UIKit
import NotificationCenter
class TodayClassesLeftViewController: UIViewController, NCWidgetProviding {
@IBOutlet weak var tableView: UITableView!
var todayClasses = [Timetable]()
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.delegate = self
self.tableView.dataSource = self
self.tableView.tableFooterView = UIView()
self.extensionContext?.widgetLargestAvailableDisplayMode = NCWidgetDisplayMode.expanded
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
// Perform any setup necessary in order to update the view.
// If an error is encountered, use NCUpdateResult.Failed
// If there's no update required, use NCUpdateResult.NoData
// If there's an update, use NCUpdateResult.NewData
loadData()
completionHandler(NCUpdateResult.newData)
}
func widgetMarginInsets(forProposedMarginInsets defaultMarginInsets: UIEdgeInsets) -> (UIEdgeInsets) {
return UIEdgeInsets.zero
}
func widgetActiveDisplayModeDidChange(_ activeDisplayMode: NCWidgetDisplayMode, withMaximumSize maxSize: CGSize) {
if activeDisplayMode == .expanded {
preferredContentSize = CGSize(width: 0, height: 280)
} else {
preferredContentSize = maxSize
}
}
// MARK: - Loading of data
func loadData() {
DispatchQueue.global(qos: DispatchQoS.QoSClass.default).async {
let database = Database()
let today = Date()
let day = today.weekday()
let indexVal = (day+5) % 7
self.todayClasses = database.getDayTimetableAfterNow(dayNo: indexVal)
DispatchQueue.main.async {
self.tableView.reloadData()
}
}
}
func createEmptyMessage(message:String) {
let messageLabel = UILabel(frame: CGRect(x: 0,y: 0,width: self.view.bounds.size.width, height: self.view.bounds.size.height))
messageLabel.text = message
messageLabel.textColor = UIColor.black
messageLabel.numberOfLines = 0;
messageLabel.textAlignment = .center;
messageLabel.font = UIFont(name: "AvenirNext", size: 15)
messageLabel.sizeToFit()
self.tableView.backgroundView = messageLabel;
self.tableView.separatorStyle = .none;
}
}
// MARK: - TableView Data Source
extension TodayClassesLeftViewController : UITableViewDelegate, UITableViewDataSource {
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let todayClassCount = self.todayClasses.count
if todayClassCount == 0 {
let message = "You don't have any classes left. Have a nice day 😀"
self.createEmptyMessage(message: message)
} else {
self.tableView.backgroundView = nil
self.tableView.separatorStyle = .singleLine
}
return todayClassCount
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "todayCell", for: indexPath) as! TodayCellTableViewCell
let timetable = todayClasses[indexPath.row]
/*cell.textLabel?.text = timetable.name
cell.textLabel?.textColor = .black
cell.textLabel?.font.withSize(17)
cell.detailTextLabel?.text = timetable.room + " - " + timetable.timeStart
cell.detailTextLabel?.textColor = .blue
cell.detailTextLabel?.font.withSize(15)*/
cell.setupCell(timetable: timetable)
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
if let url = URL(string: "ditTimetable://") {
self.extensionContext?.open(url, completionHandler: {success in print("called url complete handler: \(success)")})
}
}
}
|
mit
|
de4dce79eee4383f4fc1a32f7d0fef46
| 33.992248 | 133 | 0.64156 | 5.279532 | false | false | false | false |
kaojohnny/CoreStore
|
CoreStoreTests/MigrationChainTests.swift
|
1
|
5313
|
//
// MigrationChainTests.swift
// CoreStore
//
// Copyright © 2016 John Rommel Estropia
//
// 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 XCTest
@testable
import CoreStore
// MARK: - MigrationChainTests
final class MigrationChainTests: XCTestCase {
@objc
dynamic func test_ThatNilMigrationChains_HaveNoVersions() {
let chain: MigrationChain = nil
XCTAssertTrue(chain.valid)
XCTAssertTrue(chain.empty)
XCTAssertFalse(chain.contains("version1"))
XCTAssertNil(chain.nextVersionFrom("version1"))
}
@objc
dynamic func test_ThatStringMigrationChains_HaveOneVersion() {
let chain: MigrationChain = "version1"
XCTAssertTrue(chain.valid)
XCTAssertTrue(chain.empty)
XCTAssertTrue(chain.contains("version1"))
XCTAssertFalse(chain.contains("version2"))
XCTAssertNil(chain.nextVersionFrom("version1"))
XCTAssertNil(chain.nextVersionFrom("version2"))
}
@objc
dynamic func test_ThatArrayMigrationChains_HaveLinearVersions() {
let chain: MigrationChain = ["version1", "version2", "version3", "version4"]
XCTAssertTrue(chain.valid)
XCTAssertFalse(chain.empty)
XCTAssertTrue(chain.contains("version1"))
XCTAssertTrue(chain.contains("version2"))
XCTAssertTrue(chain.contains("version3"))
XCTAssertTrue(chain.contains("version4"))
XCTAssertFalse(chain.contains("version5"))
XCTAssertEqual(chain.nextVersionFrom("version1"), "version2")
XCTAssertEqual(chain.nextVersionFrom("version2"), "version3")
XCTAssertEqual(chain.nextVersionFrom("version3"), "version4")
XCTAssertNil(chain.nextVersionFrom("version4"))
XCTAssertNil(chain.nextVersionFrom("version5"))
}
@objc
dynamic func test_ThatDictionaryMigrationChains_HaveTreeVersions() {
let chain: MigrationChain = [
"version1": "version4",
"version2": "version3",
"version3": "version4"
]
XCTAssertTrue(chain.valid)
XCTAssertFalse(chain.empty)
XCTAssertTrue(chain.contains("version1"))
XCTAssertTrue(chain.contains("version2"))
XCTAssertTrue(chain.contains("version3"))
XCTAssertTrue(chain.contains("version4"))
XCTAssertFalse(chain.contains("version5"))
XCTAssertEqual(chain.nextVersionFrom("version1"), "version4")
XCTAssertEqual(chain.nextVersionFrom("version2"), "version3")
XCTAssertEqual(chain.nextVersionFrom("version3"), "version4")
XCTAssertNil(chain.nextVersionFrom("version4"))
XCTAssertNil(chain.nextVersionFrom("version5"))
// The cases below will trigger assertion failures internally
// let linearLoopChain: MigrationChain = ["version1", "version2", "version1", "version3", "version4"]
// XCTAssertFalse(linearLoopChain.valid, "linearLoopChain.valid")
//
// let treeAmbiguousChain: MigrationChain = [
// "version1": "version4",
// "version2": "version3",
// "version1": "version2",
// "version3": "version4"
// ]
// XCTAssertFalse(treeAmbiguousChain.valid, "treeAmbiguousChain.valid")
}
@objc
dynamic func test_ThatMigrationChains_AreEquatable() {
do {
let chain1: MigrationChain = nil
let chain2: MigrationChain = []
let chain3: MigrationChain = [:]
XCTAssertEqual(chain1, chain2)
XCTAssertEqual(chain2, chain3)
XCTAssertEqual(chain3, chain1)
}
do {
let chain1: MigrationChain = "version1"
let chain2: MigrationChain = ["version1"]
XCTAssertEqual(chain1, chain2)
}
do {
let chain1: MigrationChain = ["version1", "version2", "version3", "version4"]
let chain2: MigrationChain = [
"version1": "version2",
"version2": "version3",
"version3": "version4"
]
XCTAssertEqual(chain1, chain2)
}
}
}
|
mit
|
a90996b572d2565d8e8bf60b0d20a91c
| 35.136054 | 108 | 0.639684 | 4.643357 | false | true | false | false |
stanislavfeldman/Eventer
|
Action.swift
|
1
|
1568
|
// Created by Stanislav Feldman on 27/07/15.
// Copyright (c) 2015 Stanislav Feldman. All rights reserved.
/**
Action holder. Holds action with or without info parameter.
Executes action immediate by default or in background or main thread.
*/
enum Action {
typealias SimpleAction = () -> Void
typealias InfoAction = (info: AnyObject?) -> Void
typealias NotificationAction = (notification: NSNotification!) -> Void
case Simple(SimpleAction)
case Info(InfoAction)
enum Execution {
case Immediate
case Background
case Main
}
func execute(execution:Execution = .Immediate) {
execute(nil, execution: execution)
}
func execute(info: AnyObject?, execution:Execution = .Immediate) {
switch self {
case .Simple(let action):
switch execution {
case .Background:
dispatch.async.bg {
action()
}
case .Main:
dispatch.async.main {
action()
}
default:
action()
}
case .Info(let action):
switch execution {
case .Background:
dispatch.async.bg {
action(info: info)
}
case .Main:
dispatch.async.main {
action(info: info)
}
default:
action(info: info)
}
default:
break
}
}
}
|
bsd-2-clause
|
8c83feab6ca73d54d65fc72cf1429bb9
| 26.034483 | 74 | 0.503827 | 5.174917 | false | false | false | false |
kello711/HackingWithSwift
|
Project37/Project37/ViewController.swift
|
1
|
6114
|
//
// ViewController.swift
// Project37
//
// Created by Hudzilla on 06/01/2016.
// Copyright © 2016 Paul Hudson. All rights reserved.
//
import AVFoundation
import GameplayKit
import UIKit
import WatchConnectivity
class ViewController: UIViewController, WCSessionDelegate {
@IBOutlet weak var cardContainer: UIView!
@IBOutlet weak var gradientView: UIView!
var allCards = [CardViewController]()
var music: AVAudioPlayer!
var lastMessage: CFAbsoluteTime = 0
override func viewDidLoad() {
super.viewDidLoad()
view.backgroundColor = UIColor.redColor()
UIView.animateWithDuration(20, delay: 0, options: [.AllowUserInteraction, .Autoreverse, .Repeat], animations: {
self.view.backgroundColor = UIColor.blueColor()
}, completion: nil)
createParticles()
loadCards()
playMusic()
if (WCSession.isSupported()) {
let session = WCSession.defaultSession()
session.delegate = self
session.activateSession()
}
}
override func viewDidAppear(animated: Bool) {
super.viewDidAppear(animated)
let instructions = "Please ensure your Apple Watch is configured correctly. On your iPhone, launch Apple's 'Watch' configuration app then choose General > Wake Screen. On that screen, please disable Wake Screen On Wrist Raise, then select Wake For 70 Seconds. On your Apple Watch, please swipe up on your watch face and enable Silent Mode. You're done!"
let ac = UIAlertController(title: "Adjust your settings", message: instructions, preferredStyle: .Alert)
ac.addAction(UIAlertAction(title: "I'm Ready", style: .Default, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func loadCards() {
for card in allCards {
card.view.removeFromSuperview()
card.removeFromParentViewController()
}
allCards.removeAll(keepCapacity: true)
view.userInteractionEnabled = true
// create an array of card positions
let positions = [
CGPoint(x: 75, y: 85),
CGPoint(x: 185, y: 85),
CGPoint(x: 295, y: 85),
CGPoint(x: 405, y: 85),
CGPoint(x: 75, y: 235),
CGPoint(x: 185, y: 235),
CGPoint(x: 295, y: 235),
CGPoint(x: 405, y: 235)
]
// load and unwrap our Zener card images
let circle = UIImage(named: "cardCircle")!
let cross = UIImage(named: "cardCross")!
let lines = UIImage(named: "cardLines")!
let square = UIImage(named: "cardSquare")!
let star = UIImage(named: "cardStar")!
// create an array of the images, one for each card, then shuffle it
var images = [circle, circle, cross, cross, lines, lines, square, star]
images = GKRandomSource.sharedRandom().arrayByShufflingObjectsInArray(images) as! [UIImage]
for (index, position) in positions.enumerate() {
// loop over each card position and create a new card view controller
let card = CardViewController()
card.delegate = self
// use view controller containment and also add the card's view to our cardContainer view
addChildViewController(card)
cardContainer.addSubview(card.view)
card.didMoveToParentViewController(self)
// position the card appropriately, then give it an image from our array
card.view.center = position
card.front.image = images[index]
// if we just gave the new card the star image, mark this as the correct answer
if card.front.image == star {
card.isCorrect = true
}
// add the new card view controller to our array for easier tracking
allCards.append(card)
}
}
func cardTapped(tapped: CardViewController) {
guard view.userInteractionEnabled == true else { return }
view.userInteractionEnabled = false
for card in allCards {
if card == tapped {
card.wasTapped()
card.performSelector(#selector(card.wasntTapped), withObject: nil, afterDelay: 1)
} else {
card.wasntTapped()
}
}
performSelector(#selector(loadCards), withObject: nil, afterDelay: 2)
}
func createParticles() {
let particleEmitter = CAEmitterLayer()
particleEmitter.emitterPosition = CGPoint(x: view.frame.width / 2.0, y: -50)
particleEmitter.emitterShape = kCAEmitterLayerLine
particleEmitter.emitterSize = CGSize(width: view.frame.width, height: 1)
particleEmitter.renderMode = kCAEmitterLayerAdditive
let cell = CAEmitterCell()
cell.birthRate = 2
cell.lifetime = 5.0
cell.velocity = 100
cell.velocityRange = 50
cell.emissionLongitude = CGFloat(M_PI)
cell.spinRange = 5
cell.scale = 0.5
cell.scaleRange = 0.25
cell.color = UIColor(white: 1, alpha: 0.1).CGColor
cell.alphaSpeed = -0.025
cell.contents = UIImage(named: "particle")?.CGImage
particleEmitter.emitterCells = [cell]
gradientView.layer.addSublayer(particleEmitter)
}
func playMusic() {
if let musicURL = NSBundle.mainBundle().URLForResource("PhantomFromSpace", withExtension: "mp3") {
if let audioPlayer = try? AVAudioPlayer(contentsOfURL: musicURL) {
music = audioPlayer
music.numberOfLoops = -1
music.play()
}
}
}
override func touchesMoved(touches: Set<UITouch>, withEvent event: UIEvent?) {
super.touchesMoved(touches, withEvent: event)
if let touch = touches.first {
let location = touch.locationInView(cardContainer)
for card in allCards {
if card.view.frame.contains(location) {
if view.traitCollection.forceTouchCapability == .Available {
if touch.force == touch.maximumPossibleForce {
card.front.image = UIImage(named: "cardStar")
card.isCorrect = true
}
}
if card.isCorrect {
sendWatchMessage()
}
}
}
}
}
func sendWatchMessage() {
let currentTime = CFAbsoluteTimeGetCurrent()
// if less than half a second has passed, bail out
if lastMessage + 0.5 > currentTime {
return
}
// send a message to the watch if it's reachable
if (WCSession.defaultSession().reachable) {
let message = ["Message": "Hello"]
WCSession.defaultSession().sendMessage(message, replyHandler: nil, errorHandler: nil)
}
// update our rate limiting property
lastMessage = CFAbsoluteTimeGetCurrent()
}
}
|
unlicense
|
049824f32e1167b1b2e56fd296e19fb8
| 28.674757 | 355 | 0.715524 | 3.832602 | false | false | false | false |
galalmounir/WWDC-2017-Entry
|
So You Want To Be A Computer Scientist?.playground/Pages/What is Binary.xcplaygroundpage/Sources/Binary.swift
|
1
|
2181
|
import Foundation
import SpriteKit
import PlaygroundSupport
var number: Int = 0
let frame = CGRect(x: 0, y: 250, width: 500, height: 300)
let view = SKView(frame: frame)
let scene = MainScene(size: frame.size)
let decimal = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
let binary = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
func updateView(){
decimal.text = String(number)
binary.text = String(number, radix: 2)
scene.updateView()
}
func add(){
number = number + 1
updateView()
}
func sub(){
number = number - 1
updateView()
}
public func loadPage(){
var x = Button(text: "+", pos: CGPoint(x: frame.midX - 20, y: 30), call: add)
x.setSize(size: CGSize(width: 30, height: 30))
scene.addButton(button: x)
x = Button(text: "-", pos: CGPoint(x: frame.midX + 20, y: 30), call: sub)
x.setSize(size: CGSize(width: 30, height: 30))
scene.addButton(button: x)
var y = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
y.text = "Decimal"
y.fontSize = 30
y.fontColor = #colorLiteral(red: 0.2196078449, green: 0.007843137719, blue: 0.8549019694, alpha: 1)
y.position = CGPoint(x: frame.midX/2, y:100)
scene.addToView(node: y)
y = SKLabelNode(fontNamed: "CourierNewPS-BoldMT")
y.text = "Binary"
y.fontSize = 30
y.fontColor = #colorLiteral(red: 0.3411764801, green: 0.6235294342, blue: 0.1686274558, alpha: 1)
y.position = CGPoint(x: frame.midX + frame.midX/2, y: 100)
scene.addToView(node: y)
decimal.text = String(number)
decimal.fontSize = 30
decimal.fontColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
decimal.position = CGPoint(x: frame.midX/2, y: 70)
scene.addToView(node: decimal)
binary.text = String(number, radix: 2)
binary.fontSize = 30
binary.fontColor = #colorLiteral(red: 0, green: 0, blue: 0, alpha: 1)
binary.position = CGPoint(x: frame.midX/2 + frame.midX, y: 70)
scene.addToView(node: binary)
scene.scaleMode = .aspectFit
scene.backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1)
view.presentScene(scene)
PlaygroundPage.current.liveView = view
}
|
mit
|
c3d7b8b9b54afe3a9e13b103f784e3db
| 30.157143 | 103 | 0.655663 | 3.324695 | false | false | false | false |
niunaruto/DeDaoAppSwift
|
testSwift/Pods/RxSwift/RxSwift/Observables/Zip+Collection.swift
|
20
|
6651
|
//
// Zip+Collection.swift
// RxSwift
//
// Created by Krunoslav Zaher on 8/30/15.
// Copyright © 2015 Krunoslav Zaher. All rights reserved.
//
extension ObservableType {
/**
Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- parameter resultSelector: Function to invoke for each series of elements at corresponding indexes in the sources.
- returns: An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
public static func zip<Collection: Swift.Collection>(_ collection: Collection, resultSelector: @escaping ([Collection.Element.Element]) throws -> Element) -> Observable<Element>
where Collection.Element: ObservableType {
return ZipCollectionType(sources: collection, resultSelector: resultSelector)
}
/**
Merges the specified observable sequences into one observable sequence whenever all of the observable sequences have produced an element at a corresponding index.
- seealso: [zip operator on reactivex.io](http://reactivex.io/documentation/operators/zip.html)
- returns: An observable sequence containing the result of combining elements of the sources.
*/
public static func zip<Collection: Swift.Collection>(_ collection: Collection) -> Observable<[Element]>
where Collection.Element: ObservableType, Collection.Element.Element == Element {
return ZipCollectionType(sources: collection, resultSelector: { $0 })
}
}
final private class ZipCollectionTypeSink<Collection: Swift.Collection, Observer: ObserverType>
: Sink<Observer> where Collection.Element: ObservableConvertibleType {
typealias Result = Observer.Element
typealias Parent = ZipCollectionType<Collection, Result>
typealias SourceElement = Collection.Element.Element
private let _parent: Parent
private let _lock = RecursiveLock()
// state
private var _numberOfValues = 0
private var _values: [Queue<SourceElement>]
private var _isDone: [Bool]
private var _numberOfDone = 0
private var _subscriptions: [SingleAssignmentDisposable]
init(parent: Parent, observer: Observer, cancel: Cancelable) {
self._parent = parent
self._values = [Queue<SourceElement>](repeating: Queue(capacity: 4), count: parent.count)
self._isDone = [Bool](repeating: false, count: parent.count)
self._subscriptions = [SingleAssignmentDisposable]()
self._subscriptions.reserveCapacity(parent.count)
for _ in 0 ..< parent.count {
self._subscriptions.append(SingleAssignmentDisposable())
}
super.init(observer: observer, cancel: cancel)
}
func on(_ event: Event<SourceElement>, atIndex: Int) {
self._lock.lock(); defer { self._lock.unlock() } // {
switch event {
case .next(let element):
self._values[atIndex].enqueue(element)
if self._values[atIndex].count == 1 {
self._numberOfValues += 1
}
if self._numberOfValues < self._parent.count {
if self._numberOfDone == self._parent.count - 1 {
self.forwardOn(.completed)
self.dispose()
}
return
}
do {
var arguments = [SourceElement]()
arguments.reserveCapacity(self._parent.count)
// recalculate number of values
self._numberOfValues = 0
for i in 0 ..< self._values.count {
arguments.append(self._values[i].dequeue()!)
if !self._values[i].isEmpty {
self._numberOfValues += 1
}
}
let result = try self._parent.resultSelector(arguments)
self.forwardOn(.next(result))
}
catch let error {
self.forwardOn(.error(error))
self.dispose()
}
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
if self._isDone[atIndex] {
return
}
self._isDone[atIndex] = true
self._numberOfDone += 1
if self._numberOfDone == self._parent.count {
self.forwardOn(.completed)
self.dispose()
}
else {
self._subscriptions[atIndex].dispose()
}
}
// }
}
func run() -> Disposable {
var j = 0
for i in self._parent.sources {
let index = j
let source = i.asObservable()
let disposable = source.subscribe(AnyObserver { event in
self.on(event, atIndex: index)
})
self._subscriptions[j].setDisposable(disposable)
j += 1
}
if self._parent.sources.isEmpty {
self.forwardOn(.completed)
}
return Disposables.create(_subscriptions)
}
}
final private class ZipCollectionType<Collection: Swift.Collection, Result>: Producer<Result> where Collection.Element: ObservableConvertibleType {
typealias ResultSelector = ([Collection.Element.Element]) throws -> Result
let sources: Collection
let resultSelector: ResultSelector
let count: Int
init(sources: Collection, resultSelector: @escaping ResultSelector) {
self.sources = sources
self.resultSelector = resultSelector
self.count = self.sources.count
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Result {
let sink = ZipCollectionTypeSink(parent: self, observer: observer, cancel: cancel)
let subscription = sink.run()
return (sink: sink, subscription: subscription)
}
}
|
mit
|
f15e7ba9b0c84a5898008a373aa34a0d
| 38.349112 | 198 | 0.583759 | 5.495868 | false | false | false | false |
mrdepth/EVEUniverse
|
Neocom/Neocom/Character/Skills/OptimalAttributes.swift
|
2
|
3130
|
//
// OptimalAttributes.swift
// Neocom
//
// Created by Artem Shimanski on 2/5/20.
// Copyright © 2020 Artem Shimanski. All rights reserved.
//
import SwiftUI
import Expressible
struct OptimalAttributes: View {
var pilot: Pilot
var trainingQueue: TrainingQueue
private static let rows = [(Text("Intelligence", comment: ""), Image("intelligence"), \Pilot.Attributes.intelligence),
(Text("Memory", comment: ""), Image("memory"), \Pilot.Attributes.memory),
(Text("Perception", comment: ""), Image("perception"), \Pilot.Attributes.perception),
(Text("Willpower", comment: ""), Image("willpower"), \Pilot.Attributes.willpower),
(Text("Charisma", comment: ""), Image("charisma"), \Pilot.Attributes.charisma)]
private func section(for attributes: Pilot.Attributes) -> some View {
ForEach(0..<5) { i in
HStack {
Icon(Self.rows[i].1)
VStack(alignment: .leading) {
Self.rows[i].0
Text("\(attributes[keyPath: Self.rows[i].2] - self.pilot.augmentations[keyPath: Self.rows[i].2]) + \(self.pilot.augmentations[keyPath: Self.rows[i].2])").modifier(SecondaryLabelModifier())
}
}
}
}
var body: some View {
let optimal = Pilot.Attributes(optimalFor: trainingQueue) + pilot.augmentations
let trainingTime = trainingQueue.trainingTime()
let optimalTrainingTime = trainingQueue.trainingTime(with: optimal)
let dt = trainingTime - optimalTrainingTime
return List {
Section(header: Text("OPTIMAL: \(TimeIntervalFormatter.localizedString(from: optimalTrainingTime, precision: .seconds).uppercased())"),
footer: (dt > 0 ? Text("\(TimeIntervalFormatter.localizedString(from: dt, precision: .seconds)) better.\n") : Text("")) + Text("Based on current training queue and skill plan.")) {
section(for: optimal)
}
Section(header: Text("CURRENT: \(TimeIntervalFormatter.localizedString(from: trainingTime, precision: .seconds).uppercased())")) {
section(for: pilot.attributes)
}
}.listStyle(GroupedListStyle()).navigationBarTitle(Text("Attributes"))
}
}
#if DEBUG
struct OptimalAttributes_Previews: PreviewProvider {
static var previews: some View {
var pilot = Pilot.empty
pilot.augmentations = Pilot.Attributes(intelligence: 4, memory: 4, perception: 4, willpower: 4, charisma: 4)
pilot.attributes += pilot.augmentations
let trainingQueue = TrainingQueue(pilot: pilot)
let skill = try! Storage.testStorage.persistentContainer.viewContext
.from(SDEInvType.self)
.filter(/\SDEInvType.group?.category?.categoryID == SDECategoryID.skill.rawValue)
.first()!
trainingQueue.add(skill, level: 5)
return NavigationView {
OptimalAttributes(pilot: pilot, trainingQueue: trainingQueue)
.modifier(ServicesViewModifier.testModifier())
}
}
}
#endif
|
lgpl-2.1
|
95c13904eee25fbc4396bd433cd91a7a
| 44.347826 | 208 | 0.629594 | 4.49569 | false | false | false | false |
4taras4/totp-auth
|
TOTP/ViperModules/MainList/Module/View/MainListViewController.swift
|
1
|
3104
|
//
// MainListMainListViewController.swift
// TOTP
//
// Created by Tarik on 10/10/2020.
// Copyright © 2020 Taras Markevych. All rights reserved.
//
import UIKit
import Firebase
import GoogleMobileAds
class MainListViewController: UIViewController {
// MARK: -
// MARK: Properties
@IBOutlet weak var heightFolderConstrain: NSLayoutConstraint!
var output: MainListViewOutput!
@IBAction func addAction(_ sender: Any) {
output.addItemButtonPressed()
}
@IBAction func settingsAction(_ sender: Any) {
output.settingsButtonPressed()
}
@IBAction func favouriteAction(_ sender: Any) {
output.favItemButtonPressed()
}
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var foldersCollectionView: UICollectionView!
// MARK: -
// MARK: Life cycle
var bannerView: GADBannerView!
override func viewDidLoad() {
super.viewDidLoad()
output.viewIsReady()
setupViewElements()
setupCollectionView()
}
func setupViewElements() {
tableView.delegate = output
tableView.dataSource = output
bannerView = GADBannerView(adSize: kGADAdSizeSmartBannerPortrait)
addBannerViewToView(bannerView)
bannerView.adUnitID = Constants.adds.bannerId
bannerView.rootViewController = self
bannerView.delegate = self
}
func setupCollectionView() {
let folderCell = UINib(nibName: "FolderItemCollectionViewCell", bundle: nil)
foldersCollectionView.register(folderCell, forCellWithReuseIdentifier: "FolderItemCollectionViewCell")
foldersCollectionView.delegate = output
foldersCollectionView.dataSource = output
let collectionFlow = UICollectionViewFlowLayout()
collectionFlow.scrollDirection = .horizontal
collectionFlow.estimatedItemSize = CGSize(width: 10, height: 10)
collectionFlow.sectionInset = UIEdgeInsets(top: 0.0, left: 15.0, bottom: 0.0, right: 15.0)
foldersCollectionView.collectionViewLayout = collectionFlow
foldersCollectionView.contentInsetAdjustmentBehavior = .never
}
override func viewWillAppear(_ animated: Bool) {
output.refreshData()
output.reloadFolders()
bannerView.load(GADRequest())
}
}
// MARK: -
// MARK: MainListViewInput
extension MainListViewController: MainListViewInput {
func changeCollectionView(isHidden: Bool) {
heightFolderConstrain.constant = isHidden ? 0 : 60
foldersCollectionView.isHidden = isHidden
}
func reloadTable() {
tableView.reloadData()
}
func setupInitialState() {
}
func reloadFoldersCollectionView() {
foldersCollectionView.reloadData()
}
func changeIsEdit() {
tableView.setEditing(!tableView.isEditing, animated: true)
}
}
extension MainListViewController: NibIdentifiable {
static var nibNameIdentifier: String {
return "Main"
}
static var controllerIdentifier: String {
return "MainListViewController"
}
}
|
mit
|
8b3023dcdf37c6ed5cb23f1ddcffb79e
| 27.209091 | 110 | 0.684499 | 5.145937 | false | false | false | false |
nguyenantinhbk77/practice-swift
|
Multitasking/Handling Location Changes in Background/Handling Location Changes in Background/AppDelegate.swift
|
2
|
1902
|
//
// AppDelegate.swift
// Handling Location Changes in Background
//
// Created by Domenico Solazzo on 14/05/15.
// License MIT
//
import UIKit
import CoreLocation
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
var window: UIWindow?
var locationManager: CLLocationManager! = nil
var isExecutingInBackground = false
func application(application: UIApplication,
didFinishLaunchingWithOptions
launchOptions: [NSObject : AnyObject]?) -> Bool {
locationManager = CLLocationManager()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.startUpdatingLocation()
return true
}
func locationManager(manager: CLLocationManager!,
didUpdateToLocation newLocation: CLLocation!,
fromLocation oldLocation: CLLocation!){
if isExecutingInBackground{
/* We are in the background. Do not do any heavy processing */
println("The app is in background")
} else {
/* We are in the foreground. Do any processing that you wish */
println("The app is in foreground")
}
}
func applicationDidEnterBackground(application: UIApplication) {
isExecutingInBackground = true
/* Reduce the accuracy to ease the strain on
iOS while we are in the background */
locationManager.desiredAccuracy = kCLLocationAccuracyHundredMeters
}
func applicationWillEnterForeground(application: UIApplication) {
isExecutingInBackground = false
/* Now that our app is in the foreground again, let's increase the location
detection accuracy */
locationManager.desiredAccuracy = kCLLocationAccuracyBest
}
}
|
mit
|
3b366bd4abb81cb2b8fec0a0679e304b
| 32.368421 | 83 | 0.667718 | 6.40404 | false | false | false | false |
NemProject/NEMiOSApp
|
NEMWalletTests/AccountTests.swift
|
1
|
7459
|
//
// AccountTests.swift
//
// This file is covered by the LICENSE file in the root of this project.
// Copyright (c) 2017 NEM
//
import Quick
import Nimble
@testable import NEMWallet
final class AccountTests: QuickSpec {
override func spec() {
describe("account creation") {
context("when generating a new account") {
var accounts: [Account]!
var generatedAccount: Account!
var generatedAccountIndex: Array<Any>.Index!
beforeSuite {
waitUntil { done in
AccountManager.sharedInstance.create(account: "Newly generated account", completion: { (result, createdAccount) in
accounts = AccountManager.sharedInstance.accounts()
generatedAccount = createdAccount!
generatedAccountIndex = accounts.index(of: createdAccount!)!
done()
})
}
}
it("saves the new account") {
expect(accounts).to(contain(generatedAccount))
}
it("sets the right title") {
expect(accounts[generatedAccountIndex].title).to(equal("Newly generated account"))
}
it("generates a valid account address") {
let networkPrefix = Constants.activeNetwork == Constants.testNetwork ? "T" : "N"
expect(accounts[generatedAccountIndex].address).to(beginWith(networkPrefix))
expect(accounts[generatedAccountIndex].address.characters.count).to(equal(40))
}
it("generates a valid public and private key") {
/// A valid public key implies that the private key is also valid.
expect(AccountManager.sharedInstance.validateKey(accounts[generatedAccountIndex].publicKey)).to(beTruthy())
}
it("positions the account correctly") {
let maxPosition = accounts.max { a, b in Int(a.position) < Int(b.position) }
expect(accounts[generatedAccountIndex].position).to(equal(maxPosition!.position))
}
}
context("when importing an existing account") {
var accounts: [Account]!
var importedAccount: Account!
var importedAccountIndex: Array<Any>.Index!
beforeSuite {
waitUntil { done in
AccountManager.sharedInstance.create(account: "Newly imported account", withPrivateKey: "4846c7752fe1f4ce151224d2ca9b9d38411631cea1a3a87169b35e9058bc729a", completion: { (result, createdAccount) in
accounts = AccountManager.sharedInstance.accounts()
importedAccount = createdAccount!
importedAccountIndex = accounts.index(of: createdAccount!)!
done()
})
}
}
it("saves the existing account") {
expect(accounts).to(contain(importedAccount))
}
it("sets the right title") {
expect(accounts[importedAccountIndex].title).to(equal("Newly imported account"))
}
it("generates the valid account address") {
let accountAddress = Constants.activeNetwork == Constants.testNetwork ? "TB2DA2KFAM4GE2JU4XIPRGO72KBRMJUYS7CUXGLD" : "NB2DA2KFAM4GE2JU4XIPRGO72KBRMJUYS7LHNEUB"
expect(accounts[importedAccountIndex].address).to(equal(accountAddress))
}
it("generates the valid public key") {
expect(accounts[importedAccountIndex].publicKey).to(equal("4e312ef765e2916e4012a5290ae24b3806bdcbffda9560250749789c7bd35b50"))
}
it("positions the account correctly") {
let maxPosition = accounts.max { a, b in Int(a.position) < Int(b.position) }
expect(accounts[importedAccountIndex].position).to(equal(maxPosition!.position))
}
}
}
describe("account deletion") {
var accounts: [Account]!
var deletedAccount: Account!
beforeSuite {
accounts = AccountManager.sharedInstance.accounts()
deletedAccount = accounts[Int(arc4random_uniform(UInt32(accounts.count)) + UInt32(0))]
waitUntil { done in
AccountManager.sharedInstance.delete(account: deletedAccount, completion: { (result) in
accounts = AccountManager.sharedInstance.accounts()
done()
})
}
}
it("deletes the account from the device") {
expect(accounts).notTo(contain(deletedAccount))
}
it("updates the position of all remaining accounts") {
let maxPosition = accounts.max { a, b in Int(a.position) < Int(b.position) }
var positionIncrement = 0
for account in accounts {
if Int(account.position) == positionIncrement && positionIncrement < (accounts.count - 1) {
positionIncrement += 1
}
}
expect(positionIncrement).to(equal(Int(maxPosition!.position)))
}
}
describe("account position move") {
it("saves the position move") {
var accounts: [Account]!
accounts = AccountManager.sharedInstance.accounts()
var movedAccounts = accounts!
let movedAccount = movedAccounts[Int(arc4random_uniform(UInt32(movedAccounts.count)) + UInt32(0))]
let movedAccountIndexBefore = movedAccounts.index(of: movedAccount)!
let movedAccountIndexAfter = Int(arc4random_uniform(UInt32(accounts.count)) + UInt32(0))
movedAccounts.remove(at: movedAccountIndexBefore)
movedAccounts.insert(movedAccount, at: movedAccountIndexAfter)
waitUntil { done in
AccountManager.sharedInstance.updatePosition(ofAccounts: movedAccounts, completion: { (result) in
accounts = AccountManager.sharedInstance.accounts()
done()
})
}
expect(accounts.index(of: movedAccount)).to(equal(movedAccountIndexAfter))
}
}
}
}
|
mit
|
06958358b3b6bedff35066d5ea6a2fdb
| 42.366279 | 221 | 0.496045 | 5.742109 | false | false | false | false |
lochiego/TabBuddy
|
tips/ViewController.swift
|
1
|
3612
|
//
// ViewController.swift
// tips
//
// Created by Eric Gonzalez on 12/4/15.
// Copyright © 2015 Eric Gonzalez. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var billLabel: UILabel!
@IBOutlet weak var billField: UITextField!
@IBOutlet weak var tipTitleLabel: UILabel!
@IBOutlet weak var tipLabel: UILabel!
@IBOutlet weak var separatorView: UIView!
@IBOutlet weak var totalTitleLabel: UILabel!
@IBOutlet weak var totalLabel: UILabel!
@IBOutlet weak var tipSlider: UISlider!
@IBOutlet weak var sliderView: UIView!
var valuesHidden = true
private func updateVisibility(hide: Bool) {
let alpha: CGFloat = hide ? 0 : 1
UIView.animateWithDuration(0.35) { () -> Void in
self.tipTitleLabel.alpha = alpha
self.tipLabel.alpha = alpha
self.separatorView.alpha = alpha
self.totalTitleLabel.alpha = alpha
self.totalLabel.alpha = alpha
self.sliderView.alpha = alpha
}
}
private func applyTheme() {
let backgroundColor = getThemeBackgroundColor()
view.backgroundColor = backgroundColor
sliderView.backgroundColor = backgroundColor
updateForegrounds(view)
let currencySymbol = currencyFormatter.currencySymbol
print(currencySymbol)
billField.attributedPlaceholder = NSAttributedString(string: currencySymbol, attributes: [NSForegroundColorAttributeName:UIColor ( red: 0.498, green: 0.498, blue: 0.498, alpha: 1.0 )])
tipSlider.minimumTrackTintColor = getThemeSegColor()
}
override func viewWillAppear(animated: Bool) {
applyTheme()
}
var currencyFormatter: NSNumberFormatter!
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
currencyFormatter = NSNumberFormatter()
currencyFormatter.numberStyle = .CurrencyStyle
currencyFormatter.usesGroupingSeparator = true
currencyFormatter.alwaysShowsDecimalSeparator = false
let cachedAmount = getCachedBill()
billField.text = cachedAmount == 0 ? "" : String(format:"%.2f", cachedAmount)
billChanged()
}
override func viewDidAppear(animated: Bool) {
tipSlider.value = getDefaultTip()
billChanged()
billField.becomeFirstResponder()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
@IBAction func billChanged() {
let billText = billField.text!
if (valuesHidden != billText.isEmpty) {
valuesHidden = !valuesHidden
updateVisibility(valuesHidden)
}
let billAmount = (billText as NSString).doubleValue
let tipPercent = Int(tipSlider.value)
let tip = billAmount * Double(tipPercent) * 0.01
let total = billAmount + tip
tipLabel.text = currencyFormatter.stringFromNumber(tip)
tipTitleLabel.text = "Tip (\(tipPercent)%)"
totalLabel.text = currencyFormatter.stringFromNumber(total)
updateCachedBill(billAmount)
}
@IBAction func sliderChanged(slider: UISlider) {
let newValue = roundf(slider.value)
slider.setValue(newValue, animated: true)
billChanged()
}
@IBAction func dismissKeyboard(sender: AnyObject) {
view.endEditing(true)
}
}
|
apache-2.0
|
f8e50cd17daa3a23a1059469e707482a
| 31.531532 | 192 | 0.648297 | 5.218208 | false | false | false | false |
benlangmuir/swift
|
test/SourceKit/CodeComplete/complete_sequence_toplevel.swift
|
22
|
1023
|
class Foo {
var x: Int
var y: Int
func fooMethod() {}
}
struct Bar {
var a: Int
var b: Int
}
extension Bar {
func barMethod() {}
}
func foo(arg: Foo) {
_ = arg.
}
_ = Bar(a: 12, b: 42)
// Enabled.
// RUN: %sourcekitd-test \
// RUN: -req=complete -pos=14:11 %s -- %s == \
// RUN: -req=complete -pos=13:15 %s -- %s == \
// RUN: -req=complete -pos=16:22 %s -- %s > %t.response
// RUN: %FileCheck --check-prefix=RESULT %s < %t.response
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "fooMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "x"
// RESULT-DAG: key.name: "y"
// RESULT: ]
// RESULT-NOT: key.reusingastcontext: 1
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "Foo"
// RESULT-DAG: key.name: "Bar"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
// RESULT-LABEL: key.results: [
// RESULT-DAG: key.name: "barMethod()"
// RESULT-DAG: key.name: "self"
// RESULT-DAG: key.name: "a"
// RESULT-DAG: key.name: "b"
// RESULT: ]
// RESULT: key.reusingastcontext: 1
|
apache-2.0
|
f16caa4f4d08f243d2bd39f5c93b6450
| 21.733333 | 57 | 0.596285 | 2.609694 | false | false | false | false |
davidisaaclee/VectorKit
|
Pod/Classes/Vector.swift
|
1
|
7382
|
import Foundation
/// A dimensional data structure.
public protocol Vector: CollectionType, Ring {
associatedtype Generator = IndexingGenerator<Self>
/// The type which represents this vector type's length or magnitude.
associatedtype LengthType
/// Common initializer for vectors, allowing conversion among similar vector types.
init<T where T: CollectionType, T.Generator.Element == Self.Generator.Element>(collection: T)
/// How many dimensions does this vector have?
var numberOfDimensions: Int { get }
/// The magnitude of the vector.
var magnitude: LengthType { get }
/// The squared magnitude of the vector.
var squaredMagnitude: LengthType { get }
/// A unit vector pointing in this vector's direction.
var unit: Self { get }
/// The negation of this vector, which points in the opposite direction as this vector, with an equal magnitude.
var negative: Self { get }
/// Produces a vector by translating this vector by `operand`.
func sum(operand: Self) -> Self
/// Produces a vector by translating one vector by another of a similar type.
func sum<V: Vector where V.Generator.Element == Self.Generator.Element>(operand: V) -> Self
/// Produces a vector by translating one vector by another of a similar type.
func sum<V: Vector where V.Generator.Element == Self.Generator.Element>(operand: V) -> V
/// Produces a vector by scaling this vector by a scalar.
func scale(scalar: Self.Generator.Element) -> Self
/// Produces a vector by performing a piecewise multiplication of this vector by another vector.
func piecewiseMultiply(vector: Self) -> Self
func piecewiseMultiply<V: Vector where V.Generator.Element == Self.Generator.Element>(vector: V) -> Self
func piecewiseMultiply<V: Vector where V.Generator.Element == Self.Generator.Element>(vector: V) -> V
// MARK: - Methods with default implementations
/// Produces a vector by translating one vector by another.
func + (randl: Self, randr: Self) -> Self
func + <V: Vector where V.Generator.Element == Self.Generator.Element>(randl: Self, randr: V) -> Self
func + <V: Vector where V.Generator.Element == Self.Generator.Element>(randl: Self, randr: V) -> V
/// Produces a vector by scaling a vector by a scalar.
func * (vector: Self, scalar: Self.Generator.Element) -> Self
func * (scalar: Self.Generator.Element, vector: Self) -> Self
/// Produces a vector by multiplying two vectors piecewise.
func * (lhs: Self, rhs: Self) -> Self
func * <V: Vector where V.Generator.Element == Self.Generator.Element>(lhs: Self, rhs: V) -> Self
func * <V: Vector where V.Generator.Element == Self.Generator.Element>(lhs: Self, rhs: V) -> V
/// Produces a vector by translating the right-hand vector by the negation of the left-hand vector.
func - (randl: Self, randr: Self) -> Self
func - <V: Vector where V.Generator.Element == Self.Generator.Element>(randl: Self, randr: V) -> Self
func - <V: Vector where V.Generator.Element == Self.Generator.Element>(randl: Self, randr: V) -> V
/// Negates a vector.
prefix func - (rand: Self) -> Self
}
// MARK: - Aliases
public extension Vector {
public var normalized: Self {
return self.unit
}
public var length: Self.LengthType {
return self.magnitude
}
public func distanceTo(vector: Self) -> Self.LengthType {
return (vector - self).magnitude
}
public func distanceTo<V: Vector where V.Generator.Element == Self.Generator.Element>(vector: V) -> Self.LengthType {
return self.distanceTo(Self(collection: vector))
}
}
// MARK: - Default implementations
public extension Vector {
public func generate() -> IndexingGenerator<Self> {
return IndexingGenerator(self)
}
}
public extension Vector where Self.Index == Int {
public var startIndex: Int {
return 0
}
public var endIndex: Int {
return self.numberOfDimensions
}
}
public func + <V: Vector> (randl: V, randr: V) -> V {
return randl.sum(randr)
}
public func + <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V1 {
return randl.sum(randr)
}
public func + <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V2 {
return randl.sum(randr)
}
public func * <V: Vector> (vector: V, scalar: V.Generator.Element) -> V {
return vector.scale(scalar)
}
public func * <V: Vector> (scalar: V.Generator.Element, vector: V) -> V {
return vector.scale(scalar)
}
public func * <V: Vector>(randl: V, randr: V) -> V {
return randl.piecewiseMultiply(randr)
}
public func * <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V1 {
return randl.piecewiseMultiply(randr)
}
public func * <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V2 {
return randl.piecewiseMultiply(randr)
}
public func - <V: Vector>(randl: V, randr: V) -> V {
return randl.sum(randr.negative)
}
public func - <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V1 {
return randl.sum(randr.negative)
}
public func - <V1: Vector, V2: Vector where V1.Generator.Element == V2.Generator.Element> (randl: V1, randr: V2) -> V2 {
return randl.sum(randr.negative)
}
public prefix func - <V: Vector>(rand: V) -> V {
return rand.negative
}
public extension Vector where Self: Equatable, Self.Generator.Element: Equatable {}
public func == <V: Vector where V.Generator.Element: Equatable>(lhs: V, rhs: V) -> Bool {
if lhs.count != rhs.count {
return false
}
return zip(lhs, rhs)
.map { $0.0 == $0.1 }
.reduce(true) { $0 && $1 }
}
// MARK: - Default implementations for specific element types
public extension Vector where Self.Generator.Element: Ring {
public func sum(operand: Self) -> Self {
return self.dynamicType.init(collection: Array(zip(self, operand).map { $0 + $1 }))
}
public func sum<V: Vector where V.Generator.Element == Self.Generator.Element>(operand: V) -> Self {
return self.dynamicType.init(collection: Array(zip(self, operand).map { $0 + $1 }))
}
public func sum<V: Vector where V.Generator.Element == Self.Generator.Element>(operand: V) -> V {
return V(collection: Array(zip(self, operand).map { $0 + $1 }))
}
public func scale(scalar: Self.Generator.Element) -> Self {
return self.dynamicType.init(collection: self.map { $0 * scalar })
}
public func piecewiseMultiply(vector: Self) -> Self {
return Self(collection: zip(self, vector).map { (lhs, rhs) in lhs * rhs })
}
public func piecewiseMultiply <V: Vector where V.Generator.Element == Self.Generator.Element> (vector: V) -> Self {
return Self(collection: zip(self, vector).map { (lhs, rhs) in lhs * rhs })
}
public func piecewiseMultiply <V: Vector where V.Generator.Element == Self.Generator.Element> (vector: V) -> V {
return V(collection: zip(self, vector).map { (lhs, rhs) in lhs * rhs })
}
public var squaredMagnitude: Self.Generator.Element {
return self.reduce(Self.Generator.Element.additionIdentity) { $0 + $1 * $1 }
}
}
public extension Vector where Generator.Element: Field, LengthType == Self.Generator.Element {
public var magnitude: LengthType {
return self.squaredMagnitude.toThePowerOf(0.5)
}
public var unit: Self {
return self * (self.dynamicType.LengthType.multiplicationIdentity / self.magnitude)
}
public var negative: Self {
return self * -1.0
}
}
|
mit
|
3674c1295e3ad4c3f35bbf96a6a007f5
| 31.668142 | 120 | 0.705771 | 3.289661 | false | false | false | false |
phakphumi/Chula-Expo-iOS-Application
|
Chula Expo 2017/Chula Expo 2017/CoreData/RoundData+CoreDataProperties.swift
|
1
|
12274
|
//
// RoundData+CoreDataProperties.swift
// Chula Expo 2017
//
// Created by NOT on 1/23/2560 BE.
// Copyright © 2560 Chula Computer Engineering Batch#41. All rights reserved.
//
import Foundation
import CoreData
extension RoundData {
@nonobjc public class func fetchRequest() -> NSFetchRequest<RoundData> {
return NSFetchRequest<RoundData>(entityName: "RoundData");
}
@NSManaged public var activityId: String?
@NSManaged public var endTime: Date?
@NSManaged public var fullCapacity: Int16
@NSManaged public var id: String?
@NSManaged public var reserved: Int16
@NSManaged public var seatAvaliable: Int16
@NSManaged public var startTime: Date?
@NSManaged public var toActivity: ActivityData?
var dateSection: String
{
get
{
if self.startTime!.isToday()
{
return "TODAY"
}
else if self.startTime!.isTomorrow()
{
return "TOMORROW"
}
else if self.startTime!.isYesterday()
{
return "YESTERDAY"
}
else
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE H m"
return dateFormatter.string(from: startTime! as Date)
}
}
}
var dateText: String
{
get
{
if self.startTime!.isToday()
{
return "Today"
}
else if self.startTime!.isTomorrow()
{
return "Tomorrow"
}
else if self.startTime!.isYesterday()
{
return "Yesterday"
}
else
{
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE"
return dateFormatter.string(from: startTime! as Date)
}
}
}
}
extension Date {
static var day1 = Date.from(year: 2017, month: 3, day: 15)
static var day2 = Date.from(year: 2017, month: 3, day: 16)
static var day3 = Date.from(year: 2017, month: 3, day: 17)
static var day4 = Date.from(year: 2017, month: 3, day: 18)
static var day5 = Date.from(year: 2017, month: 3, day: 19)
static var day6 = Date.from(year: 2017, month: 3, day: 20)
static func from(year: Int, month: Int, day: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
gregorianCalendar.timeZone = TimeZone(secondsFromGMT: 25200)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
static func from(year: Int, month: Int, day: Int, hour: Int, minuite: Int) -> Date {
let gregorianCalendar = NSCalendar(calendarIdentifier: .gregorian)!
gregorianCalendar.timeZone = TimeZone(secondsFromGMT: 25200)!
var dateComponents = DateComponents()
dateComponents.year = year
dateComponents.month = month
dateComponents.day = day
dateComponents.hour = hour
dateComponents.minute = minuite
let date = gregorianCalendar.date(from: dateComponents)!
return date
}
func toThaiText() -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let year = calendar.component(.year, from: self)
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
var monthText = ""
switch month {
case 1:
monthText = "มกราคม"
case 2:
monthText = "กุมภาพันธ์"
case 3:
monthText = "March"
case 4:
monthText = "เมษายน"
case 5:
monthText = "มิถุนายน"
default:
monthText = "ธันวาคม"
}
return ("\(day) \(monthText) \(year) • \(hour):\(minuiteText)")
}
func toThaiText(withEnd end: Date) -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
let endDay = calendar.component(.day, from: end)
let endHour = calendar.component(.hour, from: end)
let endMin = calendar.component(.minute, from: end)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
var endMinuiteText = "\(endMin)"
if endMin < 10{
endMinuiteText = "0\(endMin)"
}
var monthText = ""
switch month {
case 1:
monthText = "มกราคม"
case 2:
monthText = "กุมภาพันธ์"
case 3:
monthText = "March"
case 4:
monthText = "เมษายน"
case 5:
monthText = "มิถุนายน"
default:
monthText = "ธันวาคม"
}
var dayText = "\(day)"
if endDay != day {
dayText = ("\(dayText)-\(endDay)")
}
return ("\(dayText) \(monthText) • \(hour):\(minuiteText)-\(endHour):\(endMinuiteText)")
}
func toThaiTextOnlyDate(withEnd end: Date) -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let day = calendar.component(.day, from: self)
let month = calendar.component(.month, from: self)
let endDay = calendar.component(.day, from: end)
var monthText = ""
switch month {
case 1:
monthText = "มกราคม"
case 2:
monthText = "กุมภาพันธ์"
case 3:
monthText = "March"
case 4:
monthText = "เมษายน"
case 5:
monthText = "มิถุนายน"
default:
monthText = "ธันวาคม"
}
var dayText = "\(day)"
if endDay != day {
dayText = ("\(dayText)-\(endDay)")
}
return ("\(dayText) \(monthText)")
}
func toTimeText() -> String{
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
calendar.timeZone = TimeZone(secondsFromGMT: 25200)!
let hour = calendar.component(.hour, from: self)
let minuite = calendar.component(.minute, from: self)
var minuiteText = "\(minuite)"
if minuite < 10{
minuiteText = "0\(minuite)"
}
return ("\(hour):\(minuiteText)")
}
func isGreaterThanDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isGreater = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedDescending {
isGreater = true
}
//Return Result
return isGreater
}
func isLessThanDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isLess = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedAscending {
isLess = true
}
//Return Result
return isLess
}
func equalToDate(_ dateToCompare: Date) -> Bool {
//Declare Variables
var isEqualTo = false
//Compare Values
if self.compare(dateToCompare) == ComparisonResult.orderedSame {
isEqualTo = true
}
//Return Result
return isEqualTo
}
func addDays(daysToAdd: Int) -> Date {
let secondsInDays: TimeInterval = Double(daysToAdd) * 60 * 60 * 24
let dateWithDaysAdded: Date = self.addingTimeInterval(secondsInDays)
//Return Result
return dateWithDaysAdded
}
func addHours(hoursToAdd: Int) -> Date {
let secondsInHours: TimeInterval = Double(hoursToAdd) * 60 * 60
let dateWithHoursAdded: Date = self.addingTimeInterval(secondsInHours)
//Return Result
return dateWithHoursAdded
}
func isToday() -> Bool{
var isToday = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let today = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 0, to: Date())!)
let tomorrow = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 1, to: Date())!)
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "MMMM dd, EEE H m"
// print("TODAY == \(dateFormatter.string(from: today))")
// print("TOMORROW == \(dateFormatter.string(from: tomorrow))")
if(self.isLessThanDate(tomorrow)){
print("PASS1")
if(self.isGreaterThanDate(today) || self.equalToDate(today)){
isToday = true
// print("PASS2")
}
// print("MISS2")
}
// print("MISS1")
return isToday
}
func isTomorrow() -> Bool{
var isTomorrow = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let twoDayAfter = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 2, to: Date())!)
let tomorrow = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 1, to: Date())!)
if(self.isLessThanDate(twoDayAfter)){
if(self.isGreaterThanDate(tomorrow) || self.equalToDate(tomorrow)){
isTomorrow = true
}
}
return isTomorrow
}
func isYesterday() -> Bool{
var isYesterday = false
let calendar = NSCalendar(calendarIdentifier: .gregorian)!
let today = calendar.startOfDay(for: calendar.date(byAdding: .day, value: 0, to: Date())!)
let yesterday = calendar.startOfDay(for: calendar.date(byAdding: .day, value: -1, to: Date())!)
if(self.isLessThanDate(today)){
// print("PASS1")
if(self.isGreaterThanDate(yesterday) || self.equalToDate( yesterday)){
isYesterday = true
// print("PASS2")
}
}
return isYesterday
}
func isInRangeOf(start: Date?, end: Date?) -> Bool{
if (start == nil || end == nil){
return false
}
// print("condition \(start!.toThaiText()) - \(end!.toThaiText()) compareto \(self.toThaiText()))")
return self.isLessThanDate(end!) && (self.isGreaterThanDate(start!) || self.equalToDate(start!))
}
func checkInday() -> Int{
if self.isInRangeOf(start: Date.day1, end: Date.day2){
return 1
}
else if self.isInRangeOf(start: Date.day2, end: Date.day3){
return 2
}
else if self.isInRangeOf(start: Date.day3, end: Date.day4){
return 3
}
else if self.isInRangeOf(start: Date.day4, end: Date.day5){
return 4
}
else if self.isInRangeOf(start: Date.day5, end: Date.day6){
return 5
}
return 0
}
}
|
mit
|
f6af674bfc03d8c72759cb99164a5892
| 29.042394 | 106 | 0.538889 | 4.447028 | false | false | false | false |
rolandleth/LTHExtensions
|
LTHExtensions/UIView.swift
|
1
|
2159
|
//
// UIView.swift
// LTHExtensions
//
// Created by Roland Leth on 4/6/14.
// Copyright (c) 2014 Roland Leth. All rights reserved.
//
import UIKit
extension UIView {
/// Shorthand for `frame.origin.x`.
var x: CGFloat {
get { return frame.origin.x }
set { frame = CGRect(x: newValue, y: y, width: width, height: height) }
}
/// Shorthand for `frame.origin.y`.
var y: CGFloat {
get { return frame.origin.y }
set { frame = CGRect(x: x, y: newValue, width: width, height: height) }
}
/// Shorthand for `frame.size.width`.
var width: CGFloat {
get { return frame.size.width }
set { frame = CGRect(x: x, y: y, width: newValue, height: height) }
}
/// Shorthand for `frame.size.height`.
var height: CGFloat {
get { return frame.size.height }
set { frame = CGRect(x: x, y: y, width: width, height: newValue) }
}
/// An `UIView`, found at `digitIndex` in `self.subviews`.
subscript(digitIndex: Int) -> UIView? {
for (index, view) in subviews.enumerated() where index == digitIndex {
return view
}
return nil
}
/// Sets the `center.y` to the passed `view`'s `width * 0.5`.
func centerHorizontally(in view: UIView) {
center = CGPoint(x: view.width * 0.5, y: self.center.y)
}
/// Sets the `center.y` to the passed `view`'s `height * 0.5`.
func centerVertically(in view: UIView) {
center = CGPoint(x: center.x, y: view.height * 0.5)
}
/// Sets the `center` to the passed `view`'s `width * 0.5` and `height * 0.5`.
func center(in view: UIView) {
center = CGPoint(x: view.width * 0.5, y: view.height * 0.5)
}
/// Aligns `center.y` with the passed `view`'s `center.x`.
func alignHorizontally(with view: UIView) {
center = CGPoint(x: view.center.x, y: center.y)
}
/// Aligns `center.y` with the passed `view`'s `center.y`.
func alignVertically(with view: UIView) {
center = CGPoint(x: center.x, y: view.center.y)
}
/// Aligns `center` with the passed `view`'s `center`.
func align(with view: UIView) {
center = view.center
}
}
/// Adds the right hand operator as a `subview` to the left hand operator.
func << <T: UIView>(left: inout T, right: T) {
left.addSubview(right)
}
|
mit
|
ac1d702444929abb8d8fa0fd8aa111cf
| 26.329114 | 79 | 0.639648 | 2.88251 | false | false | false | false |
dimitris-c/Omicron
|
Sources/Omicron/Service/APIService+Defaults.swift
|
1
|
4324
|
//
// APIService.swift
//
// Created by Dimitris C. on 16/09/2016.
// Copyright © 2016 decimal. All rights reserved.
//
import Foundation
import Alamofire
import SwiftyJSON
public typealias CompletionBlock<Model> = (_ success: Bool, _ result: Result<Model>, _ response: HTTPURLResponse?) -> Void
internal struct Queue {
fileprivate static let queueLabel: String = "com.decimal.services.api-response-queue"
static let network: DispatchQueue = DispatchQueue(label: queueLabel,
attributes: DispatchQueue.Attributes.concurrent)
}
internal final class Log {
final class func debug(_ message:String) {
#if DEBUG
print(message)
#else
#endif
}
}
/**
A generic `APIService` which parses the response and returns the specifed `Model`
*/
public extension APIService {
/**
Executes the call of the specified `APIRequest` with the passed parse object.
- parameter completion: A completion block to handle the response
- returns: The Alamofire `Request` that can be used to cancel the request
*/
@discardableResult
public func call<Model>(request: APIRequest, parse: APIResponse<Model>, _ completion: @escaping CompletionBlock<Model>) -> Request {
let handler: (DataResponse<Any>) -> Void = { [request, parse, completion] (response) in
if let statusCode = response.response?.statusCode {
Log.debug("Request: \(request.apiPath), status code: \(statusCode)")
}
switch response.result {
case .success(let value):
let json = JSON(value)
var modelResult: Result<Model> = .failure(APIError.parseError())
if let data = parse.toData(rawData: json) {
modelResult = .success(data)
}
DispatchQueue.main.async {
completion(true, modelResult, response.response)
}
break
case .failure(let error):
if let data = response.data {
let json = JSON(data: data)
Log.debug("Server Response: \(json)")
Log.debug("Error: \(error.localizedDescription)")
}
let result: Result<Model> = .failure(error)
DispatchQueue.main.async {
completion(false, result, response.response)
}
break
}
}
Log.debug("Requesting: \(request.apiPath)")
return request.toAlamofire().validate().responseJSON(queue: Queue.network, completionHandler: handler)
}
/**
A convenient method to which outputs its response as JSON as is.
*/
@discardableResult
public func callJSON(request: APIRequest, _ completion: @escaping CompletionBlock<JSON>) -> Request {
return self.call(request: request, parse: JSONResponse(), completion)
}
/**
A convenient method to which outputs its response as String using Alamofire's `responseString`
*/
@discardableResult
public func callString(request: APIRequest, _ completion: @escaping CompletionBlock<String>) -> Request {
return request.toAlamofire().validate().responseString(queue: Queue.network,
completionHandler: { [completion] (response) in
DispatchQueue.main.async {
completion(response.result.isSuccess, response.result, response.response)
}
})
}
/**
Executes the call of the specified `APIRequest` with Data response
- parameter completion: A completion block to handle the response.
- returns: The Alamofire `Request` that can be used to cancel the request.
*/
@discardableResult
public func callData(request: APIRequest, _ completion: @escaping CompletionBlock<Data>) -> Request {
Log.debug("Requesting: \(request.apiPath)")
return request.toAlamofire().validate().responseData(completionHandler: { (response) in
DispatchQueue.main.async {
completion(response.result.isSuccess, response.result, response.response)
}
})
}
}
|
mit
|
0ec378fb7aaee93d345500226f8eb30c
| 36.921053 | 136 | 0.601666 | 5.122038 | false | false | false | false |
bromas/ActivityViewController
|
ApplicationVCSample/SpringSlideAnimator.swift
|
1
|
1662
|
//
// SpringSlideAnimator.swift
// ApplicationVCSample
//
// Created by Brian Thomas on 3/2/15.
// Copyright (c) 2015 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
class SpringSlideAnimator : NSObject, UIViewControllerAnimatedTransitioning {
func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval {
return 0.7
}
func animateTransition(using transitionContext: UIViewControllerContextTransitioning) {
let fromView = transitionContext.view(forKey: UITransitionContextViewKey.from)
let toView = transitionContext.view(forKey: UITransitionContextViewKey.to)
toView!.translatesAutoresizingMaskIntoConstraints = false
let container = transitionContext.containerView
container.backgroundColor = UIColor.black
container.addSubview(toView!)
let centerXTo = constrainEdgesOf(toView!, toEdgesOf: container)
centerXTo.constant = container.bounds.width + 16
container.layoutIfNeeded()
let animations = { () -> Void in
centerXTo.constant = 0
fromView!.transform = CGAffineTransform(translationX: -container.bounds.width - 16, y: 0.0)
container.layoutIfNeeded()
}
let completion : (Bool) -> Void = { (didComplete) in
transitionContext.completeTransition(!transitionContext.transitionWasCancelled)
return
}
UIView.animate(withDuration: 0.7, delay: 0.0, usingSpringWithDamping: 0.75, initialSpringVelocity: 0.5, options: UIViewAnimationOptions(rawValue: 0), animations: animations, completion: completion)
}
func animationEnded(_ transitionCompleted: Bool) {
}
}
|
mit
|
9c4bce703c6169d2bc49c28f372fde3e
| 34.361702 | 201 | 0.741877 | 5.145511 | false | false | false | false |
cuappdev/tcat-ios
|
TCAT/Cells/BusStopTableViewCell.swift
|
1
|
3061
|
//
// BusStopTableViewCell.swift
// TCAT
//
// Created by Matthew Barker on 2/12/17.
// Copyright © 2017 cuappdev. All rights reserved.
//
import UIKit
class BusStopTableViewCell: UITableViewCell {
private let connectorBottom = UIView()
private let connectorTop = UIView()
private let statusCircle = Circle(size: .small, style: .outline, color: Colors.tcatBlue)
private let titleLabel = UILabel()
private let hairline = UIView()
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
selectionStyle = .none
titleLabel.font = .getFont(.regular, size: 14)
titleLabel.textColor = Colors.secondaryText
titleLabel.lineBreakMode = .byWordWrapping
titleLabel.numberOfLines = 0
contentView.addSubview(titleLabel)
connectorTop.backgroundColor = Colors.tcatBlue
contentView.addSubview(connectorTop)
connectorBottom.backgroundColor = Colors.tcatBlue
contentView.addSubview(connectorBottom)
contentView.addSubview(statusCircle)
setupConstraints()
}
private func setupConstraints() {
let cellHeight: CGFloat = RouteDetailCellSize.smallHeight
let cellWidth: CGFloat = RouteDetailCellSize.indentedWidth
let connectorSize = CGSize(width: 4, height: cellHeight / 2)
let statusCircleLeadingInset = DetailIconView.width - 22 - (statusCircle.frame.width / 2)
let titleLabelSize = CGSize(width: UIScreen.main.bounds.width - cellWidth - 20, height: 20)
titleLabel.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(cellWidth)
make.centerY.equalToSuperview()
make.size.equalTo(titleLabelSize)
}
connectorTop.snp.makeConstraints { make in
make.centerX.equalTo(statusCircle)
make.top.equalToSuperview()
make.size.equalTo(connectorSize)
}
connectorBottom.snp.makeConstraints { make in
make.centerX.equalTo(statusCircle)
make.top.equalTo(connectorTop.snp.bottom)
make.size.equalTo(connectorSize)
}
statusCircle.snp.makeConstraints { make in
make.leading.equalToSuperview().inset(statusCircleLeadingInset)
make.centerY.equalToSuperview()
make.size.equalTo(statusCircle.intrinsicContentSize)
}
}
private func setupConfigDependentConstraints() {
hairline.snp.makeConstraints { make in
make.leading.equalTo(titleLabel)
make.bottom.trailing.equalToSuperview()
make.height.equalTo(0.5)
}
}
func configure(for name: String) {
titleLabel.text = name
hairline.backgroundColor = Colors.tableViewSeparator
contentView.addSubview(hairline)
setupConfigDependentConstraints()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
c04dd08c0ee337a096eec872a71d4894
| 31.903226 | 99 | 0.672876 | 4.896 | false | false | false | false |
LuckyChen73/CW_WEIBO_SWIFT
|
WeiBo/WeiBo/Classes/View(视图)/LogIn(登录界面)/WBLogInController.swift
|
1
|
5172
|
//
// WBLogInController.swift
// WeiBo
//
// Created by chenWei on 2017/4/4.
// Copyright © 2017年 陈伟. All rights reserved.
//
import UIKit
class WBLogInController: UIViewController {
//webView 的懒加载属性
lazy var webView: UIWebView = {
//1.创建 webView 并设置 frame
let webView = UIWebView(frame: self.view.bounds)
//设置代理
webView.delegate = self
//2.返回 webView
return webView
}()
override func viewDidLoad() {
super.viewDidLoad()
//创建 UI
setupUI()
//加载登录页面
loadLoginPage()
}
}
// MARK: - 创建 UI
extension WBLogInController {
/// 创建 UI
func setupUI() {
self.view.backgroundColor = UIColor.yellow
//添加 webView
self.view.addSubview(webView)
//添加返回按钮
let backBtnItem = UIBarButtonItem(title: "返回", style: UIBarButtonItemStyle.plain, target: self, action: #selector(back))
self.navigationItem.leftBarButtonItem = backBtnItem
}
//加载登录页面
func loadLoginPage() {
//url 字符串
let urlString = "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURL)"
//转换成 url 地址
let url = URL(string: urlString)
// 转为请求 request
let request = URLRequest(url: url!)
//网页加载请求
webView.loadRequest(request)
}
}
// MARK: - 点击事件
extension WBLogInController {
func back() {
//自己消失
self.dismiss(animated: true, completion: nil)
}
}
// MARK: - webView 代理
extension WBLogInController: UIWebViewDelegate {
//webView 代理方法
func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool {
//result = request.url?.absoluteString.hasPrefix("http://www.baidu.com")
// query 是获取网址后所有的字符串
guard let urlString = request.url?.absoluteString, urlString.hasPrefix("http://www.baidu.com") == true, let query = request.url?.query else {
//如果没有跳转的网址没有“http://www.baidu.com”前缀,则允许加载
return true
}
//根据上面获取的字符串范围,通过判断头部字符串,确定用户点击的是取消,还是授权
guard query.hasPrefix("code=") else {
//点击的是取消
dismiss()
return false
}
//则为授权
//拦截code http://www.baidu.com/?code=0d822614e628ed858c780b4634af6a64
let subRange = urlString.range(of: "code=") //获取"code="的范围
//range是一个index的区间值(lowerBound..<upperBound), upperBound取的是区间值的右边的index的值; lowerBounds可以取到械的index的值
let code = urlString.substring(from: (subRange?.upperBound)!) //截取 code upperBound: 最大下标,上限
//使用 code 获取 token
NetworkTool.shared.requestToken(code: code, callBack: { (tokenDict) in
//空合运算符,如果 tokenDict 没有值就会打印 ?? 后面的值
// print(tokenDict ?? "没有token")
//获取用户名和头像
guard let tokenDict = tokenDict as? [String: Any] else {
//没有获取到信息,退出登录界面
self.dismiss()
return
}
let uid = tokenDict["uid"] as! String
let token = tokenDict["access_token"] as! String
//调用网络中间层的分类中获取用户信息的方法
NetworkTool.shared.requestUser(uid: uid, accessToken: token, callBack: { (userDict) in
// print(userDict ?? "没有用户信息")
//判断 userDict 是否有值
if var userDict = userDict as? [String: Any] {
//有值就合并
for (k, v) in tokenDict {
userDict[k] = v
}
//保存信息
WBUserAccount.shared.save(dict: userDict)
//登录成功之后发送通知
NotificationCenter.default.post(name: loginSuccessNotification, object: nil)
//退出登录界面
self.dismiss()
}
})
})
//不加载
return false
}
//webView加载完成之后执行
func webViewDidFinishLoad(_ webView: UIWebView) {
webView.stringByEvaluatingJavaScript(from: "document.getElementById('userId').value='15773399189';document.getElementById('passwd').value='CW19951120")
}
func dismiss() {
dismiss(animated: true, completion: nil)
}
}
|
mit
|
13bf54c70043e9070044e88ef661cc5f
| 25.202312 | 159 | 0.538495 | 4.51494 | false | false | false | false |
PigDogBay/swift-utils
|
SwiftUtilsTests/LetterSetTests.swift
|
1
|
6096
|
//
// LetterSetTests.swift
// Anagram Solver
//
// Created by Mark Bailey on 11/02/2015.
// Copyright (c) 2015 MPD Bailey Technology. All rights reserved.
//
import UIKit
import XCTest
import SwiftUtils
class LetterSetTests: XCTestCase {
override func setUp() {
super.setUp()
// Put setup code here. This method is called before the invocation of each test method in the class.
}
override func tearDown() {
// Put teardown code here. This method is called after the invocation of each test method in the class.
super.tearDown()
}
func testIsAnagramBlank1(){
let target = LetterSet(word: "cat")
XCTAssert(target.isAnagram("chart", numberOfBlanks: 3))
XCTAssert(target.isAnagram("charts", numberOfBlanks: 3))
XCTAssertFalse(target.isAnagram("charted", numberOfBlanks: 3))
}
func testIsAnagramBlank2(){
let target = LetterSet(word: "")
XCTAssert(target.isAnagram("", numberOfBlanks: 0))
XCTAssert(target.isAnagram("cat", numberOfBlanks: 3))
XCTAssertFalse(target.isAnagram("cats", numberOfBlanks: 3))
}
func testIsAnagramBlank3(){
let target = LetterSet(word: "black")
XCTAssert(target.isAnagram("black", numberOfBlanks: 0))
XCTAssertFalse(target.isAnagram("clack", numberOfBlanks: 0))
XCTAssert(target.isAnagram("clack", numberOfBlanks: 1))
}
func testIsAnagram1() {
let target = LetterSet(word: "hearts")
XCTAssert(target.isAnagram("earths"))
XCTAssertFalse(target.isAnagram("eatths"))
}
func testIsAnagram2() {
let target = LetterSet(word: "streamline")
XCTAssert(target.isAnagram("linestream"))
XCTAssertFalse(target.isAnagram("linestmeer"))
}
func testIsSupergram1() {
let target = LetterSet(word: "err")
XCTAssert(target.isSupergram("supergram"))
}
func testIsSupergram2() {
let target = LetterSet(word: "supergram")
XCTAssert(target.isSupergram("supergram"))
}
func testIsSupergram3() {
let target = LetterSet(word: "eri")
XCTAssertFalse(target.isSupergram("supergram"))
}
func testIsSupergram4() {
let alphabet="abcdefghijklmnopqrstuvwxyz"
let target = LetterSet(word: alphabet)
XCTAssert(target.isSupergram(alphabet))
}
func testIsSubgram1()
{
let target = LetterSet(word: "streamline")
XCTAssert(target.isSubgram("treenails"))
XCTAssert(target.isSubgram("steamier"))
XCTAssert(target.isSubgram("merlins"))
XCTAssertFalse(target.isSubgram("reamx"))
}
func testIsSubgram2()
{
let target = LetterSet(word: "hearts")
XCTAssert(target.isSubgram("rates"))
XCTAssertFalse(target.isSubgram("ratjs"))
XCTAssert(target.isSubgram("shat"))
XCTAssertFalse(target.isSubgram("shit"))
XCTAssert(target.isSubgram("eat"))
XCTAssertFalse(target.isSubgram("emt"))
}
let loop = 1
func testPerformanceIsAnagram() {
let target = LetterSet(word: "streamline")
// This is an example of a performance test case.
self.measure() {
for _ in 0 ..< self.loop
{
_ = target.isAnagram("linestream")
_ = target.isAnagram("linestream")
_ = target.isAnagram("linestream")
_ = target.isAnagram("linestream")
if !target.isAnagram("linestream")
{
break
}
}
}
}
func testPerformanceIsSupergram1() {
let target = LetterSet(word: "hearts")
// This is an example of a performance test case.
self.measure() {
for _ in 0 ..< self.loop
{
_ = target.isSupergram("breathers")
_ = target.isSupergram("breathers")
_ = target.isSupergram("breathers")
_ = target.isSupergram("breathers")
if !target.isSupergram("breathers")
{
break
}
}
}
}
func testIsDistinct1(){
let target = LetterSet(word: "spectrum")
XCTAssertTrue(target.isDistinct())
}
func testIsDistinct2(){
let target = LetterSet(word: "electron")
XCTAssertFalse(target.isDistinct())
}
func testIsDistinct3(){
let target = LetterSet(word: "")
XCTAssertFalse(target.isDistinct())
}
func testIsSpellingBee1(){
let target = LetterSet(word: "deaf")
XCTAssertTrue(target.isSpellingBee("feed", mustContain: Character("e")))
XCTAssertTrue(target.isSpellingBee("feed", mustContain: Character("f")))
XCTAssertTrue(target.isSpellingBee("dadded", mustContain: Character("d")))
XCTAssertTrue(target.isSpellingBee("faffed", mustContain: Character("a")))
XCTAssertTrue(target.isSpellingBee("deaf", mustContain: Character("a")))
}
func testIsSpellingBee2(){
let target = LetterSet(word: "deaf")
XCTAssertFalse(target.isSpellingBee("feed", mustContain: Character("a")))
XCTAssertFalse(target.isSpellingBee("feed", mustContain: Character("s")))
XCTAssertFalse(target.isSpellingBee("daddy", mustContain: Character("d")))
XCTAssertFalse(target.isSpellingBee("deaf", mustContain: Character("b")))
}
func testIsSpellingBee3(){
let target = LetterSet(word: "deaf")
XCTAssertFalse(target.isSpellingBee("", mustContain: Character("a")))
XCTAssertFalse(target.isSpellingBee("DEAF", mustContain: Character("a")))
XCTAssertFalse(target.isSpellingBee("add", mustContain: Character("A")))
XCTAssertFalse(target.isSpellingBee("*&^ZA123", mustContain: Character("d")))
XCTAssertFalse(target.isSpellingBee("daddy", mustContain: Character(Unicode.Scalar(0))))
XCTAssertFalse(target.isSpellingBee("daddy", mustContain: Character(Unicode.Scalar(255))))
}
}
|
apache-2.0
|
0318ad327872f132df3e5822662860cf
| 35.722892 | 111 | 0.615322 | 4.305085 | false | true | false | false |
huonw/swift
|
test/SILOptimizer/pgo_si_reduce.swift
|
3
|
2049
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -profile-generate -Xfrontend -disable-incremental-llvm-codegen -module-name pgo_si_reduce -o %t/main
// RUN: env LLVM_PROFILE_FILE=%t/default.profraw %target-run %t/main
// RUN: %llvm-profdata merge %t/default.profraw -o %t/default.profdata
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -emit-sorted-sil -emit-sil -module-name pgo_si_reduce -o - | %FileCheck %s --check-prefix=SIL
// RUN: %target-swift-frontend %s -profile-use=%t/default.profdata -O -emit-sorted-sil -emit-sil -module-name pgo_si_reduce -o - | %FileCheck %s --check-prefix=SIL-OPT
// REQUIRES: profile_runtime
// REQUIRES: OS=macosx
public func bar(_ x: Int32) -> Int32 {
if (x == 0) {
return 42
}
if (x == 1) {
return 6
}
if (x == 2) {
return 9
}
if (x % 2 == 0) {
return 4242
}
var ret : Int32 = 0
for currNum in stride(from: 5, to: x, by: 5) {
ret += currNum
}
return ret
}
// SIL-LABEL: sil @$S13pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
// SIL-OPT-LABEL: sil @$S13pgo_si_reduce3fooyys5Int32VF : $@convention(thin) (Int32) -> () !function_entry_count(1) {
public func foo(_ x: Int32) {
// SIL: switch_enum {{.*}} : $Optional<Int32>, case #Optional.some!enumelt.1: {{.*}} !case_count(100), case #Optional.none!enumelt: {{.*}} !case_count(1)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(50)
// SIL: cond_br {{.*}}, {{.*}}, {{.*}} !true_count(1)
// SIL-OPT: integer_literal $Builtin.Int32, 4242
// SIL-OPT: integer_literal $Builtin.Int32, 42
// SIL-OPT: function_ref @$S13pgo_si_reduce3barys5Int32VADF : $@convention(thin) (Int32) -> Int32
var sum : Int32 = 0
for index in 1...x {
if (index % 2 == 0) {
sum += bar(index)
}
if (index == 50) {
sum += bar(index)
}
sum += 1
}
print(sum)
}
// SIL-LABEL: } // end sil function '$S13pgo_si_reduce3fooyys5Int32VF'
// SIL-OPT-LABEL: } // end sil function '$S13pgo_si_reduce3fooyys5Int32VF'
foo(100)
|
apache-2.0
|
f4dc70992cb495ec32d8692578b9c4a9
| 35.589286 | 167 | 0.617374 | 2.80301 | false | false | false | false |
joshpar/Lyrebird
|
LyrebirdSynth/Lyrebird/LyrebirdTypes.swift
|
1
|
6743
|
//
// LyrebirdTypes.swift
// Lyrebird
//
// Created by Joshua Parmenter on 5/2/16.
// Copyright © 2016 Op133Studios. All rights reserved.
//
public typealias LyrebirdInt = Int
public typealias LyrebirdFloat = Double
public typealias LyrebirdKey = String
public typealias LyrebirdFloatClosureBody = (_ graph: LyrebirdGraph?, _ currentPoint: LyrebirdFloat?) -> LyrebirdFloat
public protocol LyrebirdNumber {
func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat
func numberValue() -> LyrebirdFloat
func valueAtPoint(graph: LyrebirdGraph?, point: LyrebirdNumber) -> LyrebirdFloat
func valueAtPoint(point: LyrebirdNumber) -> LyrebirdFloat
}
extension LyrebirdNumber {
public func valueAtPoint(graph: LyrebirdGraph?, point: LyrebirdNumber) -> LyrebirdFloat {
//var currentPoint = point.numberValue(graph)
return self.numberValue(graph: graph)
}
public func valueAtPoint(point: LyrebirdNumber) -> LyrebirdFloat {
return self.valueAtPoint(graph: nil, point: point)
}
public func numberValue() -> LyrebirdFloat {
return self.numberValue(graph: nil)
}
}
protocol LyrebirdFloatUGenValue {
}
public struct LyrebirdFloatClosure {
public var closure : LyrebirdFloatClosureBody?
public init(closure: @escaping LyrebirdFloatClosureBody){
self.closure = closure
}
}
extension LyrebirdFloatClosure : LyrebirdValidUGenInput {
public func calculatedSamples(graph: LyrebirdGraph?) -> [[LyrebirdFloat]] {
let float = closure?(graph, nil) ?? 0.0
let returnValues = [LyrebirdFloat](repeating: LyrebirdFloat(float), count: Lyrebird.engine.blockSize)
return [returnValues]
}
public func floatValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
let float = closure?(graph, nil) ?? 0.0
return LyrebirdFloat(float)
}
public func intValue(graph: LyrebirdGraph?) -> LyrebirdInt {
let int = closure?(graph, nil) ?? 0
return LyrebirdInt(int)
}
}
extension LyrebirdFloatClosure : LyrebirdFloatUGenValue {
}
extension LyrebirdFloatClosure : LyrebirdNumber {
public func valueAtPoint(graph: LyrebirdGraph?, point: LyrebirdNumber) -> LyrebirdFloat {
let currentPoint = point.numberValue()
return closure?(graph, currentPoint) ?? 0.0
}
public func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return self.floatValue(graph: graph)
}
}
extension LyrebirdInt : LyrebirdValidUGenInput {
public func calculatedSamples(graph: LyrebirdGraph?) -> [[LyrebirdFloat]] {
let returnValues = [LyrebirdFloat](repeating: LyrebirdFloat(self), count: Lyrebird.engine.blockSize)
return [returnValues]
}
public func floatValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return LyrebirdFloat(self)
}
public func intValue(graph: LyrebirdGraph?) -> LyrebirdInt {
return self
}
}
extension LyrebirdInt : LyrebirdNumber {
public func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return self.floatValue(graph: graph)
}
}
extension LyrebirdInt : LyrebirdFloatUGenValue {
}
extension LyrebirdFloat : LyrebirdValidUGenInput {
public func intValue(graph: LyrebirdGraph?) -> LyrebirdInt {
//var selfCopy = round(self)
return LyrebirdInt(self)
}
public func calculatedSamples(graph: LyrebirdGraph?) -> [[LyrebirdFloat]] {
let returnValues = [LyrebirdFloat](repeating: self, count: Lyrebird.engine.blockSize)
return [returnValues]
}
public func floatValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return self
}
//
// public mutating func intValue(_ graph: LyrebirdGraph?) -> LyrebirdInt {
// return LyrebirdInt(round(self))
// }
}
extension LyrebirdFloat : LyrebirdNumber {
public func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return self.floatValue(graph: graph)
}
}
extension LyrebirdFloat : LyrebirdFloatUGenValue {
}
// TODO:: right now, accessing a key that doesn't exist returns zeroes. However, once mapped, that key is valid. Do we want this?
extension LyrebirdKey : LyrebirdValidUGenInput {
public func calculatedSamples(graph: LyrebirdGraph?) -> [[LyrebirdFloat]] {
if let graph: LyrebirdGraph = graph {
if let parameter = graph.parameters[self] {
return parameter.calculatedSamples(graph: graph)
}
}
let returnValues = [LyrebirdFloat](repeating: LyrebirdFloat(0.0), count: Lyrebird.engine.blockSize)
return [returnValues]
}
public func floatValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
if let graph: LyrebirdGraph = graph {
if let parameter = graph.parameters[self] {
return parameter.floatValue(graph: graph)
}
}
return 0.0
}
public func intValue(graph: LyrebirdGraph?) -> LyrebirdInt {
if let graph: LyrebirdGraph = graph {
if let parameter = graph.parameters[self] {
return parameter.intValue(graph: graph)
}
}
return 0
}
}
extension LyrebirdKey : LyrebirdFloatUGenValue {
}
extension LyrebirdKey : LyrebirdNumber {
public func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return self.floatValue(graph: graph)
}
}
/**
LyrebirdPollable is a class that keeps track of how values can change over time
Timekeeping is internal to its methods and accessible from currentTime(). With the first time currentTime() or every time start() is called (if allowsRestart is true), the timekeeping begins
*/
open class LyrebirdPollable {
var startTime: LyrebirdFloat = -1.0
var currentValue: LyrebirdFloat
open var allowsRestart: Bool = false
fileprivate var hasStarted: Bool = false
public required init(currentValue: LyrebirdFloat = 0.0){
self.currentValue = currentValue
}
public convenience init(){
self.init(currentValue: 0.0)
}
open func currentTime() -> LyrebirdFloat {
if startTime < 0.0 {
start()
return 0.0
}
let currentTime = Date.timeIntervalSinceReferenceDate
return currentTime - startTime
}
open func start() {
if !hasStarted || allowsRestart {
hasStarted = true
startTime = Date.timeIntervalSinceReferenceDate
}
}
}
extension LyrebirdPollable : LyrebirdNumber {
public func numberValue(graph: LyrebirdGraph?) -> LyrebirdFloat {
return currentValue
}
}
enum LyrebirdError : Error {
case notEnoughWires
}
|
artistic-2.0
|
aced021dec0fcb542c586d47227ef4e3
| 28.186147 | 191 | 0.668644 | 3.947307 | false | false | false | false |
omiz/In-Air
|
In Air/Resources/Color/ThemeManager.swift
|
1
|
1472
|
//
// ThemeManager.swift
// Clouds
//
// Created by Omar Allaham on 3/17/17.
// Copyright © 2017 Bemaxnet. All rights reserved.
//
import UIKit
struct ThemeManager {
static func apply() {
let sharedApplication = UIApplication.shared
sharedApplication.delegate?.window??.tintColor = UIColor.primary
UINavigationBar.appearance().barTintColor = UIColor.background
UINavigationBar.appearance().tintColor = UIColor.white
UINavigationBar.appearance().titleTextAttributes = [NSForegroundColorAttributeName : UIColor.white]
UINavigationBar.appearance().isTranslucent = false
UISwitch.appearance().onTintColor = UIColor.primary.withAlphaComponent(0.3)
UISwitch.appearance().thumbTintColor = UIColor.primary
UITableViewCell.appearance().tintColor = UIColor.primary
let bgColorView = UIView()
bgColorView.backgroundColor = UIColor.primary.withAlphaComponent(0.6)
UITableViewCell.appearance().selectedBackgroundView = bgColorView
UIBarButtonItem.appearance().setBackButtonTitlePositionAdjustment(UIOffsetMake(0, -80.0), for: .default)
// UIView.appearance().backgroundColor = .clear
UITableView.appearance().backgroundColor = .clear
UITableViewCell.appearance().backgroundColor = .clear
UICollectionViewCell.appearance().backgroundColor = .clear
UICollectionView.appearance().backgroundColor = .clear
// UILabel.appearance().textColor = .text
}
}
|
apache-2.0
|
3f7f3f95283c18407dd46339e703d5b9
| 31.688889 | 110 | 0.736914 | 5.253571 | false | false | false | false |
NikolaevSergey/KRDeviceInfo
|
Libraries/KRDeviceSize.swift
|
1
|
2357
|
//
// KRDeviceSize.swift
// DeviceInfo
//
// Created by Sergey Nikolaev on 15.11.15.
// Copyright © 2015 Sergey Nikolaev. All rights reserved.
//
import UIKit
public enum KRDeviceSize: Int {
case inch3_5
case inch4
case inch4_7
case inch5_5
case inch5_8
case unknown
public var scale: CGFloat {return UIScreen.main.scale}
public var pixelsSize: CGSize {
return CGSize(width: self.size.width*self.scale, height: self.size.height*self.scale)
}
public var size: CGSize {
switch self {
case .inch3_5: return CGSize(width: 320, height: 480)
case .inch4: return CGSize(width: 320, height: 568)
case .inch4_7: return CGSize(width: 375, height: 667)
case .inch5_5: return CGSize(width: 414, height: 736)
case .inch5_8: return CGSize(width: 375, height: 812)
case .unknown: return CGSize.zero
}
}
public init () {
let size = UIScreen.main.bounds.size
let width = min(size.width, size.height)
let height = max(size.width, size.height)
switch CGSize(width: width, height: height) {
case KRDeviceSize.inch3_5.size: self = KRDeviceSize.inch3_5
case KRDeviceSize.inch4.size: self = KRDeviceSize.inch4
case KRDeviceSize.inch4_7.size: self = KRDeviceSize.inch4_7
case KRDeviceSize.inch5_5.size: self = KRDeviceSize.inch5_5
case KRDeviceSize.inch5_8.size: self = KRDeviceSize.inch5_8
default: self = KRDeviceSize.unknown
}
}
public var description: String {
switch self {
case .inch3_5: return "3.5 inch"
case .inch4: return "4 inch"
case .inch4_7: return "4.7 inch"
case .inch5_5: return "5.5 inch"
case .inch5_8: return "5.8 inch"
case .unknown: return "Unknown"
}
}
public func getScreenValue<T> (value3_5: T! = nil, value4: T, value4_7: T, value5_5: T, value5_8: T) -> T {
switch self {
case .inch3_5: return value3_5 ?? value4
case .inch4: return value4
case .inch4_7: return value4_7
case .inch5_5: return value5_5
case .inch5_8: return value5_8
case .unknown: return value4_7
}
}
}
|
mit
|
d98cac49643e50e0f71f536b84b33fcf
| 30.837838 | 111 | 0.584041 | 3.409551 | false | false | false | false |
HabitRPG/habitrpg-ios
|
HabiticaTests/Interactors/Tasks/TaskRepeatablesSummaryInteractorTests.swift
|
1
|
6581
|
//
// TaskRepeatablesSummaryInteractorTests.swift
// Habitica
//
// Created by Phillip Thelen on 20/03/2017.
// Copyright © 2017 HabitRPG Inc. All rights reserved.
//
import Foundation
@testable import Habitica
import Habitica_Models
import Nimble
class TaskRepeatablesSummaryInteractorTests: HabiticaTests {
let interactor = TaskRepeatablesSummaryInteractor()
private let observer = TestObserver<String, NSError>()
private var task = TestTask()
override func setUp() {
super.setUp()
self.task.weekRepeat = TestWeekRepeat()
/*guard let task = NSEntityDescription.insertNewObject(forEntityName: "Task", into: HRPGManager.shared().getManagedObjectContext()) as? Task else {
return;
}
self.task = task*/
task.text = "Task Title"
task.notes = "Task notes"
task.type = "daily"
task.startDate = Date(timeIntervalSince1970: 1485887999)
}
func testDailyNeverRepeats() {
task.everyX = 0
task.frequency = "daily"
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats never"
}
func testDailyEvery() {
task.everyX = 1
task.frequency = "daily"
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats daily"
}
func testDailyEveryThree() {
task.everyX = 3
task.frequency = "daily"
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats every 3 days"
}
func testWeeklyNeverRepeats() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = false
task.weekRepeat?.tuesday = false
task.weekRepeat?.wednesday = false
task.weekRepeat?.thursday = false
task.weekRepeat?.friday = false
task.weekRepeat?.saturday = false
task.weekRepeat?.sunday = false
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats never"
}
func testWeeklyEveryAllDays() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = true
task.weekRepeat?.tuesday = true
task.weekRepeat?.wednesday = true
task.weekRepeat?.thursday = true
task.weekRepeat?.friday = true
task.weekRepeat?.saturday = true
task.weekRepeat?.sunday = true
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats weekly on every day"
}
func testWeeklyEveryOneDay() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = false
task.weekRepeat?.tuesday = true
task.weekRepeat?.wednesday = false
task.weekRepeat?.thursday = false
task.weekRepeat?.friday = false
task.weekRepeat?.saturday = false
task.weekRepeat?.sunday = false
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats weekly on Tuesday"
}
func testWeeklyEveryThreeDay() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = false
task.weekRepeat?.tuesday = true
task.weekRepeat?.wednesday = false
task.weekRepeat?.thursday = true
task.weekRepeat?.friday = false
task.weekRepeat?.saturday = true
task.weekRepeat?.sunday = false
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats weekly on Tuesday, Thursday, Saturday"
}
func testWeeklyEveryWeekdays() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = true
task.weekRepeat?.tuesday = true
task.weekRepeat?.wednesday = true
task.weekRepeat?.thursday = true
task.weekRepeat?.friday = true
task.weekRepeat?.saturday = false
task.weekRepeat?.sunday = false
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats weekly on weekdays"
}
func testWeeklyEveryWeekend() {
task.everyX = 1
task.frequency = "weekly"
task.weekRepeat?.monday = false
task.weekRepeat?.tuesday = false
task.weekRepeat?.wednesday = false
task.weekRepeat?.thursday = false
task.weekRepeat?.friday = false
task.weekRepeat?.saturday = true
task.weekRepeat?.sunday = true
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats weekly on weekends"
}
func testWeeklyEveryThreeAllDays() {
task.everyX = 3
task.frequency = "weekly"
task.weekRepeat?.monday = true
task.weekRepeat?.tuesday = true
task.weekRepeat?.wednesday = true
task.weekRepeat?.thursday = true
task.weekRepeat?.friday = true
task.weekRepeat?.saturday = true
task.weekRepeat?.sunday = true
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats every 3 weeks on every day"
}
func testMonthyEveryDayOfMonth() {
task.everyX = 1
task.frequency = "monthly"
task.daysOfMonth = [31]
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats monthly on the 31"
}
func testMonthyEveryThreeDayOfMonth() {
task.everyX = 3
task.frequency = "monthly"
task.daysOfMonth = [31]
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats every 3 months on the 31"
}
func testMonthyEveryWeekOfMonth() {
task.everyX = 1
task.frequency = "monthly"
task.weeksOfMonth = [5]
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats monthly on the 5 Tuesday"
}
func testMonthyEveryThreeWeekOfMonth() {
task.everyX = 3
task.frequency = "monthly"
task.weeksOfMonth = [5]
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats every 3 months on the 5 Tuesday"
}
func testYearlyEvery() {
task.everyX = 1
task.frequency = "yearly"
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats yearly on January 31"
}
func testYearlyEveryThree() {
task.everyX = 3
task.frequency = "yearly"
expect(self.interactor.repeatablesSummary(self.task)) == "Repeats every 3 years on January 31"
}
}
private class TestWeekRepeat: WeekRepeatProtocol {
var monday: Bool = false
var tuesday: Bool = false
var wednesday: Bool = false
var thursday: Bool = false
var friday: Bool = false
var saturday: Bool = false
var sunday: Bool = false
}
|
gpl-3.0
|
7032b6f536a172446645826ae174caf0
| 32.74359 | 155 | 0.632371 | 4.236961 | false | true | false | false |
jmgc/swift
|
test/decl/var/property_wrappers.swift
|
1
|
57964
|
// RUN: %target-typecheck-verify-swift -swift-version 5
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct Wrapper<T> {
private var _stored: T
init(stored: T) {
self._stored = stored
}
var wrappedValue: T {
get { _stored }
set { _stored = newValue }
}
}
@propertyWrapper
struct WrapperWithInitialValue<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperWithDefaultInit<T> {
private var stored: T?
var wrappedValue: T {
get { stored! }
set { stored = newValue }
}
init() {
self.stored = nil
}
}
@propertyWrapper
struct WrapperAcceptingAutoclosure<T> {
private let fn: () -> T
var wrappedValue: T {
return fn()
}
init(wrappedValue fn: @autoclosure @escaping () -> T) {
self.fn = fn
}
init(body fn: @escaping () -> T) {
self.fn = fn
}
}
@propertyWrapper
struct MissingValue<T> { }
// expected-error@-1{{property wrapper type 'MissingValue' does not contain a non-static property named 'wrappedValue'}} {{educational-notes=property-wrapper-requirements}}
@propertyWrapper
struct StaticValue {
static var wrappedValue: Int = 17
}
// expected-error@-3{{property wrapper type 'StaticValue' does not contain a non-static property named 'wrappedValue'}}
// expected-error@+1{{'@propertyWrapper' attribute cannot be applied to this declaration}}
@propertyWrapper
protocol CannotBeAWrapper {
associatedtype Value
var wrappedValue: Value { get set }
}
@propertyWrapper
struct NonVisibleValueWrapper<Value> {
private var wrappedValue: Value // expected-error{{private property 'wrappedValue' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleValueWrapper' (which is internal)}} {{educational-notes=property-wrapper-requirements}}
}
@propertyWrapper
struct NonVisibleInitWrapper<Value> {
var wrappedValue: Value
private init(wrappedValue initialValue: Value) { // expected-error{{private initializer 'init(wrappedValue:)' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleInitWrapper' (which is internal)}}
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct InitialValueTypeMismatch<Value> {
var wrappedValue: Value // expected-note{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Value?) { // expected-error{{'init(wrappedValue:)' parameter type ('Value?') must be the same as its 'wrappedValue' property type ('Value') or an @autoclosure thereof}} {{educational-notes=property-wrapper-requirements}}
self.wrappedValue = initialValue!
}
}
@propertyWrapper
struct MultipleInitialValues<Value> {
var wrappedValue: Value? = nil // expected-note 2{{'wrappedValue' declared here}}
init(wrappedValue initialValue: Int) { // expected-error{{'init(wrappedValue:)' parameter type ('Int') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
init(wrappedValue initialValue: Double) { // expected-error{{'init(wrappedValue:)' parameter type ('Double') must be the same as its 'wrappedValue' property type ('Value?') or an @autoclosure thereof}}
}
}
@propertyWrapper
struct InitialValueFailable<Value> {
var wrappedValue: Value
init?(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}} {{educational-notes=property-wrapper-requirements}}
return nil
}
}
@propertyWrapper
struct InitialValueFailableIUO<Value> {
var wrappedValue: Value
init!(wrappedValue initialValue: Value) { // expected-error{{property wrapper initializer 'init(wrappedValue:)' cannot be failable}}
return nil
}
}
// ---------------------------------------------------------------------------
// Property wrapper type definitions
// ---------------------------------------------------------------------------
@propertyWrapper
struct _lowercaseWrapper<T> {
var wrappedValue: T
}
@propertyWrapper
struct _UppercaseWrapper<T> {
var wrappedValue: T
}
// ---------------------------------------------------------------------------
// Local property wrappers
// ---------------------------------------------------------------------------
func testLocalContext() {
@WrapperWithInitialValue
var x = 17
x = 42
let _: Int = x
let _: WrapperWithInitialValue = _x
@WrapperWithInitialValue(wrappedValue: 17)
var initialValue
let _: Int = initialValue
let _: WrapperWithInitialValue = _initialValue
@Clamping(min: 0, max: 100)
var percent = 50
let _: Int = percent
let _: Clamping = _percent
@WrapperA @WrapperB
var composed = "hello"
let _: WrapperA<WrapperB> = _composed
@WrapperWithStorageRef
var hasProjection = 10
let _: Wrapper = $hasProjection
@WrapperWithInitialValue
var uninitialized: Int { // expected-error {{non-member observing properties require an initializer}}
didSet {}
}
}
// ---------------------------------------------------------------------------
// Limitations on where property wrappers can be used
// ---------------------------------------------------------------------------
enum SomeEnum {
case foo
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside an enum cannot have a wrapper}}
// expected-error@-1{{enums must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
protocol SomeProtocol {
@Wrapper(stored: 17)
var bar: Int // expected-error{{property 'bar' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
@Wrapper(stored: 17)
static var x: Int // expected-error{{property 'x' declared inside a protocol cannot have a wrapper}}
// expected-error@-1{{property in protocol must have explicit { get } or { get set } specifier}}
}
struct HasWrapper { }
extension HasWrapper {
@Wrapper(stored: 17)
var inExt: Int // expected-error{{property 'inExt' declared inside an extension cannot have a wrapper}}
// expected-error@-1{{extensions must not contain stored properties}}
@Wrapper(stored: 17)
static var x: Int
}
class ClassWithWrappers {
@Wrapper(stored: 17)
var x: Int
}
class Superclass {
var x: Int = 0
}
class SubclassOfClassWithWrappers: ClassWithWrappers {
override var x: Int {
get { return super.x }
set { super.x = newValue }
}
}
class SubclassWithWrapper: Superclass {
@Wrapper(stored: 17)
override var x: Int { get { return 0 } set { } } // expected-error{{property 'x' with attached wrapper cannot override another property}}
}
class C { }
struct BadCombinations {
@WrapperWithInitialValue
lazy var x: C = C() // expected-error{{property 'x' with a wrapper cannot also be lazy}}
@Wrapper
weak var y: C? // expected-error{{property 'y' with a wrapper cannot also be weak}}
@Wrapper
unowned var z: C // expected-error{{property 'z' with a wrapper cannot also be unowned}}
}
struct MultipleWrappers {
// FIXME: The diagnostics here aren't great. The problem is that we're
// attempting to splice a 'wrappedValue:' argument into the call to Wrapper's
// init, but it doesn't have a matching init. We're then attempting to access
// the nested 'wrappedValue', but Wrapper's 'wrappedValue' is Int.
@Wrapper(stored: 17) // expected-error{{cannot convert value of type 'Int' to expected argument type 'WrapperWithInitialValue<Int>'}}
@WrapperWithInitialValue // expected-error{{extra argument 'wrappedValue' in call}}
var x: Int = 17
@WrapperWithInitialValue // expected-error 2{{property wrapper can only apply to a single variable}}
var (y, z) = (1, 2)
}
// ---------------------------------------------------------------------------
// Initialization
// ---------------------------------------------------------------------------
struct Initialization {
@Wrapper(stored: 17)
var x: Int
@Wrapper(stored: 17)
var x2: Double
@Wrapper(stored: 17)
var x3 = 42 // expected-error {{extra argument 'wrappedValue' in call}}
@Wrapper(stored: 17)
var x4
@WrapperWithInitialValue
var y = true
@WrapperWithInitialValue<Int>
var y2 = true // expected-error{{cannot convert value of type 'Bool' to specified type 'Int'}}
mutating func checkTypes(s: String) {
x2 = s // expected-error{{cannot assign value of type 'String' to type 'Double'}}
x4 = s // expected-error{{cannot assign value of type 'String' to type 'Int'}}
y = s // expected-error{{cannot assign value of type 'String' to type 'Bool'}}
}
}
@propertyWrapper
struct Clamping<V: Comparable> {
var value: V
let min: V
let max: V
init(wrappedValue initialValue: V, min: V, max: V) {
value = initialValue
self.min = min
self.max = max
assert(value >= min && value <= max)
}
var wrappedValue: V {
get { return value }
set {
if newValue < min {
value = min
} else if newValue > max {
value = max
} else {
value = newValue
}
}
}
}
struct Color {
@Clamping(min: 0, max: 255) var red: Int = 127
@Clamping(min: 0, max: 255) var green: Int = 127
@Clamping(min: 0, max: 255) var blue: Int = 127
@Clamping(min: 0, max: 255) var alpha: Int = 255
}
func testColor() {
_ = Color(green: 17)
}
// ---------------------------------------------------------------------------
// Wrapper type formation
// ---------------------------------------------------------------------------
@propertyWrapper
struct IntWrapper {
var wrappedValue: Int
}
@propertyWrapper
struct WrapperForHashable<T: Hashable> { // expected-note{{where 'T' = 'NotHashable'}}
var wrappedValue: T
}
@propertyWrapper
struct WrapperWithTwoParams<T, U> {
var wrappedValue: (T, U)
}
struct NotHashable { }
struct UseWrappersWithDifferentForm {
@IntWrapper
var x: Int
@WrapperForHashable // expected-error {{generic struct 'WrapperForHashable' requires that 'NotHashable' conform to 'Hashable'}}
var y: NotHashable
@WrapperForHashable
var yOkay: Int
@WrapperWithTwoParams
var zOkay: (Int, Float)
@HasNestedWrapper.NestedWrapper // expected-error {{generic parameter 'T' could not be inferred}} expected-note {{explicitly specify}}
var w: Int
@HasNestedWrapper<Double>.NestedWrapper
var wOkay: Int
@HasNestedWrapper.ConcreteNestedWrapper
var wOkay2: Int
}
@propertyWrapper
struct Function<T, U> { // expected-note{{'U' declared as parameter to type 'Function'}}
var wrappedValue: (T) -> U?
}
struct TestFunction {
@Function var f: (Int) -> Float?
// FIXME: This diagnostic should be more specific
@Function var f2: (Int) -> Float // expected-error {{property type '(Int) -> Float' does not match 'wrappedValue' type '(Int) -> U?'}}
// expected-error@-1 {{generic parameter 'U' could not be inferred}}
// expected-note@-2 {{explicitly specify}}
func test() {
let _: Int = _f // expected-error{{cannot convert value of type 'Function<Int, Float>' to specified type 'Int'}}
}
}
// ---------------------------------------------------------------------------
// Nested wrappers
// ---------------------------------------------------------------------------
struct HasNestedWrapper<T> { // expected-note {{'T' declared as parameter to type 'HasNestedWrapper'}}
@propertyWrapper
struct NestedWrapper<U> {
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@propertyWrapper
struct ConcreteNestedWrapper {
var wrappedValue: T
init(wrappedValue initialValue: T) {
self.wrappedValue = initialValue
}
}
@NestedWrapper
var y: [T] = []
}
struct UsesNestedWrapper<V> {
@HasNestedWrapper<V>.NestedWrapper
var y: [V]
}
// ---------------------------------------------------------------------------
// Referencing the backing store
// ---------------------------------------------------------------------------
struct BackingStore<T> {
@Wrapper
var x: T
@WrapperWithInitialValue
private var y = true // expected-note{{'y' declared here}}
func getXStorage() -> Wrapper<T> {
return _x
}
func getYStorage() -> WrapperWithInitialValue<Bool> {
return self._y
}
}
func testBackingStore<T>(bs: BackingStore<T>) {
_ = bs.x
_ = bs.y // expected-error{{'y' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Explicitly-specified accessors
// ---------------------------------------------------------------------------
struct WrapperWithAccessors {
@Wrapper // expected-error{{property wrapper cannot be applied to a computed property}}
var x: Int {
return 17
}
}
struct UseWillSetDidSet {
@Wrapper
var x: Int {
willSet {
print(newValue)
}
}
@Wrapper
var y: Int {
didSet {
print(oldValue)
}
}
@Wrapper
var z: Int {
willSet {
print(newValue)
}
didSet {
print(oldValue)
}
}
}
struct DidSetUsesSelf {
@Wrapper
var x: Int {
didSet {
print(self)
}
}
}
// ---------------------------------------------------------------------------
// Mutating/nonmutating
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithNonMutatingSetter<Value> {
class Box {
var wrappedValue: Value
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
}
var box: Box
init(wrappedValue initialValue: Value) {
self.box = Box(wrappedValue: initialValue)
}
var wrappedValue: Value {
get { return box.wrappedValue }
nonmutating set { box.wrappedValue = newValue }
}
}
@propertyWrapper
struct WrapperWithMutatingGetter<Value> {
var readCount = 0
var writeCount = 0
var stored: Value
init(wrappedValue initialValue: Value) {
self.stored = initialValue
}
var wrappedValue: Value {
mutating get {
readCount += 1
return stored
}
set {
writeCount += 1
stored = newValue
}
}
}
@propertyWrapper
class ClassWrapper<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseMutatingnessWrappers {
@WrapperWithNonMutatingSetter
var x = true
@WrapperWithMutatingGetter
var y = 17
@WrapperWithNonMutatingSetter // expected-error{{property wrapper can only be applied to a 'var'}}
let z = 3.14159 // expected-note 2{{change 'let' to 'var' to make it mutable}}
@ClassWrapper
var w = "Hello"
}
func testMutatingness() {
var mutable = UseMutatingnessWrappers()
_ = mutable.x
mutable.x = false
_ = mutable.y
mutable.y = 42
_ = mutable.z
mutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
_ = mutable.w
mutable.w = "Goodbye"
let nonmutable = UseMutatingnessWrappers() // expected-note 2{{change 'let' to 'var' to make it mutable}}
// Okay due to nonmutating setter
_ = nonmutable.x
nonmutable.x = false
_ = nonmutable.y // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
nonmutable.y = 42 // expected-error{{cannot use mutating getter on immutable value: 'nonmutable' is a 'let' constant}}
_ = nonmutable.z
nonmutable.z = 2.71828 // expected-error{{cannot assign to property: 'z' is a 'let' constant}}
// Okay due to implicitly nonmutating setter
_ = nonmutable.w
nonmutable.w = "World"
}
// ---------------------------------------------------------------------------
// Access control
// ---------------------------------------------------------------------------
struct HasPrivateWrapper<T> {
@propertyWrapper
private struct PrivateWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@PrivateWrapper
var y: [T] = []
// expected-error@-1{{property must be declared private because its property wrapper type uses a private type}}
// Okay to reference private entities from a private property
@PrivateWrapper
private var z: [T]
}
public struct HasUsableFromInlineWrapper<T> {
@propertyWrapper
struct InternalWrapper<U> { // expected-note{{type declared here}}
var wrappedValue: U
init(wrappedValue initialValue: U) {
self.wrappedValue = initialValue
}
}
@InternalWrapper
@usableFromInline
var y: [T] = []
// expected-error@-1{{property wrapper type referenced from a '@usableFromInline' property must be '@usableFromInline' or public}}
}
@propertyWrapper
class Box<Value> {
private(set) var wrappedValue: Value
init(wrappedValue initialValue: Value) {
self.wrappedValue = initialValue
}
}
struct UseBox {
@Box
var x = 17 // expected-note{{'_x' declared here}}
}
func testBox(ub: UseBox) {
_ = ub.x
ub.x = 5 // expected-error{{cannot assign to property: 'x' is a get-only property}}
var mutableUB = ub
mutableUB = ub
}
func backingVarIsPrivate(ub: UseBox) {
_ = ub._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
// ---------------------------------------------------------------------------
// Memberwise initializers
// ---------------------------------------------------------------------------
struct MemberwiseInits<T> {
@Wrapper
var x: Bool
@WrapperWithInitialValue
var y: T
}
func testMemberwiseInits() {
// expected-error@+1{{type '(Wrapper<Bool>, Double) -> MemberwiseInits<Double>'}}
let _: Int = MemberwiseInits<Double>.init
_ = MemberwiseInits(x: Wrapper(stored: true), y: 17)
}
struct DefaultedMemberwiseInits {
@Wrapper(stored: true)
var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
var z: Int
@WrapperWithDefaultInit
var w: Int
@WrapperWithDefaultInit
var optViaDefaultInit: Int?
@WrapperWithInitialValue
var optViaInitialValue: Int?
}
struct CannotDefaultMemberwiseOptionalInit { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Int?
}
func testDefaultedMemberwiseInits() {
_ = DefaultedMemberwiseInits()
_ = DefaultedMemberwiseInits(
x: Wrapper(stored: false),
y: 42,
z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(y: 42)
_ = DefaultedMemberwiseInits(x: Wrapper(stored: false))
_ = DefaultedMemberwiseInits(z: WrapperWithInitialValue(wrappedValue: 42))
_ = DefaultedMemberwiseInits(w: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaDefaultInit: WrapperWithDefaultInit())
_ = DefaultedMemberwiseInits(optViaInitialValue: nil)
_ = DefaultedMemberwiseInits(optViaInitialValue: 42)
_ = CannotDefaultMemberwiseOptionalInit() // expected-error{{missing argument for parameter 'x' in call}}
_ = CannotDefaultMemberwiseOptionalInit(x: Wrapper(stored: nil))
}
// ---------------------------------------------------------------------------
// Default initializers
// ---------------------------------------------------------------------------
struct DefaultInitializerStruct {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
var y: Int = 10
}
struct NoDefaultInitializerStruct { // expected-note{{'init(x:)' declared here}}
@Wrapper
var x: Bool
}
class DefaultInitializerClass {
@Wrapper(stored: true)
var x
@WrapperWithInitialValue
final var y: Int = 10
}
class NoDefaultInitializerClass { // expected-error{{class 'NoDefaultInitializerClass' has no initializers}}
@Wrapper
final var x: Bool // expected-note{{stored property 'x' without initial value prevents synthesized initializers}}
}
func testDefaultInitializers() {
_ = DefaultInitializerStruct()
_ = DefaultInitializerClass()
_ = NoDefaultInitializerStruct() // expected-error{{missing argument for parameter 'x' in call}}
}
struct DefaultedPrivateMemberwiseLets {
@Wrapper(stored: true)
private var x: Bool
@WrapperWithInitialValue
var y: Int = 17
@WrapperWithInitialValue(wrappedValue: 17)
private var z: Int
}
func testDefaultedPrivateMemberwiseLets() {
_ = DefaultedPrivateMemberwiseLets()
_ = DefaultedPrivateMemberwiseLets(y: 42)
_ = DefaultedPrivateMemberwiseLets(x: Wrapper(stored: false)) // expected-error{{argument passed to call that takes no arguments}}
}
// ---------------------------------------------------------------------------
// Storage references
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithStorageRef<T> {
var wrappedValue: T
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
extension Wrapper {
var wrapperOnlyAPI: Int { return 17 }
}
struct TestStorageRef {
@WrapperWithStorageRef var x: Int // expected-note{{'_x' declared here}}
init(x: Int) {
self._x = WrapperWithStorageRef(wrappedValue: x)
}
mutating func test() {
let _: Wrapper = $x
let i = $x.wrapperOnlyAPI
let _: Int = i
// x is mutable, $x is not
x = 17
$x = Wrapper(stored: 42) // expected-error{{cannot assign to property: '$x' is immutable}}
}
}
func testStorageRef(tsr: TestStorageRef) {
let _: Wrapper = tsr.$x
_ = tsr._x // expected-error{{'_x' is inaccessible due to 'private' protection level}}
}
struct TestStorageRefPrivate {
@WrapperWithStorageRef private(set) var x: Int
init() {
self._x = WrapperWithStorageRef(wrappedValue: 5)
}
}
func testStorageRefPrivate() {
var tsr = TestStorageRefPrivate()
let a = tsr.$x // okay, getter is internal
tsr.$x = a // expected-error{{cannot assign to property: '$x' is immutable}}
}
// rdar://problem/50873275 - crash when using wrapper with projectedValue in
// generic type.
@propertyWrapper
struct InitialValueWrapperWithStorageRef<T> {
var wrappedValue: T
init(wrappedValue initialValue: T) {
wrappedValue = initialValue
}
var projectedValue: Wrapper<T> {
return Wrapper(stored: wrappedValue)
}
}
struct TestGenericStorageRef<T> {
struct Inner { }
@InitialValueWrapperWithStorageRef var inner: Inner = Inner()
}
// Wiring up the _projectedValueProperty attribute.
struct TestProjectionValuePropertyAttr {
@_projectedValueProperty(wrapperA)
@WrapperWithStorageRef var a: String
var wrapperA: Wrapper<String> {
Wrapper(stored: "blah")
}
@_projectedValueProperty(wrapperB) // expected-error{{could not find projection value property 'wrapperB'}}
@WrapperWithStorageRef var b: String
}
// ---------------------------------------------------------------------------
// Misc. semantic issues
// ---------------------------------------------------------------------------
@propertyWrapper
struct BrokenLazy { }
// expected-error@-1{{property wrapper type 'BrokenLazy' does not contain a non-static property named 'wrappedValue'}}
struct S {
@BrokenLazy
var wrappedValue: Int
}
@propertyWrapper
struct DynamicSelfStruct {
var wrappedValue: Self { self } // okay
var projectedValue: Self { self } // okay
}
@propertyWrapper
class DynamicSelf {
var wrappedValue: Self { self } // expected-error {{property wrapper wrapped value cannot have dynamic Self type}}
var projectedValue: Self? { self } // expected-error {{property wrapper projected value cannot have dynamic Self type}}
}
struct UseDynamicSelfWrapper {
@DynamicSelf() var value
}
// ---------------------------------------------------------------------------
// Invalid redeclaration
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperWithProjectedValue<T> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
class TestInvalidRedeclaration1 {
@WrapperWithProjectedValue var i = 17
// expected-note@-1 {{'i' previously declared here}}
// expected-note@-2 {{'$i' synthesized for property wrapper projected value}}
// expected-note@-3 {{'_i' synthesized for property wrapper backing storage}}
@WrapperWithProjectedValue var i = 39
// expected-error@-1 {{invalid redeclaration of 'i'}}
// expected-error@-2 {{invalid redeclaration of synthesized property '$i'}}
// expected-error@-3 {{invalid redeclaration of synthesized property '_i'}}
}
// SR-12839
struct TestInvalidRedeclaration2 {
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
}
struct TestInvalidRedeclaration3 {
@WrapperWithInitialValue var foo1 = 123 // expected-note {{'_foo1' synthesized for property wrapper backing storage}}
var _foo1 = 123 // expected-error {{invalid redeclaration of synthesized property '_foo1'}}
}
// Diagnose when wrapped property uses the name we use for lazy variable storage property.
struct TestInvalidRedeclaration4 {
@WrapperWithProjectedValue var __lazy_storage_$_foo: Int
// expected-error@-1 {{invalid redeclaration of synthesized property '$__lazy_storage_$_foo'}}
// expected-note@-2 {{'$__lazy_storage_$_foo' synthesized for property wrapper projected value}}
lazy var foo = 1
}
// ---------------------------------------------------------------------------
// Closures in initializers
// ---------------------------------------------------------------------------
struct UsesExplicitClosures {
@WrapperAcceptingAutoclosure(body: { 42 })
var x: Int
@WrapperAcceptingAutoclosure(body: { return 42 })
var y: Int
}
// ---------------------------------------------------------------------------
// Enclosing instance diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Observable<Value> {
private var stored: Value
init(wrappedValue: Value) {
self.stored = wrappedValue
}
@available(*, unavailable, message: "must be in a class")
var wrappedValue: Value { // expected-note{{'wrappedValue' has been explicitly marked unavailable here}}
get { fatalError("called wrappedValue getter") }
set { fatalError("called wrappedValue setter") }
}
static subscript<EnclosingSelf>(
_enclosingInstance observed: EnclosingSelf,
wrapped wrappedKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Value>,
storage storageKeyPath: ReferenceWritableKeyPath<EnclosingSelf, Self>
) -> Value {
get {
observed[keyPath: storageKeyPath].stored
}
set {
observed[keyPath: storageKeyPath].stored = newValue
}
}
}
struct MyObservedValueType {
@Observable // expected-error{{'wrappedValue' is unavailable: must be in a class}}
var observedProperty = 17
}
// ---------------------------------------------------------------------------
// Miscellaneous bugs
// ---------------------------------------------------------------------------
// rdar://problem/50822051 - compiler assertion / hang
@propertyWrapper
struct PD<Value> {
var wrappedValue: Value
init<A>(wrappedValue initialValue: Value, a: A) {
self.wrappedValue = initialValue
}
}
struct TestPD {
@PD(a: "foo") var foo: Int = 42
}
protocol P { }
@propertyWrapper
struct WrapperRequiresP<T: P> {
var wrappedValue: T
var projectedValue: T { return wrappedValue }
}
struct UsesWrapperRequiringP {
// expected-note@-1{{in declaration of}}
@WrapperRequiresP var x.: UsesWrapperRequiringP
// expected-error@-1{{expected member name following '.'}}
// expected-error@-2{{expected declaration}}
// expected-error@-3{{type annotation missing in pattern}}
}
// SR-10899 / rdar://problem/51588022
@propertyWrapper
struct SR_10899_Wrapper {
var wrappedValue: String { "hi" }
}
struct SR_10899_Usage {
@SR_10899_Wrapper var thing: Bool // expected-error{{property type 'Bool' does not match 'wrappedValue' type 'String'}}
}
// SR-11061 / rdar://problem/52593304 assertion with DeclContext mismatches
class SomeValue {
@SomeA(closure: { $0 }) var some: Int = 100
}
@propertyWrapper
struct SomeA<T> {
var wrappedValue: T
let closure: (T) -> (T)
init(wrappedValue initialValue: T, closure: @escaping (T) -> (T)) {
self.wrappedValue = initialValue
self.closure = closure
}
}
// rdar://problem/51989272 - crash when the property wrapper is a generic type
// alias
typealias Alias<T> = WrapperWithInitialValue<T>
struct TestAlias {
@Alias var foo = 17
}
// rdar://problem/52969503 - crash due to invalid source ranges in ill-formed
// code.
@propertyWrapper
struct Wrap52969503<T> {
var wrappedValue: T
init(blah: Int, wrappedValue: T) { }
}
struct Test52969503 {
@Wrap52969503(blah: 5) var foo: Int = 1 // expected-error{{argument 'blah' must precede argument 'wrappedValue'}}
}
//
// ---------------------------------------------------------------------------
// Property wrapper composition
// ---------------------------------------------------------------------------
@propertyWrapper
struct WrapperA<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperB<Value> {
var wrappedValue: Value
init(wrappedValue initialValue: Value) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperC<Value> { // expected-note {{'Value' declared as parameter to type 'WrapperC'}}
var wrappedValue: Value?
init(wrappedValue initialValue: Value?) {
wrappedValue = initialValue
}
}
@propertyWrapper
struct WrapperD<Value, X, Y> {
var wrappedValue: Value
}
@propertyWrapper
struct WrapperE<Value> {
var wrappedValue: Value
}
struct TestComposition {
@WrapperA @WrapperB @WrapperC var p1: Int?
@WrapperA @WrapperB @WrapperC var p2 = "Hello"
@WrapperD<WrapperE, Int, String> @WrapperE var p3: Int?
@WrapperD<WrapperC, Int, String> @WrapperC var p4: Int?
@WrapperD<WrapperC, Int, String> @WrapperE var p5: Int // expected-error{{generic parameter 'Value' could not be inferred}}
// expected-note@-1 {{explicitly specify the generic arguments to fix this issue}}
// expected-error@-2 {{composed wrapper type 'WrapperE<Int>' does not match former 'wrappedValue' type 'WrapperC<Value>'}}
func triggerErrors(d: Double) { // expected-note 6 {{mark method 'mutating' to make 'self' mutable}} {{2-2=mutating }}
p1 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{8-8=Int(}} {{9-9=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
p2 = d // expected-error{{cannot assign value of type 'Double' to type 'String?'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
// TODO(diagnostics): Looks like source range for 'd' here is reported as starting at 10, but it should be 8
p3 = d // expected-error{{cannot assign value of type 'Double' to type 'Int?'}} {{10-10=Int(}} {{11-11=)}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p1 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<Int>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p2 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperA<WrapperB<WrapperC<String>>>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
_p3 = d // expected-error{{cannot assign value of type 'Double' to type 'WrapperD<WrapperE<Int?>, Int, String>'}}
// expected-error@-1 {{cannot assign to property: 'self' is immutable}}
}
}
// ---------------------------------------------------------------------------
// Property wrapper composition type inference
// ---------------------------------------------------------------------------
protocol DefaultValue {
static var defaultValue: Self { get }
}
extension Int: DefaultValue {
static var defaultValue: Int { 0 }
}
struct TestCompositionTypeInference {
@propertyWrapper
struct A<Value: DefaultValue> {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue, key: String) {
self.wrappedValue = wrappedValue
}
}
@propertyWrapper
struct B<Value: DefaultValue>: DefaultValue {
var wrappedValue: Value
init(wrappedValue: Value = .defaultValue) {
self.wrappedValue = wrappedValue
}
static var defaultValue: B<Value> { B() }
}
// All of these are okay
@A(key: "b") @B
var a: Int = 0
@A(key: "b") @B
var b: Int
@A(key: "c") @B @B
var c: Int
}
// ---------------------------------------------------------------------------
// Missing Property Wrapper Unwrap Diagnostics
// ---------------------------------------------------------------------------
@propertyWrapper
struct Foo<T> { // expected-note {{arguments to generic parameter 'T' ('W' and 'Int') are expected to be equal}}
var wrappedValue: T {
get {
fatalError("boom")
}
set {
}
}
var prop: Int = 42
func foo() {}
func bar(x: Int) {}
subscript(q: String) -> Int {
get { return 42 }
set { }
}
subscript(x x: Int) -> Int {
get { return 42 }
set { }
}
subscript(q q: String, a: Int) -> Bool {
get { return false }
set { }
}
}
extension Foo : Equatable where T : Equatable {
static func == (lhs: Foo, rhs: Foo) -> Bool {
lhs.wrappedValue == rhs.wrappedValue
}
}
extension Foo : Hashable where T : Hashable {
func hash(into hasher: inout Hasher) {
hasher.combine(wrappedValue)
}
}
@propertyWrapper
struct Bar<T, V> {
var wrappedValue: T
func bar() {}
// TODO(diagnostics): We need to figure out what to do about subscripts.
// The problem standing in our way - keypath application choice
// is always added to results even if it's not applicable.
}
@propertyWrapper
struct Baz<T> {
var wrappedValue: T
func onPropertyWrapper() {}
var projectedValue: V {
return V()
}
}
extension Bar where V == String { // expected-note {{where 'V' = 'Bool'}}
func barWhereVIsString() {}
}
struct V {
func onProjectedValue() {}
}
struct W {
func onWrapped() {}
}
struct MissingPropertyWrapperUnwrap {
@Foo var w: W
@Foo var x: Int
@Bar<Int, Bool> var y: Int
@Bar<Int, String> var z: Int
@Baz var usesProjectedValue: W
func a<T>(_: Foo<T>) {}
func a<T>(named: Foo<T>) {}
func b(_: Foo<Int>) {}
func c(_: V) {}
func d(_: W) {}
func e(_: Foo<W>) {}
subscript<T : Hashable>(takesFoo x: Foo<T>) -> Foo<T> { x }
func baz() {
self.x.foo() // expected-error {{referencing instance method 'foo()' requires wrapper 'Foo<Int>'}}{{10-10=_}}
self.x.prop // expected-error {{referencing property 'prop' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x.bar(x: 42) // expected-error {{referencing instance method 'bar(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.y.bar() // expected-error {{referencing instance method 'bar()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
self.y.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, Bool>'}}{{10-10=_}}
// expected-error@-1 {{referencing instance method 'barWhereVIsString()' on 'Bar' requires the types 'Bool' and 'String' be equivalent}}
self.z.barWhereVIsString() // expected-error {{referencing instance method 'barWhereVIsString()' requires wrapper 'Bar<Int, String>'}}{{10-10=_}}
self.usesProjectedValue.onPropertyWrapper() // expected-error {{referencing instance method 'onPropertyWrapper()' requires wrapper 'Baz<W>'}}{{10-10=_}}
self._w.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self.usesProjectedValue.onProjectedValue() // expected-error {{referencing instance method 'onProjectedValue()' requires wrapper 'V'}}{{10-10=$}}
self.$usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
self._usesProjectedValue.onWrapped() // expected-error {{referencing instance method 'onWrapped()' requires wrapped value of type 'W'}}{{10-11=}}
a(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self.x) // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{12-12=_}}
b(self.w) // expected-error {{cannot convert value of type 'W' to expected argument type 'Foo<Int>'}}
e(self.w) // expected-error {{cannot convert value 'w' of type 'W' to expected type 'Foo<W>', use wrapper instead}}{{12-12=_}}
b(self._w) // expected-error {{cannot convert value of type 'Foo<W>' to expected argument type 'Foo<Int>'}}
c(self.usesProjectedValue) // expected-error {{cannot convert value 'usesProjectedValue' of type 'W' to expected type 'V', use wrapper instead}}{{12-12=$}}
d(self.$usesProjectedValue) // expected-error {{cannot convert value '$usesProjectedValue' of type 'V' to expected type 'W', use wrapped value instead}}{{12-13=}}
d(self._usesProjectedValue) // expected-error {{cannot convert value '_usesProjectedValue' of type 'Baz<W>' to expected type 'W', use wrapped value instead}}{{12-13=}}
self.x["ultimate question"] // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x["ultimate question"] = 42 // expected-error {{referencing subscript 'subscript(_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[x: 42] = 0 // expected-error {{referencing subscript 'subscript(x:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
self.x[q: "ultimate question", 42] = true // expected-error {{referencing subscript 'subscript(q:_:)' requires wrapper 'Foo<Int>'}} {{10-10=_}}
// SR-11476
_ = \Self.[takesFoo: self.x] // expected-error {{cannot convert value 'x' of type 'Int' to expected type 'Foo<Int>', use wrapper instead}}{{31-31=_}}
_ = \Foo<W>.[x: self._x] // expected-error {{cannot convert value '_x' of type 'Foo<Int>' to expected type 'Int', use wrapped value instead}} {{26-27=}}
}
}
struct InvalidPropertyDelegateUse {
// TODO(diagnostics): We need to a tailored diagnostic for extraneous arguments in property delegate initialization
@Foo var x: Int = 42 // expected-error@:21 {{argument passed to call that takes no arguments}}
func test() {
self.x.foo() // expected-error {{value of type 'Int' has no member 'foo'}}
}
}
// SR-11060
class SR_11060_Class {
@SR_11060_Wrapper var property: Int = 1234 // expected-error {{missing argument for parameter 'string' in property wrapper initializer; add 'wrappedValue' and 'string' arguments in '@SR_11060_Wrapper(...)'}}
}
@propertyWrapper
struct SR_11060_Wrapper {
var wrappedValue: Int
init(wrappedValue: Int, string: String) { // expected-note {{'init(wrappedValue:string:)' declared here}}
self.wrappedValue = wrappedValue
}
}
// SR-11138
// Check that all possible compositions of nonmutating/mutating accessors
// on wrappers produce wrapped properties with the correct settability and
// mutatiness in all compositions.
@propertyWrapper
struct NonmutatingGetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
}
}
@propertyWrapper
struct MutatingGetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetNonmutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
nonmutating set { fatalError() }
}
}
@propertyWrapper
struct NonmutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
nonmutating get { fatalError() }
mutating set { fatalError() }
}
}
@propertyWrapper
struct MutatingGetMutatingSetWrapper<T> {
var wrappedValue: T {
mutating get { fatalError() }
mutating set { fatalError() }
}
}
struct AllCompositionsStruct {
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetWrapper
var ngxs_ngxs: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var ngxs_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngxs_ngns: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgns: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var ngxs_ngms: Int
// Should be disallowed
@NonmutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var ngxs_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetWrapper
var mgxs_ngxs: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetWrapper // expected-error{{cannot be composed}}
var mgxs_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgxs_ngns: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetNonmutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgns: Int
// Should have mutating getter, undefined setter
@MutatingGetWrapper @NonmutatingGetMutatingSetWrapper
var mgxs_ngms: Int
// Should be disallowed
@MutatingGetWrapper @MutatingGetMutatingSetWrapper // expected-error{{cannot be composed}}
var mgxs_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var ngns_ngxs: Int
// Should have nonmutating getter, undefined setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var ngns_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngns_ngns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngns_mgns: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngns_ngms: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngns_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetWrapper
var mgns_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetNonmutatingSetWrapper @MutatingGetWrapper
var mgns_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgns_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgns_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgns_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetNonmutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgns_mgms: Int
////
// Should have nonmutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var ngms_ngxs: Int
// Should have mutating getter, undefined setter
@NonmutatingGetMutatingSetWrapper @MutatingGetWrapper
var ngms_mgxs: Int
// Should have nonmutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var ngms_ngns: Int
// Should have mutating getter, nonmutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var ngms_mgns: Int
// Should have nonmutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var ngms_ngms: Int
// Should have mutating getter, mutating setter
@NonmutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var ngms_mgms: Int
////
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @NonmutatingGetWrapper
var mgms_ngxs: Int
// Should have mutating getter, undefined setter
@MutatingGetMutatingSetWrapper @MutatingGetWrapper
var mgms_mgxs: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetNonmutatingSetWrapper
var mgms_ngns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetNonmutatingSetWrapper
var mgms_mgns: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @NonmutatingGetMutatingSetWrapper
var mgms_ngms: Int
// Should have mutating getter, mutating setter
@MutatingGetMutatingSetWrapper @MutatingGetMutatingSetWrapper
var mgms_mgms: Int
func readonlyContext(x: Int) { // expected-note *{{}}
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs // expected-error{{}}
// _ = mgxs_mgxs
_ = mgxs_ngns // expected-error{{}}
// _ = mgxs_mgns
_ = mgxs_ngms // expected-error{{}}
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs // expected-error{{}}
_ = mgns_mgxs // expected-error{{}}
_ = mgns_ngns // expected-error{{}}
_ = mgns_mgns // expected-error{{}}
_ = mgns_ngms // expected-error{{}}
_ = mgns_mgms // expected-error{{}}
_ = ngms_ngxs
_ = ngms_mgxs // expected-error{{}}
_ = ngms_ngns
_ = ngms_mgns // expected-error{{}}
_ = ngms_ngms
_ = ngms_mgms // expected-error{{}}
_ = mgms_ngxs // expected-error{{}}
_ = mgms_mgxs // expected-error{{}}
_ = mgms_ngns // expected-error{{}}
_ = mgms_mgns // expected-error{{}}
_ = mgms_ngms // expected-error{{}}
_ = mgms_mgms // expected-error{{}}
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x // expected-error{{}}
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x // expected-error{{}}
mgns_mgns = x // expected-error{{}}
mgns_ngms = x // expected-error{{}}
mgns_mgms = x // expected-error{{}}
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
// FIXME: This ought to be allowed because it's a pure set, so the mutating
// get should not come into play.
ngms_mgns = x // expected-error{{cannot use mutating getter}}
ngms_ngms = x // expected-error{{}}
ngms_mgms = x // expected-error{{}}
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x // expected-error{{}}
mgms_mgns = x // expected-error{{}}
mgms_ngms = x // expected-error{{}}
mgms_mgms = x // expected-error{{}}
}
mutating func mutatingContext(x: Int) {
_ = ngxs_ngxs
// _ = ngxs_mgxs
_ = ngxs_ngns
// _ = ngxs_mgns
_ = ngxs_ngms
// _ = ngxs_mgms
_ = mgxs_ngxs
// _ = mgxs_mgxs
_ = mgxs_ngns
// _ = mgxs_mgns
_ = mgxs_ngms
// _ = mgxs_mgms
_ = ngns_ngxs
_ = ngns_mgxs
_ = ngns_ngns
_ = ngns_mgns
_ = ngns_ngms
_ = ngns_mgms
_ = mgns_ngxs
_ = mgns_mgxs
_ = mgns_ngns
_ = mgns_mgns
_ = mgns_ngms
_ = mgns_mgms
_ = ngms_ngxs
_ = ngms_mgxs
_ = ngms_ngns
_ = ngms_mgns
_ = ngms_ngms
_ = ngms_mgms
_ = mgms_ngxs
_ = mgms_mgxs
_ = mgms_ngns
_ = mgms_mgns
_ = mgms_ngms
_ = mgms_mgms
////
ngxs_ngxs = x // expected-error{{}}
// ngxs_mgxs = x
ngxs_ngns = x
// ngxs_mgns = x
ngxs_ngms = x // expected-error{{}}
// ngxs_mgms = x
mgxs_ngxs = x // expected-error{{}}
// mgxs_mgxs = x
mgxs_ngns = x
// mgxs_mgns = x
mgxs_ngms = x // expected-error{{}}
// mgxs_mgms = x
ngns_ngxs = x // expected-error{{}}
ngns_mgxs = x // expected-error{{}}
ngns_ngns = x
ngns_mgns = x
ngns_ngms = x
ngns_mgms = x
mgns_ngxs = x // expected-error{{}}
mgns_mgxs = x // expected-error{{}}
mgns_ngns = x
mgns_mgns = x
mgns_ngms = x
mgns_mgms = x
ngms_ngxs = x // expected-error{{}}
ngms_mgxs = x // expected-error{{}}
ngms_ngns = x
ngms_mgns = x
ngms_ngms = x
ngms_mgms = x
mgms_ngxs = x // expected-error{{}}
mgms_mgxs = x // expected-error{{}}
mgms_ngns = x
mgms_mgns = x
mgms_ngms = x
mgms_mgms = x
}
}
// rdar://problem/54184846 - crash while trying to retrieve wrapper info on l-value base type
func test_missing_method_with_lvalue_base() {
@propertyWrapper
struct Ref<T> {
var wrappedValue: T
}
struct S<T> where T: RandomAccessCollection, T.Element: Equatable {
@Ref var v: T.Element
init(items: T, v: Ref<T.Element>) {
self.v.binding = v // expected-error {{value of type 'T.Element' has no member 'binding'}}
}
}
}
// SR-11288
// Look into the protocols that the type conforms to
// typealias as propertyWrapper //
@propertyWrapper
struct SR_11288_S0 {
var wrappedValue: Int
}
protocol SR_11288_P1 {
typealias SR_11288_Wrapper1 = SR_11288_S0
}
struct SR_11288_S1: SR_11288_P1 {
@SR_11288_Wrapper1 var answer = 42 // Okay
}
// associatedtype as propertyWrapper //
protocol SR_11288_P2 {
associatedtype SR_11288_Wrapper2 = SR_11288_S0
}
struct SR_11288_S2: SR_11288_P2 {
@SR_11288_Wrapper2 var answer = 42 // expected-error {{unknown attribute 'SR_11288_Wrapper2'}}
}
protocol SR_11288_P3 {
associatedtype SR_11288_Wrapper3
}
struct SR_11288_S3: SR_11288_P3 {
typealias SR_11288_Wrapper3 = SR_11288_S0
@SR_11288_Wrapper3 var answer = 42 // Okay
}
// typealias as propertyWrapper in a constrained protocol extension //
protocol SR_11288_P4 {}
extension SR_11288_P4 where Self: AnyObject { // expected-note {{requirement specified as 'Self' : 'AnyObject' [with Self = SR_11288_S4]}}
typealias SR_11288_Wrapper4 = SR_11288_S0
}
struct SR_11288_S4: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // expected-error {{'Self.SR_11288_Wrapper4' (aka 'SR_11288_S0') requires that 'SR_11288_S4' be a class type}}
}
class SR_11288_C0: SR_11288_P4 {
@SR_11288_Wrapper4 var answer = 42 // Okay
}
// typealias as propertyWrapper in a generic type //
protocol SR_11288_P5 {
typealias SR_11288_Wrapper5 = SR_11288_S0
}
struct SR_11288_S5<T>: SR_11288_P5 {
@SR_11288_Wrapper5 var answer = 42 // Okay
}
// SR-11393
protocol Copyable: AnyObject {
func copy() -> Self
}
@propertyWrapper
struct CopyOnWrite<Value: Copyable> {
init(wrappedValue: Value) {
self.wrappedValue = wrappedValue
}
var wrappedValue: Value
var projectedValue: Value {
mutating get {
if !isKnownUniquelyReferenced(&wrappedValue) {
wrappedValue = wrappedValue.copy()
}
return wrappedValue
}
set {
wrappedValue = newValue
}
}
}
final class CopyOnWriteTest: Copyable {
let a: Int
init(a: Int) {
self.a = a
}
func copy() -> Self {
Self.init(a: a)
}
}
struct CopyOnWriteDemo1 {
@CopyOnWrite var a = CopyOnWriteTest(a: 3)
func foo() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
_ = $a // expected-error{{cannot use mutating getter on immutable value: 'self' is immutable}}
}
}
@propertyWrapper
struct NonMutatingProjectedValueSetWrapper<Value> {
var wrappedValue: Value
var projectedValue: Value {
get { wrappedValue }
nonmutating set { }
}
}
struct UseNonMutatingProjectedValueSet {
@NonMutatingProjectedValueSetWrapper var x = 17
func test() { // expected-note{{mark method 'mutating' to make 'self' mutable}}
$x = 42 // okay
x = 42 // expected-error{{cannot assign to property: 'self' is immutable}}
}
}
// SR-11478
@propertyWrapper
struct SR_11478_W<Value> {
var wrappedValue: Value
}
class SR_11478_C1 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
final class SR_11478_C2 {
@SR_11478_W static var bool1: Bool = true // Ok
@SR_11478_W class var bool2: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
@SR_11478_W class final var bool3: Bool = true // expected-error {{class stored properties not supported in classes; did you mean 'static'?}}
}
// SR-11381
@propertyWrapper
struct SR_11381_W<T> {
init(wrappedValue: T) {}
var wrappedValue: T {
fatalError()
}
}
struct SR_11381_S {
@SR_11381_W var foo: Int = nil // expected-error {{'nil' is not compatible with expected argument type 'Int'}}
}
// rdar://problem/53349209 - regression in property wrapper inference
struct Concrete1: P {}
@propertyWrapper struct ConcreteWrapper {
var wrappedValue: Concrete1 { get { fatalError() } }
}
struct TestConcrete1 {
@ConcreteWrapper() var s1
func f() {
// Good:
let _: P = self.s1
// Bad:
self.g(s1: self.s1)
// Ugly:
self.g(s1: self.s1 as P)
}
func g(s1: P) {
// ...
}
}
// SR-11477
// Two initializers that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W1 { // Okay
let name: String
init() {
self.name = "Init"
}
init(name: String = "DefaultParamInit") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Two initializers with default arguments that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W2 { // Okay
let name: String
init(anotherName: String = "DefaultParamInit1") {
self.name = anotherName
}
init(name: String = "DefaultParamInit2") {
self.name = name
}
var wrappedValue: Int {
get { return 0 }
}
}
// Single initializer that can default initialize the wrapper //
@propertyWrapper
struct SR_11477_W3 { // Okay
let name: String
init() {
self.name = "Init"
}
var wrappedValue: Int {
get { return 0 }
}
}
// rdar://problem/56213175 - backward compatibility issue with Swift 5.1,
// which unconditionally skipped protocol members.
protocol ProtocolWithWrapper {
associatedtype Wrapper = Float // expected-note{{associated type 'Wrapper' declared here}}
}
struct UsesProtocolWithWrapper: ProtocolWithWrapper {
@Wrapper var foo: Int // expected-warning{{ignoring associated type 'Wrapper' in favor of module-scoped property wrapper 'Wrapper'; please qualify the reference with 'property_wrappers'}}{{4-4=property_wrappers.}}
}
// rdar://problem/56350060 - [Dynamic key path member lookup] Assertion when subscripting with a key path
func test_rdar56350060() {
@propertyWrapper
@dynamicMemberLookup
struct DynamicWrapper<Value> {
var wrappedValue: Value { fatalError() }
subscript<T>(keyPath keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
fatalError()
}
subscript<T>(dynamicMember keyPath: KeyPath<Value, T>) -> DynamicWrapper<T> {
return self[keyPath: keyPath] // Ok
}
}
}
// rdar://problem/57411331 - crash due to incorrectly synthesized "nil" default
// argument.
@propertyWrapper
struct Blah<Value> {
init(blah _: Int) { }
var wrappedValue: Value {
let val: Value? = nil
return val!
}
}
struct UseRdar57411331 {
let x = Rdar57411331(other: 5)
}
struct Rdar57411331 {
@Blah(blah: 17) var something: Int?
var other: Int
}
// SR-11994
@propertyWrapper
open class OpenPropertyWrapperWithPublicInit {
public init(wrappedValue: String) { // Okay
self.wrappedValue = wrappedValue
}
open var wrappedValue: String = "Hello, world"
}
// SR-11654
struct SR_11654_S {}
class SR_11654_C {
@Foo var property: SR_11654_S?
}
func sr_11654_generic_func<T>(_ argument: T?) -> T? {
return argument
}
let sr_11654_c = SR_11654_C()
_ = sr_11654_generic_func(sr_11654_c.property) // Okay
// rdar://problem/59471019 - property wrapper initializer requires empty parens
// for default init
@propertyWrapper
struct DefaultableIntWrapper {
var wrappedValue: Int
init() {
self.wrappedValue = 0
}
}
struct TestDefaultableIntWrapper {
@DefaultableIntWrapper var x
@DefaultableIntWrapper() var y
@DefaultableIntWrapper var z: Int
mutating func test() {
x = y
y = z
}
}
@propertyWrapper
public struct NonVisibleImplicitInit {
// expected-error@-1 {{internal initializer 'init()' cannot have more restrictive access than its enclosing property wrapper type 'NonVisibleImplicitInit' (which is public)}}
public var wrappedValue: Bool {
return false
}
}
@propertyWrapper
struct OptionalWrapper<T> {
init() {}
var wrappedValue: T? { nil }
}
struct UseOptionalWrapper {
@OptionalWrapper var p: Int?? // Okay
}
|
apache-2.0
|
14c07c19426202cd3238e2711fefb751
| 26.894129 | 260 | 0.648075 | 4.201203 | false | false | false | false |
mcgraw/tomorrow
|
Tomorrow/IGIGradientView.swift
|
1
|
947
|
//
// IGIGradientView.swift
// Tomorrow
//
// Created by David McGraw on 1/24/15.
// Copyright (c) 2015 David McGraw. All rights reserved.
//
import UIKit
class IGIGradientView: UIView {
var gradientLayer: CAGradientLayer?
var startColor: UIColor?
var endColor: UIColor?
override func layoutSubviews() {
super.layoutSubviews()
gradientLayer?.frame = bounds
}
func updateGradientLayer(startColor: UIColor, endColor: UIColor) {
self.startColor = startColor
self.endColor = endColor
if gradientLayer == nil {
gradientLayer = CAGradientLayer()
gradientLayer?.frame = bounds
gradientLayer?.colors = [startColor.CGColor, endColor.CGColor]
layer.insertSublayer(gradientLayer, atIndex: 0)
} else {
gradientLayer?.colors = [startColor.CGColor, endColor.CGColor]
}
}
}
|
bsd-2-clause
|
b0a827bea7bd86ed26371179d1d864ff
| 24.594595 | 74 | 0.619852 | 4.932292 | false | false | false | false |
mlibai/XZKit
|
XZKit/Code/CacheManager/XZImageCacheManager.swift
|
1
|
3862
|
//
// XZImageCacheManager.swift
// XZKit
//
// Created by Xezun on 2018/6/11.
// Copyright © 2018年 XEZUN INC. All rights reserved.
//
import UIKit
public let ImageCacheStorage = "image"
extension CacheManager.Domain {
public static let XZKit = CacheManager.Domain.init(rawValue: "com.xezun.XZKit.CacheManager")
}
extension CacheManager.Storage {
public static let image = CacheManager.Storage.init(rawValue: "image")
}
/// 图片缓存。
@objc(XZImageCacheManager)
final public class ImageCacheManager: CacheManager {
/// XZKit 默认的图片缓存。
@objc(defaultManager)
public static let `default` = try! ImageCacheManager.init(domain: .XZKit, storage: .image)
@objc(XZImageCacheType)
public enum ImageType: Int, CustomStringConvertible {
@objc(XZImageCacheTypePNG)
case png
@objc(XZImageCacheTypeJPG)
case jpg
public var description: String {
switch self {
case .png: return "png"
case .jpg: return "jpg"
}
}
}
@objc(identifierForImageName:type:scale:)
public func identifier(for imageName: String, type: ImageType, scale: CGFloat) -> String {
return "\(imageName)@\(Int(scale))x.\(type.description)"
}
@objc(imageNamed:type:scale:)
public func image(named imageName: String, type: ImageType = .png, scale: CGFloat = UIScreen.main.scale) -> UIImage? {
let identifier = self.identifier(for: imageName, type: type, scale: scale)
return UIImage.init(named: self.filePath(forIdentifier: identifier))
}
@discardableResult
@objc(cacheImage:name:type:scale:)
public func cache(_ image: UIImage?, name: String, type: ImageType = .png, scale: CGFloat = UIScreen.main.scale) -> Bool {
let identifier = self.identifier(for: name, type: type, scale: scale)
guard let image = image else {
return self.removeData(forIdentifier: identifier)
}
if let data = image.pngData() {
return self.setData(data, forIdentifier: identifier)
} else if let data = image.jpegData(compressionQuality: 1.0) {
return self.setData(data, forIdentifier: identifier)
}
return false
}
/// 匹配图片名称中的拓展名,如 @2x.png 等。
private static let regularExpression = try! NSRegularExpression.init(pattern: "(@[1-9]+x)*.[a-z]+$", options: .caseInsensitive)
/// 图片 URL 生成标识符。
///
/// - Parameter imageURL: 图片 URL 。
/// - Returns: 图片缓存标识符。
@objc(identifierForImageURL:)
public func identifier(for imageURL: URL) -> String {
let fileFullName = imageURL.lastPathComponent as NSString
if let match = ImageCacheManager.regularExpression.firstMatch(in: fileFullName as String, options: .init(rawValue: 0), range: NSMakeRange(0, fileFullName.length)) {
let fileExt = fileFullName.substring(with: match.range)
return imageURL.absoluteString.md5 + fileExt
}
return imageURL.absoluteString.md5 + ".img"
}
/// 缓存指定 URL 对应的图片数据。
///
/// - Parameters:
/// - imageData: 图片数据。
/// - imageURL: 图片地址。
/// - Returns: 是否缓存成功。
@discardableResult
@objc(cacheImageData:forImageURL:)
public func cache(_ imageData: Data?, for imageURL: URL) -> Bool {
return setData(imageData, forIdentifier: self.identifier(for: imageURL))
}
@objc(imageForImageURL:)
public func image(for imageURL: URL) -> UIImage? {
let identifier = self.identifier(for: imageURL)
guard let imageData = self.data(forIdentifier: identifier) else { return nil }
return UIImage.init(data: imageData)
}
}
|
mit
|
022b1f269c1af0ffa0aa35828a8866bb
| 33.324074 | 172 | 0.642568 | 4.15583 | false | false | false | false |
peaks-cc/iOS11_samplecode
|
chapter_02/05_FeaturePoints/ARFeaturePoints/ViewController.swift
|
1
|
4329
|
//
// ViewController.swift
// ARTapeMeasure
//
// Created by Shuichi Tsutsumi on 2017/07/17.
// Copyright © 2017 Shuichi Tsutsumi. All rights reserved.
//
import UIKit
import SceneKit
import ARKit
class ViewController: UIViewController, ARSessionDelegate {
private var hitPointNode: SCNNode?
@IBOutlet var sceneView: ARSCNView!
@IBOutlet var statusLabel: UILabel!
@IBOutlet var resultLabel: UILabel!
@IBOutlet var resetBtn: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.session.delegate = self
// シーンを生成してARSCNViewにセット
sceneView.scene = SCNScene()
// セッションのコンフィギュレーションを生成
let configuration = ARWorldTrackingConfiguration()
configuration.planeDetection = .horizontal
configuration.isLightEstimationEnabled = true
// 特徴量を可視化
sceneView.debugOptions = [ARSCNDebugOptions.showFeaturePoints]
// セッション開始
sceneView.session.run(configuration)
}
// MARK: - ARSessionDelegate
func session(_ session: ARSession, didUpdate frame: ARFrame) {
guard let pointCloud = frame.rawFeaturePoints else {
return
}
statusLabel.text = "feature points: \(pointCloud.__count)"
// for index in 0..<pointCloud.__count {
// let identifier = pointCloud.identifiers[index] // UInt64
// let point = pointCloud.points[index] // vector_float3
// // do something with point
// }
}
func session(_ session: ARSession, didAdd anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
}
func session(_ session: ARSession, didUpdate anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
}
func session(_ session: ARSession, didRemove anchors: [ARAnchor]) {
print("\(self.classForCoder)/" + #function)
}
// MARK: - ARSessionObserver
func session(_ session: ARSession, cameraDidChangeTrackingState camera: ARCamera) {
print("trackingState: \(camera.trackingState)")
statusLabel.text = camera.trackingState.description
}
// MARK: - Private
private func putSphere(at pos: SCNVector3, color: UIColor) -> SCNNode {
let node = SCNNode.sphereNode(color: color)
sceneView.scene.rootNode.addChildNode(node)
node.position = pos
return node
}
private func arkitHitTest(_ pos: CGPoint) {
// 特徴点と平面を対象にヒットテストを実行
let results = sceneView.hitTest(pos, types: [.featurePoint, .existingPlane])
// 最も近い(手前にある)結果を取得
guard let result = results.first else {
resultLabel.text = "no hit"
return
}
// ヒットした位置を計算する
let pos = result.worldTransform.position()
// ノードを置く
if let hitPointNode = hitPointNode {
hitPointNode.removeFromParentNode()
}
hitPointNode = SCNNode.sphereNode(color: UIColor.green)
hitPointNode?.position = pos
sceneView.scene.rootNode.addChildNode(hitPointNode!)
// 結果のタイプの判定
switch result.type {
case .featurePoint:
// 特徴点へのヒット
print(result.anchor as Any) // 特徴点にはアンカーはないのでnilになる
case .existingPlane:
// 検出済み平面へのヒット
print(result.anchor as Any) // ヒットした平面のアンカーが得られる
default:
break
}
resultLabel.text = result.type == .featurePoint ? "Feature Point" : "Plane"
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
// タップ位置のスクリーン座標を取得
guard let touch = touches.first else {return}
let pos = touch.location(in: sceneView)
arkitHitTest(pos)
}
@IBAction func resetBtnTapped(_ sender: UIButton) {
hitPointNode?.removeFromParentNode()
}
}
|
mit
|
9c4ce239427bff3ad5dc54905d3f073e
| 28.879699 | 87 | 0.608958 | 4.371837 | false | false | false | false |
jbrayton/Golden-Hill-HTTP-Library
|
GoldenHillHTTPLibrary/PinningURLSessionDelegate.swift
|
1
|
3312
|
//
// PinningURLSessionDelegate.swift
// GoldenHillHTTPLibrary
//
// Created by John Brayton on 3/8/17.
// Copyright © 2017 John Brayton. All rights reserved.
//
import Foundation
@objc
public class PinningURLSessionDelegate: SimpleURLSessionDelegate {
let publicKeyHashes: [String]
/*
The certificateUrls should be an array of URL objects from the app bundle. The certificates
must be in DER format.
*/
@objc
public init( followRedirects: Bool, publicKeyHashes: [String] ) {
self.publicKeyHashes = publicKeyHashes
let followRedirectsEnum: FollowRedirects = followRedirects ? FollowRedirects.always : FollowRedirects.never
super.init(followRedirects: followRedirectsEnum)
}
public init( followRedirects: FollowRedirects, publicKeyHashes: [String] ) {
self.publicKeyHashes = publicKeyHashes
super.init(followRedirects: followRedirects)
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void) {
// Adapted from OWASP https://www.owasp.org/index.php/Certificate_and_Public_Key_Pinning#iOS
if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
if let serverTrust = challenge.protectionSpace.serverTrust {
let isServerTrusted = SecTrustEvaluateWithError(serverTrust, nil)
if(isServerTrusted) {
if let serverCertificate = SecTrustGetCertificateAtIndex(serverTrust, 0) {
// Server public key
let serverPublicKey = SecCertificateCopyKey(serverCertificate)
let serverPublicKeyData = SecKeyCopyExternalRepresentation(serverPublicKey!, nil )!
let data:Data = serverPublicKeyData as Data
// Server Hash key
let serverHashKey = sha256(data: data)
// Local Hash Key
if (self.publicKeyHashes.contains(where: { (str) -> Bool in
str == serverHashKey
})) {
// Success! This is our server
completionHandler(.useCredential, URLCredential(trust:serverTrust))
return
}
}
}
}
}
// Pinning failed
completionHandler(URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
let rsa2048Asn1Header:[UInt8] = [
0x30, 0x82, 0x01, 0x22, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86,
0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x82, 0x01, 0x0f, 0x00
]
private func sha256(data : Data) -> String {
var keyWithHeader = Data(rsa2048Asn1Header)
keyWithHeader.append(data)
var hash = [UInt8](repeating: 0, count: Int(CC_SHA256_DIGEST_LENGTH))
_ = keyWithHeader.withUnsafeBytes { (ptr: UnsafeRawBufferPointer) -> Void in
_ = CC_SHA256(ptr.baseAddress, CC_LONG(keyWithHeader.count), &hash)
}
return Data(hash).base64EncodedString()
}
}
|
mit
|
94e286d5065a49f107ffd94fb2bcad85
| 40.3875 | 192 | 0.620054 | 4.777778 | false | false | false | false |
CD1212/Doughnut
|
Pods/GRDB.swift/GRDB/Core/DatabaseReader.swift
|
1
|
10054
|
#if SWIFT_PACKAGE
import CSQLite
#elseif !GRDBCUSTOMSQLITE && !GRDBCIPHER
import SQLite3
#endif
/// The protocol for all types that can fetch values from a database.
///
/// It is adopted by DatabaseQueue and DatabasePool.
///
/// The protocol comes with isolation guarantees that describe the behavior of
/// adopting types in a multithreaded application.
///
/// Types that adopt the protocol can provide in practice stronger guarantees.
/// For example, DatabaseQueue provides a stronger isolation level
/// than DatabasePool.
///
/// **Warning**: Isolation guarantees stand as long as there is no external
/// connection to the database. Should you have to cope with external
/// connections, protect yourself with transactions, and be ready to setup a
/// [busy handler](https://www.sqlite.org/c3ref/busy_handler.html).
public protocol DatabaseReader : class {
// MARK: - Read From Database
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// Guarantee 1: the block argument is isolated. Eventual concurrent
/// database updates are not visible inside the block:
///
/// try reader.read { db in
/// // Those two values are guaranteed to be equal, even if the
/// // `wines` table is modified between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// try reader.read { db in
/// // Now this value may be different:
/// let count = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Guarantee 2: Starting iOS 8.2, OSX 10.10, and with custom SQLite builds
/// and SQLCipher, attempts to write in the database throw a DatabaseError
/// whose resultCode is `SQLITE_READONLY`.
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
func read<T>(_ block: (Database) throws -> T) throws -> T
/// Synchronously executes a read-only block that takes a database
/// connection, and returns its result.
///
/// The two guarantees of the safe `read` method are lifted:
///
/// The block argument is not isolated: eventual concurrent database updates
/// are visible inside the block:
///
/// try reader.unsafeRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
/// The block argument is not prevented from writing (DatabaseQueue, in
/// particular, will accept database modifications in `unsafeRead`).
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T
/// Synchronously executes a block that takes a database connection, and
/// returns its result.
///
/// The two guarantees of the safe `read` method are lifted:
///
/// The block argument is not isolated: eventual concurrent database updates
/// are visible inside the block:
///
/// try reader.unsafeReentrantRead { db in
/// // Those two values may be different because some other thread
/// // may have inserted or deleted a wine between the two requests:
/// let count1 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// let count2 = try Int.fetchOne(db, "SELECT COUNT(*) FROM wines")!
/// }
///
/// Cursor iterations are isolated, though:
///
/// try reader.unsafeReentrantRead { db in
/// // No concurrent update can mess with this iteration:
/// let rows = try Row.fetchCursor(db, "SELECT ...")
/// while let row = try rows.next() { ... }
/// }
///
/// The block argument is not prevented from writing (DatabaseQueue, in
/// particular, will accept database modifications in `unsafeReentrantRead`).
///
/// - parameter block: A block that accesses the database.
/// - throws: The error thrown by the block, or any DatabaseError that would
/// happen while establishing the read access to the database.
///
/// This method is reentrant. It should be avoided because it fosters
/// dangerous concurrency practices.
func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T
// MARK: - Functions
/// Add or redefine an SQL function.
///
/// let fn = DatabaseFunction("succ", argumentCount: 1) { dbValues in
/// guard let int = Int.fromDatabaseValue(dbValues[0]) else {
/// return nil
/// }
/// return int + 1
/// }
/// reader.add(function: fn)
/// try reader.read { db in
/// try Int.fetchOne(db, "SELECT succ(1)")! // 2
/// }
func add(function: DatabaseFunction)
/// Remove an SQL function.
func remove(function: DatabaseFunction)
// MARK: - Collations
/// Add or redefine a collation.
///
/// let collation = DatabaseCollation("localized_standard") { (string1, string2) in
/// return (string1 as NSString).localizedStandardCompare(string2)
/// }
/// reader.add(collation: collation)
/// try reader.execute("SELECT * FROM files ORDER BY name COLLATE localized_standard")
func add(collation: DatabaseCollation)
/// Remove a collation.
func remove(collation: DatabaseCollation)
}
extension DatabaseReader {
// MARK: - Backup
/// Copies the database contents into another database.
///
/// The `backup` method blocks the current thread until the destination
/// database contains the same contents as the source database.
///
/// When the source is a DatabasePool, concurrent writes can happen during
/// the backup. Those writes may, or may not, be reflected in the backup,
/// but they won't trigger any error.
public func backup(to writer: DatabaseWriter) throws {
try backup(to: writer, afterBackupInit: nil, afterBackupStep: nil)
}
func backup(to writer: DatabaseWriter, afterBackupInit: (() -> ())?, afterBackupStep: (() -> ())?) throws {
try read { dbFrom in
try writer.write { dbDest in
guard let backup = sqlite3_backup_init(dbDest.sqliteConnection, "main", dbFrom.sqliteConnection, "main") else {
throw DatabaseError(resultCode: dbDest.lastErrorCode, message: dbDest.lastErrorMessage)
}
guard Int(bitPattern: backup) != Int(SQLITE_ERROR) else {
throw DatabaseError(resultCode: .SQLITE_ERROR)
}
afterBackupInit?()
do {
backupLoop: while true {
switch sqlite3_backup_step(backup, -1) {
case SQLITE_DONE:
afterBackupStep?()
break backupLoop
case SQLITE_OK:
afterBackupStep?()
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
}
} catch {
sqlite3_backup_finish(backup)
throw error
}
switch sqlite3_backup_finish(backup) {
case SQLITE_OK:
break
case let code:
throw DatabaseError(resultCode: code, message: dbDest.lastErrorMessage)
}
dbDest.clearSchemaCache()
}
}
}
}
/// A type-erased DatabaseReader
///
/// Instances of AnyDatabaseReader forward their methods to an arbitrary
/// underlying database reader.
public final class AnyDatabaseReader : DatabaseReader {
private let base: DatabaseReader
/// Creates a database reader that wraps a base database reader.
public init(_ base: DatabaseReader) {
self.base = base
}
// MARK: - Reading from Database
public func read<T>(_ block: (Database) throws -> T) throws -> T {
return try base.read(block)
}
public func unsafeRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeRead(block)
}
public func unsafeReentrantRead<T>(_ block: (Database) throws -> T) throws -> T {
return try base.unsafeReentrantRead(block)
}
// MARK: - Functions
public func add(function: DatabaseFunction) {
base.add(function: function)
}
public func remove(function: DatabaseFunction) {
base.remove(function: function)
}
// MARK: - Collations
public func add(collation: DatabaseCollation) {
base.add(collation: collation)
}
public func remove(collation: DatabaseCollation) {
base.remove(collation: collation)
}
}
|
gpl-3.0
|
4b5a458148d33ce0eac3675559d9a13e
| 38.120623 | 127 | 0.590611 | 4.792183 | false | false | false | false |
zhugejunwei/LeetCode
|
120. Triangle.swift
|
1
|
2150
|
import Darwin
// First Version
//func minimumTotal(triangle: [[Int]]) -> Int {
// var myT = triangle
// for row in 0..<triangle.count {
// for col in 0..<triangle[row].count {
// if row > 0 {
// if col == 0 {
// myT[row][0] += myT[row-1][0]
// }else if col == triangle[row].count-1 {
// myT[row][triangle[row].count-1] += myT[row-1][triangle[row].count-2]
// }else {
// myT[row][col] += min(myT[row-1][col-1], myT[row-1][col])
// }
// }
// }
// }
// return myT[myT.count-1].minElement()!
//}
// Updated Version
//func minimumTotal(triangle: [[Int]]) -> Int {
// var myT = Array(count: triangle.count, repeatedValue: 0)
// var pre = Array(count: triangle.count, repeatedValue: 0)
// myT[0] = triangle[0][0]
// pre[0] = triangle[0][0]
// for row in 1..<triangle.count {
// for col in 0..<triangle[row].count {
// if col == 0 {
// myT[0] = triangle[row][0] + pre[0]
// }else if col == triangle[row].count-1 {
// myT[triangle[row].count-1] = triangle[row][triangle[row].count-1] + pre[triangle[row].count-2]
// }else {
// myT[col] = triangle[row][col] + min(pre[col-1], pre[col])
// }
// }
// swap(&myT, &pre)
// }
// return pre.minElement()!
//}
// Optimized Version, O(n) extra space
func minimumTotal(triangle: [[Int]]) -> Int {
var myT = triangle[triangle.count-1]
var row = triangle.count - 2
while row >= 0 {
for col in 0...row {
myT[col] = triangle[row][col] + min(myT[col],myT[col+1])
}
row -= 1
}
return myT[0]
}
//var a = [[2],[3,4],[6,5,7],[4,1,8,3]]
var a = [[-7],[-2,1],[-5,-5,9],[-4,-5,4,4],[-6,-6,2,-1,-5],[3,7,8,-3,7,-9],[-9,-1,-9,6,9,0,7],[-7,0,-6,-8,7,1,-4,9],[-3,2,-6,-9,-7,-6,-9,4,0],[-8,-6,-3,-9,-2,-6,7,-5,0,7],[-9,-1,-2,4,-2,4,4,-1,2,-5,5],[1,1,-6,1,-2,-4,4,-2,6,-6,0,6],[-3,-3,-6,-2,-6,-2,7,-9,-5,-7,-5,5,1]]
// -63
//var a = [[-1],[2,3],[1,-1,-3]]
minimumTotal(a)
|
mit
|
040a0ed09c932a7eb7aad5172a0097c9
| 30.15942 | 270 | 0.45814 | 2.599758 | false | false | false | false |
vector-im/vector-ios
|
Riot/Utils/UserNameColorGenerator.swift
|
1
|
1762
|
/*
Copyright 2019 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 UIKit
/// Generate a user name color from user id
@objcMembers
final class UserNameColorGenerator: NSObject {
// MARK: - Properties
/// User name colors.
var userNameColors: [UIColor] = []
/// Fallback color when `userNameColors` is empty.
var defaultColor: UIColor = .black
// MARK: - Public
/// Generate a user name color from the user ID.
///
/// - Parameter userId: The user ID of the user.
/// - Returns: A color associated to the user ID.
func color(from userId: String) -> UIColor {
guard self.userNameColors.isEmpty == false else {
return self.defaultColor
}
guard userId.isEmpty == false else {
return self.userNameColors[0]
}
let senderNameColorIndex = Int(userId.vc_hashCode % Int32(self.userNameColors.count))
return self.userNameColors[senderNameColorIndex]
}
}
// MARK: - Themable
extension UserNameColorGenerator: Themable {
func update(theme: Theme) {
self.defaultColor = theme.colors.primaryContent
self.userNameColors = theme.colors.namesAndAvatars
}
}
|
apache-2.0
|
68fdc0438346701a8f9ca718343d0d60
| 28.864407 | 93 | 0.678207 | 4.552972 | false | false | false | false |
manfengjun/KYMart
|
Section/Product/Detail/Controller/CartUtil.swift
|
1
|
1488
|
//
// CartUtil.swift
// KYMart
//
// Created by jun on 2017/6/14.
// Copyright © 2017年 JUN. All rights reserved.
//
import UIKit
class CartUtil: NSObject {
class func returnAddParams() -> [String:AnyObject]{
let goods_id = SingleManager.instance.productBuyInfoModel?.good_buy_id
let goods_num = SingleManager.instance.productBuyInfoModel?.good_buy_count
let goods_spec = NSMutableArray()
if let array = SingleManager.instance.productBuyInfoModel?.good_buy_propertys
{
if array.count > 0{
for item in array{
goods_spec.add("\(item.good_buy_spec_list.item_id)")
}
return ["goods_num": String(goods_num!) as AnyObject, "goods_spec": goods_spec, "goods_id": String(goods_id!) as AnyObject]
}
}
return ["goods_num": String(goods_num!) as AnyObject, "goods_id": String(goods_id!) as AnyObject]
}
class func addCart(completion:@escaping (Bool) -> Void) {
let params = returnAddParams()
SJBRequestModel.push_fetchAddCartProductData(params: params as [String : AnyObject], completion: { (response, status) in
if status == 1{
self.Toast(content: "添加成功!")
completion(true)
}
else
{
self.Toast(content: response as! String)
completion(false)
}
})
}
}
|
mit
|
cfa39f42c0de39f4ec96fd0783223642
| 33.302326 | 139 | 0.568136 | 4.190341 | false | false | false | false |
davidbjames/Uniview
|
Pods/Anchorage/Source/Anchorage.swift
|
1
|
17449
|
//
// Anchorage.swift
// Anchorage
//
// Created by Rob Visentin on 2/6/16.
//
// Copyright 2016 Raizlabs and other contributors
// http://raizlabs.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.
#if os(macOS)
import Cocoa
#else
import UIKit
#endif
public protocol LayoutConstantType {}
extension CGFloat: LayoutConstantType {}
extension CGSize: LayoutConstantType {}
extension EdgeInsets: LayoutConstantType {}
public protocol LayoutAnchorType {}
extension NSLayoutAnchor: LayoutAnchorType {}
// MARK: - Equality Constraints
@discardableResult public func == <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalToConstant: CGFloat(rhs)))
}
@discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalTo: rhs))
}
@discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalTo: rhs))
}
@discardableResult public func == (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalTo: rhs))
}
@discardableResult public func == (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func == (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(equalTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func == (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint {
if let anchor = rhs.anchor {
return finalize(constraint: lhs.constraint(equalTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority)
}
else {
return finalize(constraint: lhs.constraint(equalToConstant: rhs.constant), withPriority: rhs.priority)
}
}
@discardableResult public func == (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup {
return lhs.finalize(constraintsEqualToEdges: rhs)
}
@discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup {
return lhs.finalize(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func == (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup {
return lhs.finalize(constraintsEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority)
}
@discardableResult public func == <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair {
return lhs.finalize(constraintsEqualToEdges: rhs)
}
@discardableResult public func == <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair {
return lhs.finalize(constraintsEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func == (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair {
return lhs.finalize(constraintsEqualToConstant: rhs)
}
@discardableResult public func == (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair {
return lhs.finalize(constraintsEqualToConstant: rhs.constant, priority: rhs.priority)
}
// MARK: - Inequality Constraints
@discardableResult public func <= <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualToConstant: CGFloat(rhs)))
}
@discardableResult public func <= (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs))
}
@discardableResult public func <= (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs))
}
@discardableResult public func <= (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs))
}
@discardableResult public func <= (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func <= (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func <= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint {
if let anchor = rhs.anchor {
return finalize(constraint: lhs.constraint(lessThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority)
}
else {
return finalize(constraint: lhs.constraint(lessThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority)
}
}
@discardableResult public func <= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup {
return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs)
}
@discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup {
return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func <= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup {
return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority)
}
@discardableResult public func <= <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair {
return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs)
}
@discardableResult public func <= <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair {
return lhs.finalize(constraintsLessThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func <= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair {
return lhs.finalize(constraintsLessThanOrEqualToConstant: rhs)
}
@discardableResult public func <= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair {
return lhs.finalize(constraintsLessThanOrEqualToConstant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func >= <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualToConstant: CGFloat(rhs)))
}
@discardableResult public func >= (lhs: NSLayoutXAxisAnchor, rhs: NSLayoutXAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs))
}
@discardableResult public func >= (lhs: NSLayoutYAxisAnchor, rhs: NSLayoutYAxisAnchor) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs))
}
@discardableResult public func >= (lhs: NSLayoutDimension, rhs: NSLayoutDimension) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs))
}
@discardableResult public func >= (lhs: NSLayoutXAxisAnchor, rhs: LayoutExpression<NSLayoutXAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func >= (lhs: NSLayoutYAxisAnchor, rhs: LayoutExpression<NSLayoutYAxisAnchor, CGFloat>) -> NSLayoutConstraint {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: rhs.anchor!, constant: rhs.constant), withPriority: rhs.priority)
}
@discardableResult public func >= (lhs: NSLayoutDimension, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> NSLayoutConstraint {
if let anchor = rhs.anchor {
return finalize(constraint: lhs.constraint(greaterThanOrEqualTo: anchor, multiplier: rhs.multiplier, constant: rhs.constant), withPriority: rhs.priority)
}
else {
return finalize(constraint: lhs.constraint(greaterThanOrEqualToConstant: rhs.constant), withPriority: rhs.priority)
}
}
@discardableResult public func >= (lhs: EdgeAnchors, rhs: EdgeAnchors) -> ConstraintGroup {
return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs)
}
@discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, CGFloat>) -> ConstraintGroup {
return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func >= (lhs: EdgeAnchors, rhs: LayoutExpression<EdgeAnchors, EdgeInsets>) -> ConstraintGroup {
return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, insets: rhs.constant, priority: rhs.priority)
}
@discardableResult public func >= <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: AnchorPair<T, U>) -> ConstraintPair {
return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs)
}
@discardableResult public func >= <T: LayoutAnchorType, U: LayoutAnchorType>(lhs: AnchorPair<T, U>, rhs: LayoutExpression<AnchorPair<T, U>, CGFloat>) -> ConstraintPair {
return lhs.finalize(constraintsGreaterThanOrEqualToEdges: rhs.anchor, constant: rhs.constant, priority: rhs.priority)
}
@discardableResult public func >= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: CGSize) -> ConstraintPair {
return lhs.finalize(constraintsGreaterThanOrEqualToConstant: rhs)
}
@discardableResult public func >= (lhs: AnchorPair<NSLayoutDimension, NSLayoutDimension>, rhs: LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize>) -> ConstraintPair {
return lhs.finalize(constraintsGreaterThanOrEqualToConstant: rhs.constant, priority: rhs.priority)
}
// MARK: - Priority
precedencegroup PriorityPrecedence {
associativity: none
higherThan: ComparisonPrecedence
lowerThan: AdditionPrecedence
}
infix operator ~: PriorityPrecedence
@discardableResult public func ~ <T: BinaryFloatingPoint>(lhs: T, rhs: Priority) -> LayoutExpression<NSLayoutDimension, CGFloat> {
return LayoutExpression(constant: CGFloat(lhs), priority: rhs)
}
@discardableResult public func ~ (lhs: CGSize, rhs: Priority) -> LayoutExpression<AnchorPair<NSLayoutDimension, NSLayoutDimension>, CGSize> {
return LayoutExpression(constant: lhs, priority: rhs)
}
@discardableResult public func ~ <T: LayoutAnchorType>(lhs: T, rhs: Priority) -> LayoutExpression<T, CGFloat> {
return LayoutExpression(anchor: lhs, constant: 0.0, priority: rhs)
}
@discardableResult public func ~ <T: LayoutAnchorType, U: LayoutConstantType>(lhs: LayoutExpression<T, U>, rhs: Priority) -> LayoutExpression<T, U> {
var expr = lhs
expr.priority = rhs
return expr
}
@discardableResult public func * <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> {
return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: CGFloat(rhs))
}
@discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: NSLayoutDimension) -> LayoutExpression<NSLayoutDimension, CGFloat> {
return LayoutExpression(anchor: rhs, constant: 0.0, multiplier: CGFloat(lhs))
}
@discardableResult public func * <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutDimension, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> {
var expr = lhs
expr.multiplier *= CGFloat(rhs)
return expr
}
@discardableResult public func * <T: BinaryFloatingPoint>(lhs: T, rhs: LayoutExpression<NSLayoutDimension, CGFloat>) -> LayoutExpression<NSLayoutDimension, CGFloat> {
var expr = rhs
expr.multiplier *= CGFloat(lhs)
return expr
}
@discardableResult public func / <T: BinaryFloatingPoint>(lhs: NSLayoutDimension, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> {
return LayoutExpression(anchor: lhs, constant: 0.0, multiplier: 1.0 / CGFloat(rhs))
}
@discardableResult public func / <T: BinaryFloatingPoint>(lhs: LayoutExpression<NSLayoutDimension, CGFloat>, rhs: T) -> LayoutExpression<NSLayoutDimension, CGFloat> {
var expr = lhs
expr.multiplier /= CGFloat(rhs)
return expr
}
@discardableResult public func + <T: LayoutAnchorType, U: BinaryFloatingPoint>(lhs: T, rhs: U) -> LayoutExpression<T, CGFloat> {
return LayoutExpression(anchor: lhs, constant: CGFloat(rhs))
}
@discardableResult public func + <T: BinaryFloatingPoint, U: LayoutAnchorType>(lhs: T, rhs: U) -> LayoutExpression<U, CGFloat> {
return LayoutExpression(anchor: rhs, constant: CGFloat(lhs))
}
@discardableResult public func + <T: LayoutAnchorType, U: BinaryFloatingPoint>(lhs: LayoutExpression<T, CGFloat>, rhs: U) -> LayoutExpression<T, CGFloat> {
var expr = lhs
expr.constant += CGFloat(rhs)
return expr
}
@discardableResult public func + <T: BinaryFloatingPoint, U: LayoutAnchorType>(lhs: T, rhs: LayoutExpression<U, CGFloat>) -> LayoutExpression<U, CGFloat> {
var expr = rhs
expr.constant += CGFloat(lhs)
return expr
}
@discardableResult public func + (lhs: EdgeAnchors, rhs: EdgeInsets) -> LayoutExpression<EdgeAnchors, EdgeInsets> {
return LayoutExpression(anchor: lhs, constant: rhs)
}
@discardableResult public func - <T: LayoutAnchorType, U: BinaryFloatingPoint>(lhs: T, rhs: U) -> LayoutExpression<T, CGFloat> {
return LayoutExpression(anchor: lhs, constant: -CGFloat(rhs))
}
@discardableResult public func - <T: BinaryFloatingPoint, U: LayoutAnchorType>(lhs: T, rhs: U) -> LayoutExpression<U, CGFloat> {
return LayoutExpression(anchor: rhs, constant: -CGFloat(lhs))
}
@discardableResult public func - <T: LayoutAnchorType, U: BinaryFloatingPoint>(lhs: LayoutExpression<T, CGFloat>, rhs: U) -> LayoutExpression<T, CGFloat> {
var expr = lhs
expr.constant -= CGFloat(rhs)
return expr
}
@discardableResult public func - <T: BinaryFloatingPoint, U: LayoutAnchorType>(lhs: T, rhs: LayoutExpression<U, CGFloat>) -> LayoutExpression<U, CGFloat> {
var expr = rhs
expr.constant -= CGFloat(lhs)
return expr
}
@discardableResult public func - (lhs: EdgeAnchors, rhs: EdgeInsets) -> LayoutExpression<EdgeAnchors, EdgeInsets> {
return LayoutExpression(anchor: lhs, constant: -rhs)
}
// MARK: - Batching
/// Any Anchorage constraints created inside the passed closure are returned in the array.
///
/// - Precondition: Can't be called inside or simultaneously with another batch. Batches cannot be nested.
/// - Parameter closure: A closure that runs some Anchorage expressions.
/// - Returns: An array of new, active `NSLayoutConstraint`s.
@discardableResult public func batch(_ closure: () -> Void) -> [NSLayoutConstraint] {
return batch(active: true, closure: closure)
}
/// Any Anchorage constraints created inside the passed closure are returned in the array.
///
/// - Precondition: Can't be called inside or simultaneously with another batch. Batches cannot be nested.
/// - Parameter active: Whether the created constraints should be active when they are returned.
/// - Parameter closure: A closure that runs some Anchorage expressions.
/// - Returns: An array of new `NSLayoutConstraint`s.
public func batch(active: Bool, closure: () -> Void) -> [NSLayoutConstraint] {
precondition(currentBatch == nil)
defer {
currentBatch = nil
}
let batch = ConstraintBatch()
currentBatch = batch
closure()
if active {
batch.activate()
}
return batch.constraints
}
|
mit
|
a447d922d1320349bce3a3bdb9a4db36
| 46.287263 | 190 | 0.760559 | 4.730008 | false | false | false | false |
PumpMagic/ostrich
|
gameboy/gameboy/Source/CPUs/Instructions/RES.swift
|
1
|
590
|
//
// RES.swift
// ostrichframework
//
// Created by Ryan Conway on 4/21/16.
// Copyright © 2016 Ryan Conway. All rights reserved.
//
import Foundation
/// Reset a given bit of an operand
struct RES
<T: Readable & Writeable & OperandType>: Z80Instruction, LR35902Instruction where T.ReadType == UInt8, T.WriteType == T.ReadType
{
let op: T
let bit: UInt8
let cycleCount = 0
func runOn(_ cpu: Z80) {
op.write(clearBit(op.read(), bit: bit))
}
func runOn(_ cpu: LR35902) {
op.write(clearBit(op.read(), bit: bit))
}
}
|
mit
|
924cc33d3c706547c15ceb5b54936463
| 19.310345 | 132 | 0.60781 | 3.254144 | false | false | false | false |
jegumhon/URWeatherView
|
URWeatherView/Filter/URRippleFilter.swift
|
1
|
2433
|
//
// URRippleFilter.swift
// URWeatherView
//
// Created by DongSoo Lee on 2017. 6. 8..
// Copyright © 2017년 zigbang. All rights reserved.
//
import Foundation
let URKernelShaderkRipple: String = "URKernelShaderRipple.cikernel.fsh"
open class URRippleFilter: URFilter {
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
/**
Initialize CIFilter with **CGImage** and CIKernel shader params
- parameters:
- frame: The frame rectangle for the input image, measured in points.
- cgImage: Core Image of the input image
- inputValues: attributes for CIKernel. The format is like below.
[sampler: CISampler, time: TimeInterval]
*/
required public init(frame: CGRect, cgImage: CGImage, inputValues: [Any]) {
super.init(frame: frame, cgImage: cgImage, inputValues: inputValues)
self.loadCIKernel(from: URKernelShaderkRipple)
guard inputValues.count == 2 else { return }
self.customAttributes = inputValues
}
/**
Initialize CIFilter with **CGImage** and CIKernel shader params
- parameters:
- frame: The frame rectangle for the input image, measured in points.
- imageView: The UIImageView of the input image
- inputValues: attributes for CIKernel. The format is like below.
[sampler: CISampler, time: TimeInterval]
*/
required public init(frame: CGRect, imageView: UIImageView, inputValues: [Any]) {
super.init(frame: frame, imageView: imageView, inputValues: inputValues)
self.loadCIKernel(from: URKernelShaderkRipple)
guard inputValues.count == 2 else { return }
self.customAttributes = inputValues
}
override func applyFilter() -> CIImage {
let samplerROI = CGRect(x: 0, y: 0, width: self.inputImage!.extent.width, height: self.inputImage!.extent.height)
let ROICallback: (Int32, CGRect) -> CGRect = { (samplerIndex, destination) in
if samplerIndex == 2 {
return samplerROI
}
return destination
}
guard let resultImage: CIImage = self.customKernel?.apply(extent: self.extent, roiCallback: ROICallback, arguments: self.customAttributes!) else {
fatalError("Filtered Image merging is failed!!")
}
return resultImage
}
}
|
mit
|
610ce87587c0b6f4e079f5bc9a5fbe87
| 34.735294 | 154 | 0.652675 | 4.533582 | false | false | false | false |
MetalPetal/MetalPetal
|
Utilities/Sources/BoilerplateGenerator/BoilerplateGenerator.swift
|
1
|
2005
|
//
// File.swift
//
//
// Created by YuAo on 2020/3/16.
//
import Foundation
import ArgumentParser
import URLExpressibleByArgument
import MetalPetalSourceLocator
public struct BoilerplateGenerator: ParsableCommand {
@Argument(help: "The root directory of the MetalPetal repo.")
var projectRoot: URL
enum CodingKeys: CodingKey {
case projectRoot
}
private let fileManager = FileManager()
public init() { }
public func run() throws {
// Sources
let blendModes = ["Normal","Darken","Multiply","ColorBurn","LinearBurn","DarkerColor","Lighten","Screen","ColorDodge","Add","LighterColor","Overlay","SoftLight","HardLight","VividLight","LinearLight","PinLight","HardMix", "Difference", "Exclusion", "Subtract", "Divide","Hue","Saturation","Color", "Luminosity"]
let sourceDirectory = MetalPetalSourcesRootURL(in: projectRoot)
let shadersFileDirectory = sourceDirectory.appendingPathComponent("Shaders")
for (file, content) in MTIVectorSIMDTypeSupportCodeGenerator.generate() {
let url = sourceDirectory.appendingPathComponent(file)
try! content.write(to: url, atomically: true, encoding: .utf8)
}
for (file, content) in MetalPetalBlendingShadersCodeGenerator.generate(blendModes: blendModes) {
let url = shadersFileDirectory.appendingPathComponent(file)
try! content.write(to: url, atomically: true, encoding: .utf8)
}
for (file, content) in MTISIMDShaderArgumentEncoderGenerator.generate() {
let url = sourceDirectory.appendingPathComponent(file)
try! content.write(to: url, atomically: true, encoding: .utf8)
}
for (file, content) in BlendFormulaSupport.generateBlendFormulaSupportFiles(sourceDirectory: sourceDirectory) {
let url = sourceDirectory.appendingPathComponent(file)
try! content.write(to: url, atomically: true, encoding: .utf8)
}
}
}
|
mit
|
489634ba570e33787b39e04f7ab2a64c
| 40.770833 | 319 | 0.681297 | 4.641204 | false | false | false | false |
gtranchedone/NFYU
|
NFYU/LocationInfo.swift
|
1
|
679
|
//
// LocationInfo.swift
// NFYU
//
// Created by Gianluca Tranchedone on 06/11/2015.
// Copyright © 2015 Gianluca Tranchedone. All rights reserved.
//
import Foundation
struct LocationInfo: Equatable {
let id: String?
let name: String?
let city: String?
let state: String?
let country: String?
init(id: String? = nil, name: String? = nil, city: String? = nil, state: String? = nil, country: String? = nil) {
self.id = id
self.name = name
self.city = city
self.state = state
self.country = country
}
}
func ==(lhs: LocationInfo, rhs: LocationInfo) -> Bool {
return lhs.id == rhs.id
}
|
mit
|
d409b074f2d76c87e849edf32d52d9dd
| 20.870968 | 117 | 0.600295 | 3.684783 | false | false | false | false |
WSDOT/wsdot-ios-app
|
wsdot/VesselItem.swift
|
2
|
2137
|
//
// VesselItem.swift
// WSDOT
//
// Copyright (c) 2016 Washington State Department of Transportation
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>
//
import Foundation
import UIKit
class VesselItem {
let vesselID: Int
let vesselName: String
let inService: Bool
fileprivate let directions = ["N", "NxE", "E", "SxE", "S", "SxW", "W", "NxW", "N"]
var headText: String {
get {
return directions[Int(round(((Double(heading).truncatingRemainder(dividingBy: 360)) / 45)))]
}
}
var icon: UIImage {
get {
return UIImage(named: "ferry" + String( (heading + 30 / 2) / 30 * 30))!// round heading to nearest 30 degrees
}
}
let heading: Int
let lat: Double
let lon: Double
let speed: Float
let updateTime: Date
var route: String = "Not available"
var arrivingTerminal = "Not available"
var departingTerminal = "Not available"
var arrivingTerminalID = -1
var departingTerminalID = -1
var nextDeparture: Date? = nil
var leftDock: Date? = nil
var eta: Date? = nil
var atDock: Bool = true
init(id: Int, name: String, lat: Double, lon: Double, heading: Int, speed: Float, inService: Bool, updated: Date) {
self.vesselName = name
self.vesselID = id
self.lat = lat
self.lon = lon
self.heading = heading
self.speed = speed
self.inService = inService
self.updateTime = updated
}
}
|
gpl-3.0
|
c2d478ade5fd2fc9749b850ce2f7869c
| 28.680556 | 121 | 0.633599 | 3.994393 | false | false | false | false |
itechline/bonodom_new
|
SlideMenuControllerSwift/BookingUtil.swift
|
1
|
4712
|
//
// BookingUtil.swift
// Bonodom
//
// Created by Attila Dán on 2016. 07. 15..
// Copyright © 2016. Itechline. All rights reserved.
//
import Foundation
import SwiftyJSON
class BookingUtil: NSObject {
static let sharedInstance = BookingUtil()
let baseURL = "https://bonodom.com/api/"
func get_idoponts(id: Int, onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let id_post = "ingatlan_id=" + String(id)
let pa = [ tokenpost, id_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "get_idopont_dates"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func get_idoponts_by_user(onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let route = baseURL + "get_idopont_by_user"
makeHTTPPostRequest(route, body: tokenpost, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func get_idoponts_by_datum(id: Int, datum: String, onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let datum_post = "datum=" + datum
let id_post = "ingatlan_id=" + String(id)
print ("IDOPONT DATUM", datum)
print ("IDOPONT INGATLAN ID", String(id))
let pa = [ tokenpost, datum_post, id_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "get_idopont_by_date"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
print ("IDOPONT ERROR", json)
onCompletion(json as JSON)
})
}
func update_idopont(id: Int, status: Int, onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let id_post = "id=" + String(id)
let status_post = "s=" + String(status)
let pa = [ tokenpost, id_post, status_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "update_idopont"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
func get_idpontcount(onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let route = baseURL + "get_idpontcount"
makeHTTPPostRequest(route, body: tokenpost, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
//add_idopont
func add_idopont(mikor: String, ingatlan_id: Int, onCompletion: (JSON) -> Void) {
let token = [ "token", SettingUtil.sharedInstance.getToken()]
let tokenpost = token.joinWithSeparator("=")
let mikor_post = "mikor=" + mikor
let id_post = "ingatlan_id=" + String(ingatlan_id)
let pa = [ tokenpost, mikor_post, id_post]
let postbody = pa.joinWithSeparator("&")
let route = baseURL + "add_idopont"
makeHTTPPostRequest(route, body: postbody, onCompletion: { json, err in
onCompletion(json as JSON)
})
}
private func makeHTTPPostRequest(path: String, body: String, onCompletion: ServiceResponse) {
let request = NSMutableURLRequest(URL: NSURL(string: path)!)
// Set the method to POST
request.HTTPMethod = "POST"
do {
print(body)
let postData:NSData = body.dataUsingEncoding(NSUTF8StringEncoding)!
request.HTTPBody = postData
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
if let jsonData = data {
let json:JSON = JSON(data: jsonData)
onCompletion(json, nil)
} else {
onCompletion(nil, error)
}
})
task.resume()
} catch {
// Create your personal error
onCompletion(nil, nil)
}
}
}
|
mit
|
6468f2cac907cb52d43cee91f7d4a0ea
| 32.411348 | 112 | 0.557537 | 4.405987 | false | false | false | false |
zhiquan911/chance_btc_wallet
|
chance_btc_wallet/Pods/CryptoSwift/Sources/CryptoSwift/CMAC.swift
|
3
|
3776
|
//
// CryptoSwift
//
// Copyright (C) 2014-2017 Marcin Krzyżanowski <[email protected]>
// This software is provided 'as-is', without any express or implied warranty.
//
// In no event will the authors be held liable for any damages arising from the use of this software.
//
// Permission is granted to anyone to use this software for any purpose,including commercial applications, and to alter it and redistribute it freely, subject to the following restrictions:
//
// - The origin of this software must not be misrepresented; you must not claim that you wrote the original software. If you use this software in a product, an acknowledgment in the product documentation is required.
// - Altered source versions must be plainly marked as such, and must not be misrepresented as being the original software.
// - This notice may not be removed or altered from any source or binary distribution.
//
public final class CMAC: Authenticator {
public enum Error: Swift.Error {
case wrongKeyLength
}
private let key: SecureBytes
private static let BlockSize: Int = 16
private static let Zero: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
private static let Rb: Array<UInt8> = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87]
public init(key: Array<UInt8>) throws {
if key.count != 16 {
throw Error.wrongKeyLength
}
self.key = SecureBytes(bytes: key)
}
// MARK: Authenticator
public func authenticate(_ bytes: Array<UInt8>) throws -> Array<UInt8> {
let aes = try AES(key: Array(key), blockMode: .CBC(iv: CMAC.Zero), padding: .noPadding)
let l = try aes.encrypt(CMAC.Zero)
var subKey1 = leftShiftOneBit(l)
if (l[0] & 0x80) != 0 {
subKey1 = xor(CMAC.Rb, subKey1)
}
var subKey2 = leftShiftOneBit(subKey1)
if (subKey1[0] & 0x80) != 0 {
subKey2 = xor(CMAC.Rb, subKey2)
}
let lastBlockComplete: Bool
let blockCount = (bytes.count + CMAC.BlockSize - 1) / CMAC.BlockSize
if blockCount == 0 {
lastBlockComplete = false
} else {
lastBlockComplete = bytes.count % CMAC.BlockSize == 0
}
var paddedBytes = bytes
if !lastBlockComplete {
bitPadding(to: &paddedBytes, blockSize: CMAC.BlockSize)
}
var blocks = Array(paddedBytes.batched(by: CMAC.BlockSize))
var lastBlock = blocks.popLast()!
if lastBlockComplete {
lastBlock = xor(lastBlock, subKey1)
} else {
lastBlock = xor(lastBlock, subKey2)
}
var x = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize)
var y = Array<UInt8>(repeating: 0x00, count: CMAC.BlockSize)
for block in blocks {
y = xor(block, x)
x = try aes.encrypt(y)
}
y = xor(lastBlock, x)
return try aes.encrypt(y)
}
// MARK: Helper methods
/**
Performs left shift by one bit to the bit string aquired after concatenating al bytes in the byte array
- parameters:
- bytes: byte array
- returns: bit shifted bit string split again in array of bytes
*/
private func leftShiftOneBit(_ bytes: Array<UInt8>) -> Array<UInt8> {
var shifted = Array<UInt8>(repeating: 0x00, count: bytes.count)
let last = bytes.count - 1
for index in 0..<last {
shifted[index] = bytes[index] << 1
if (bytes[index + 1] & 0x80) != 0 {
shifted[index] += 0x01
}
}
shifted[last] = bytes[last] << 1
return shifted
}
}
|
mit
|
330dc201fe1ef9914b8f5be72a22a965
| 37.131313 | 217 | 0.621192 | 3.665049 | false | false | false | false |
jerrypupu111/LearnDrawingToolSet
|
SwiftGL/Vec3.swift
|
1
|
13009
|
//
// Vec3.swift
// SwiftGL
//
// Created by Scott Bennett on 2014-06-08.
// Copyright (c) 2014 Scott Bennett. All rights reserved.
//
import Darwin
public struct Vec3 {
public var x, y, z: Float
public init() {
self.x = 0
self.y = 0
self.z = 0
}
// Explicit initializers
public init(s: Float) {
self.x = s
self.y = s
self.z = s
}
public init(x: Float) {
self.x = x
self.y = 0
self.z = 0
}
public init(x: Float, y: Float) {
self.x = x
self.y = y
self.z = 0
}
public init(x: Float, y: Float, z: Float) {
self.x = x
self.y = y
self.z = z
}
public init(xy: Vec2, z: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
}
public init(x: Float, yz: Vec2) {
self.x = x
self.y = yz.x
self.z = yz.y
}
// Implicit initializers
public init(_ x: Float) {
self.x = x
self.y = 0
self.z = 0
}
public init(_ x: Float, _ y: Float) {
self.x = x
self.y = y
self.z = 0
}
public init(_ x: Float, _ y: Float, _ z: Float) {
self.x = x
self.y = y
self.z = z
}
public init(_ xy: Vec2, _ z: Float) {
self.x = xy.x
self.y = xy.y
self.z = z
}
public init(_ x: Float, _ yz: Vec2) {
self.x = x
self.y = yz.x
self.z = yz.y
}
public var length2: Float {
get {
return x * x + y * y + z * z
}
}
public var length: Float {
get {
return sqrt(self.length2)
}
set {
self = length * normalize(self)
}
}
// Swizzle (Vec2) Properties
public var xx: Vec2 {get {return Vec2(x: x, y: x)}}
public var yx: Vec2 {get {return Vec2(x: y, y: x)} set(v) {self.y = v.x; self.x = v.y}}
public var zx: Vec2 {get {return Vec2(x: z, y: x)} set(v) {self.z = v.x; self.x = v.y}}
public var yy: Vec2 {get {return Vec2(x: y, y: y)}}
public var xy: Vec2 {get {return Vec2(x: x, y: y)} set(v) {self.x = v.x; self.y = v.y}}
public var zy: Vec2 {get {return Vec2(x: z, y: y)} set(v) {self.z = v.x; self.y = v.y}}
public var xz: Vec2 {get {return Vec2(x: x, y: z)} set(v) {self.x = v.x; self.z = v.y}}
public var yz: Vec2 {get {return Vec2(x: y, y: z)} set(v) {self.y = v.x; self.z = v.y}}
public var zz: Vec2 {get {return Vec2(x: z, y: z)}}
// Swizzle (Vec3) Properties
public var xxx: Vec3 {get {return Vec3(x: x, y: x, z: x)}}
public var yxx: Vec3 {get {return Vec3(x: y, y: x, z: x)}}
public var zxx: Vec3 {get {return Vec3(x: z, y: x, z: x)}}
public var yyx: Vec3 {get {return Vec3(x: y, y: y, z: x)}}
public var xyx: Vec3 {get {return Vec3(x: x, y: y, z: x)}}
public var zyx: Vec3 {get {return Vec3(x: z, y: y, z: x)} set(v) {self.z = v.x; self.y = v.y; self.x = v.z}}
public var xzx: Vec3 {get {return Vec3(x: x, y: z, z: x)}}
public var yzx: Vec3 {get {return Vec3(x: y, y: z, z: x)} set(v) {self.y = v.x; self.z = v.y; self.x = v.z}}
public var zzx: Vec3 {get {return Vec3(x: z, y: z, z: x)}}
public var xxy: Vec3 {get {return Vec3(x: x, y: x, z: y)}}
public var yxy: Vec3 {get {return Vec3(x: y, y: x, z: y)}}
public var zxy: Vec3 {get {return Vec3(x: z, y: x, z: y)} set(v) {self.z = v.x; self.x = v.y; self.y = v.z}}
public var yyy: Vec3 {get {return Vec3(x: y, y: y, z: y)}}
public var xyy: Vec3 {get {return Vec3(x: x, y: y, z: y)}}
public var zyy: Vec3 {get {return Vec3(x: z, y: y, z: y)}}
public var xzy: Vec3 {get {return Vec3(x: x, y: z, z: y)} set(v) {self.x = v.x; self.z = v.y; self.y = v.z}}
public var yzy: Vec3 {get {return Vec3(x: y, y: z, z: y)}}
public var zzy: Vec3 {get {return Vec3(x: z, y: z, z: y)}}
public var xxz: Vec3 {get {return Vec3(x: x, y: x, z: z)}}
public var yxz: Vec3 {get {return Vec3(x: y, y: x, z: z)} set(v) {self.y = v.x; self.x = v.y; self.z = v.z}}
public var zxz: Vec3 {get {return Vec3(x: z, y: x, z: z)}}
public var yyz: Vec3 {get {return Vec3(x: y, y: y, z: z)}}
public var xyz: Vec3 {get {return Vec3(x: x, y: y, z: z)} set(v) {self.x = v.x; self.y = v.y; self.z = v.z}}
public var zyz: Vec3 {get {return Vec3(x: z, y: y, z: z)}}
public var xzz: Vec3 {get {return Vec3(x: x, y: z, z: z)}}
public var yzz: Vec3 {get {return Vec3(x: y, y: z, z: z)}}
public var zzz: Vec3 {get {return Vec3(x: z, y: z, z: z)}}
// Swizzle (Vec4) Properties
public var xxxx: Vec4 {get {return Vec4(x: x, y: x, z: x, w: x)}}
public var yxxx: Vec4 {get {return Vec4(x: y, y: x, z: x, w: x)}}
public var zxxx: Vec4 {get {return Vec4(x: z, y: x, z: x, w: x)}}
public var yyxx: Vec4 {get {return Vec4(x: y, y: y, z: x, w: x)}}
public var xyxx: Vec4 {get {return Vec4(x: x, y: y, z: x, w: x)}}
public var zyxx: Vec4 {get {return Vec4(x: z, y: y, z: x, w: x)}}
public var xzxx: Vec4 {get {return Vec4(x: x, y: z, z: x, w: x)}}
public var yzxx: Vec4 {get {return Vec4(x: y, y: z, z: x, w: x)}}
public var zzxx: Vec4 {get {return Vec4(x: z, y: z, z: x, w: x)}}
public var xxyx: Vec4 {get {return Vec4(x: x, y: x, z: y, w: x)}}
public var yxyx: Vec4 {get {return Vec4(x: y, y: x, z: y, w: x)}}
public var zxyx: Vec4 {get {return Vec4(x: z, y: x, z: y, w: x)}}
public var yyyx: Vec4 {get {return Vec4(x: y, y: y, z: y, w: x)}}
public var xyyx: Vec4 {get {return Vec4(x: x, y: y, z: y, w: x)}}
public var zyyx: Vec4 {get {return Vec4(x: z, y: y, z: y, w: x)}}
public var xzyx: Vec4 {get {return Vec4(x: x, y: z, z: y, w: x)}}
public var yzyx: Vec4 {get {return Vec4(x: y, y: z, z: y, w: x)}}
public var zzyx: Vec4 {get {return Vec4(x: z, y: z, z: y, w: x)}}
public var xxzx: Vec4 {get {return Vec4(x: x, y: x, z: z, w: x)}}
public var yxzx: Vec4 {get {return Vec4(x: y, y: x, z: z, w: x)}}
public var zxzx: Vec4 {get {return Vec4(x: z, y: x, z: z, w: x)}}
public var yyzx: Vec4 {get {return Vec4(x: y, y: y, z: z, w: x)}}
public var xyzx: Vec4 {get {return Vec4(x: x, y: y, z: z, w: x)}}
public var zyzx: Vec4 {get {return Vec4(x: z, y: y, z: z, w: x)}}
public var xzzx: Vec4 {get {return Vec4(x: x, y: z, z: z, w: x)}}
public var yzzx: Vec4 {get {return Vec4(x: y, y: z, z: z, w: x)}}
public var zzzx: Vec4 {get {return Vec4(x: z, y: z, z: z, w: x)}}
public var xxxy: Vec4 {get {return Vec4(x: x, y: x, z: x, w: y)}}
public var yxxy: Vec4 {get {return Vec4(x: y, y: x, z: x, w: y)}}
public var zxxy: Vec4 {get {return Vec4(x: z, y: x, z: x, w: y)}}
public var yyxy: Vec4 {get {return Vec4(x: y, y: y, z: x, w: y)}}
public var xyxy: Vec4 {get {return Vec4(x: x, y: y, z: x, w: y)}}
public var zyxy: Vec4 {get {return Vec4(x: z, y: y, z: x, w: y)}}
public var xzxy: Vec4 {get {return Vec4(x: x, y: z, z: x, w: y)}}
public var yzxy: Vec4 {get {return Vec4(x: y, y: z, z: x, w: y)}}
public var zzxy: Vec4 {get {return Vec4(x: z, y: z, z: x, w: y)}}
public var xxyy: Vec4 {get {return Vec4(x: x, y: x, z: y, w: y)}}
public var yxyy: Vec4 {get {return Vec4(x: y, y: x, z: y, w: y)}}
public var zxyy: Vec4 {get {return Vec4(x: z, y: x, z: y, w: y)}}
public var yyyy: Vec4 {get {return Vec4(x: y, y: y, z: y, w: y)}}
public var xyyy: Vec4 {get {return Vec4(x: x, y: y, z: y, w: y)}}
public var zyyy: Vec4 {get {return Vec4(x: z, y: y, z: y, w: y)}}
public var xzyy: Vec4 {get {return Vec4(x: x, y: z, z: y, w: y)}}
public var yzyy: Vec4 {get {return Vec4(x: y, y: z, z: y, w: y)}}
public var zzyy: Vec4 {get {return Vec4(x: z, y: z, z: y, w: y)}}
public var xxzy: Vec4 {get {return Vec4(x: x, y: x, z: z, w: y)}}
public var yxzy: Vec4 {get {return Vec4(x: y, y: x, z: z, w: y)}}
public var zxzy: Vec4 {get {return Vec4(x: z, y: x, z: z, w: y)}}
public var yyzy: Vec4 {get {return Vec4(x: y, y: y, z: z, w: y)}}
public var xyzy: Vec4 {get {return Vec4(x: x, y: y, z: z, w: y)}}
public var zyzy: Vec4 {get {return Vec4(x: z, y: y, z: z, w: y)}}
public var xzzy: Vec4 {get {return Vec4(x: x, y: z, z: z, w: y)}}
public var yzzy: Vec4 {get {return Vec4(x: y, y: z, z: z, w: y)}}
public var zzzy: Vec4 {get {return Vec4(x: z, y: z, z: z, w: y)}}
public var xxxz: Vec4 {get {return Vec4(x: x, y: x, z: x, w: z)}}
public var yxxz: Vec4 {get {return Vec4(x: y, y: x, z: x, w: z)}}
public var zxxz: Vec4 {get {return Vec4(x: z, y: x, z: x, w: z)}}
public var yyxz: Vec4 {get {return Vec4(x: y, y: y, z: x, w: z)}}
public var xyxz: Vec4 {get {return Vec4(x: x, y: y, z: x, w: z)}}
public var zyxz: Vec4 {get {return Vec4(x: z, y: y, z: x, w: z)}}
public var xzxz: Vec4 {get {return Vec4(x: x, y: z, z: x, w: z)}}
public var yzxz: Vec4 {get {return Vec4(x: y, y: z, z: x, w: z)}}
public var zzxz: Vec4 {get {return Vec4(x: z, y: z, z: x, w: z)}}
public var xxyz: Vec4 {get {return Vec4(x: x, y: x, z: y, w: z)}}
public var yxyz: Vec4 {get {return Vec4(x: y, y: x, z: y, w: z)}}
public var zxyz: Vec4 {get {return Vec4(x: z, y: x, z: y, w: z)}}
public var yyyz: Vec4 {get {return Vec4(x: y, y: y, z: y, w: z)}}
public var xyyz: Vec4 {get {return Vec4(x: x, y: y, z: y, w: z)}}
public var zyyz: Vec4 {get {return Vec4(x: z, y: y, z: y, w: z)}}
public var xzyz: Vec4 {get {return Vec4(x: x, y: z, z: y, w: z)}}
public var yzyz: Vec4 {get {return Vec4(x: y, y: z, z: y, w: z)}}
public var zzyz: Vec4 {get {return Vec4(x: z, y: z, z: y, w: z)}}
public var xxzz: Vec4 {get {return Vec4(x: x, y: x, z: z, w: z)}}
public var yxzz: Vec4 {get {return Vec4(x: y, y: x, z: z, w: z)}}
public var zxzz: Vec4 {get {return Vec4(x: z, y: x, z: z, w: z)}}
public var yyzz: Vec4 {get {return Vec4(x: y, y: y, z: z, w: z)}}
public var xyzz: Vec4 {get {return Vec4(x: x, y: y, z: z, w: z)}}
public var zyzz: Vec4 {get {return Vec4(x: z, y: y, z: z, w: z)}}
public var xzzz: Vec4 {get {return Vec4(x: x, y: z, z: z, w: z)}}
public var yzzz: Vec4 {get {return Vec4(x: y, y: z, z: z, w: z)}}
public var zzzz: Vec4 {get {return Vec4(x: z, y: z, z: z, w: z)}}
}
// Make it easier to interpret Vec3 as a string
extension Vec3: CustomStringConvertible, CustomDebugStringConvertible {
public var description: String {get {return "(\(x), \(y), \(z))"}}
public var debugDescription: String {get {return "Vec3(x: \(x), y: \(y), z: \(z))"}}
}
// Vec3 Prefix Operators
public prefix func - (v: Vec3) -> Vec3 {return Vec3(x: -v.x, y: -v.y, z: -v.z)}
// Vec3 Infix Operators
public func + (a: Vec3, b: Vec3) -> Vec3 {return Vec3(x: a.x + b.x, y: a.y + b.y, z: a.z + b.z)}
public func - (a: Vec3, b: Vec3) -> Vec3 {return Vec3(x: a.x - b.x, y: a.y - b.y, z: a.z - b.z)}
public func * (a: Vec3, b: Vec3) -> Vec3 {return Vec3(x: a.x * b.x, y: a.y * b.y, z: a.z * b.z)}
public func / (a: Vec3, b: Vec3) -> Vec3 {return Vec3(x: a.x / b.x, y: a.y / b.y, z: a.z / b.z)}
// Vec3 Scalar Operators
public func * (s: Float, v: Vec3) -> Vec3 {return Vec3(x: s * v.x, y: s * v.y, z: s * v.z)}
public func * (v: Vec3, s: Float) -> Vec3 {return Vec3(x: v.x * s, y: v.y * s, z: v.z * s)}
public func / (v: Vec3, s: Float) -> Vec3 {return Vec3(x: v.x / s, y: v.y / s, z: v.z / s)}
// Vec3 Assignment Operators
public func += (a: inout Vec3, b: Vec3) {a = a + b}
public func -= (a: inout Vec3, b: Vec3) {a = a - b}
public func *= (a: inout Vec3, b: Vec3) {a = a * b}
public func /= (a: inout Vec3, b: Vec3) {a = a / b}
public func *= (a: inout Vec3, b: Float) {a = a * b}
public func /= (a: inout Vec3, b: Float) {a = a / b}
// Functions which operate on Vec3
public func length(_ v: Vec3) -> Float {return v.length}
public func length2(_ v: Vec3) -> Float {return v.length2}
public func normalize(_ v: Vec3) -> Vec3 {return v / v.length}
public func dot(_ a: Vec3, b: Vec3) -> Float {return a.x * b.x + a.y * b.y + a.z * b.z}
public func cross(_ a: Vec3, b: Vec3) -> Vec3 {return Vec3(x: a.y * b.z - a.z * b.y, y: a.z * b.x - a.x * b.z, z: a.x * b.y - a.y * b.x)}
public func clamp(_ value: Vec3, min: Float, max: Float) -> Vec3 {return Vec3(clamp(value.x, min: min, max: max), clamp(value.y, min: min, max: max), clamp(value.z, min: min, max: max))}
public func mix(_ a: Vec3, b: Vec3, t: Float) -> Vec3 {return a + (b - a) * t}
public func smoothstep(_ a: Vec3, b: Vec3, t: Float) -> Vec3 {return mix(a, b: b, t: t * t * (3 - 2 * t))}
public func clamp(_ value: Vec3, min: Vec3, max: Vec3) -> Vec3 {return Vec3(clamp(value.x, min: min.x, max: max.x), clamp(value.y, min: min.y, max: max.y), clamp(value.z, min: min.z, max: max.z))}
public func mix(_ a: Vec3, b: Vec3, t: Vec3) -> Vec3 {return a + (b - a) * t}
public func smoothstep(_ a: Vec3, b: Vec3, t: Vec3) -> Vec3 {return mix(a, b: b, t: t * t * (Vec3(s: 3) - 2 * t))}
|
mit
|
e720460efefcb40f8fccda427bef4ba1
| 47.00369 | 196 | 0.532324 | 2.385659 | false | false | false | false |
zxpLearnios/MyProject
|
test_projectDemo1/TVC && NAV/TabBar/MyPlusButton.swift
|
1
|
2572
|
//
// MyPlusButton.swift
// test_projectDemo1
//
// Created by Jingnan Zhang on 16/5/30.
// Copyright © 2016年 Jingnan Zhang. All rights reserved.
// 专用于tabbar上面的有、无图片时的自定义按钮,会根据有无title自动适应image的位置、大小
import UIKit
class MyPlusButton: UIButton {
let buttonImageRatio:CGFloat = 0.7 // 比例
let normalColor = UIColor.red // 默认字体颜色
let selectColor = UIColor.green // 选中时字体的颜色
let fontSize:CGFloat = 10
// 0. 高亮时图片。title皆不变
fileprivate var _highlighted = false
override var isHighlighted: Bool{
get{
return self._highlighted
}
set{
self._highlighted = newValue
}
}
// -0. 如下写,则无效
// override var highlighted: Bool{
// didSet{
//
// }
// }
// MARK: 初始化
override init(frame: CGRect) {
super.init(frame: frame)
self.doInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func layoutSubviews() {
super.layoutSubviews()
}
fileprivate func doInit(){
self.adjustsImageWhenDisabled = false
self.setTitleColor(normalColor, for: UIControlState())
self.setTitleColor(selectColor, for: .selected)
self.titleLabel?.font = UIFont.systemFont(ofSize: fontSize)
self.titleLabel?.textAlignment = .center
}
// 设置 setImage时有用
override func imageRect(forContentRect contentRect: CGRect) -> CGRect {
var imgW:CGFloat = 49
var imgH = imgW
var imgX:CGFloat = self.frame.width/2 - imgW/2
var imgY:CGFloat = 0
if !(self.titleLabel?.text == "" || self.titleLabel?.text == nil) { // 有title时的图片情况
imgW = 29
imgH = 29
imgY = 5
imgX = self.frame.width/2 - imgW/2
return CGRect(x: imgX, y: imgY, width: imgH, height: imgH)
}
return CGRect(x: imgX, y: imgY, width: imgW, height: imgH)
}
override func titleRect(forContentRect contentRect: CGRect) -> CGRect {
let titleY:CGFloat = contentRect.size.height * buttonImageRatio
let titleW:CGFloat = contentRect.size.width
let titleH:CGFloat = contentRect.size.height-titleY
let titleX:CGFloat = 0
return CGRect(x: titleX, y: titleY, width: titleW, height: titleH)
}
}
|
mit
|
e32e7b00a38660f1207df57c92cfc2dc
| 26.352273 | 91 | 0.589115 | 4.15 | false | false | false | false |
BurntCaramel/Lantern
|
LanternModel/PageMapper+Validating.swift
|
1
|
4155
|
//
// PageInfoValidationResult.swift
// Hoverlytics
//
// Created by Patrick Smith on 28/04/2015.
// Copyright (c) 2015 Burnt Caramel. All rights reserved.
//
import Foundation
import Ono
public enum PageInfoValidationResult {
case valid
case notRequested
case missing
case empty
case multiple
case invalid
}
private let whitespaceCharacterSet = CharacterSet.whitespacesAndNewlines
private let nonWhitespaceCharacterSet = whitespaceCharacterSet.inverted
private func stringIsJustWhitespace(_ string: String) -> Bool {
// Return range if non-whitespace characters are present, nil if no non-whitespace characters are present.
return string.rangeOfCharacter(from: nonWhitespaceCharacterSet, options: [], range: nil) == nil
}
extension PageInfoValidationResult {
init(validatedStringValue: ValidatedStringValue) {
switch validatedStringValue{
case .validString:
self = .valid
case .notRequested:
self = .notRequested
case .missing:
self = .missing
case .empty:
self = .empty
case .multiple:
self = .multiple
case .invalid:
self = .invalid
}
}
static func validateContentsOfElements(_ elements: [ONOXMLElement]) -> PageInfoValidationResult {
let validatedStringValue = ValidatedStringValue.validateContentOfElements(elements)
return self.init(validatedStringValue: validatedStringValue)
}
static func validateMIMEType(_ MIMEType: String) -> PageInfoValidationResult {
if stringIsJustWhitespace(MIMEType) {
return .missing
}
return .valid
}
}
public enum PageInfoValidationArea: Int {
case mimeType = 1
case Title = 2
case h1 = 3
case metaDescription = 4
var title: String {
switch self {
case .mimeType:
return "MIME Type"
case .Title:
return "Title"
case .h1:
return "H1"
case .metaDescription:
return "Meta Description"
}
}
var isRequired: Bool {
return true
}
static var allAreas = Set<PageInfoValidationArea>([.mimeType, .Title, .h1, .metaDescription])
}
extension PageInfo {
public func validateArea(_ validationArea: PageInfoValidationArea) -> PageInfoValidationResult {
switch validationArea {
case .mimeType:
if let MIMEType = MIMEType {
return PageInfoValidationResult.validateMIMEType(MIMEType.stringValue)
}
case .Title:
if let pageTitleElements = contentInfo?.pageTitleElements {
return PageInfoValidationResult.validateContentsOfElements(pageTitleElements)
}
case .h1:
if let h1Elements = contentInfo?.h1Elements {
return PageInfoValidationResult.validateContentsOfElements(h1Elements)
}
case .metaDescription:
if let metaDescriptionElements = self.contentInfo?.metaDescriptionElements {
switch metaDescriptionElements.count {
case 1:
let element = metaDescriptionElements[0]
let validatedStringValue = ValidatedStringValue.validateAttribute("content", ofElement: element)
return PageInfoValidationResult(validatedStringValue: validatedStringValue)
case 0:
return .missing
default:
return .multiple
}
}
}
return .missing
}
}
public extension PageMapper {
public func copyHTMLPageURLsWhichCompletelyValidateForType(_ type: BaseContentType) -> [URL] {
let validationAreas = PageInfoValidationArea.allAreas
let URLs = copyURLsWithBaseContentType(type, withResponseType: .successful)
return URLs.filter { URL in
guard let pageInfo = self.loadedURLToPageInfo[URL] else { return false }
let containsInvalidResult = validationAreas.contains { validationArea in
return pageInfo.validateArea(validationArea) != .valid
}
return !containsInvalidResult
}
}
public func copyHTMLPageURLsForType(_ type: BaseContentType, failingToValidateInArea validationArea: PageInfoValidationArea) -> [URL] {
let URLs = copyURLsWithBaseContentType(type, withResponseType: .successful)
return URLs.filter { URL in
guard let pageInfo = self.loadedURLToPageInfo[URL] else { return false }
switch pageInfo.validateArea(validationArea) {
case .valid:
return false
case .missing:
return validationArea.isRequired // Only invalid if it is required
default:
return true
}
}
}
}
|
apache-2.0
|
d3e1d1ac53b4784cfd475479efd3d876
| 25.634615 | 136 | 0.749218 | 3.976077 | false | false | false | false |
Tueno/IconHUD
|
IconHUD/AppInfo.swift
|
1
|
1908
|
//
// AppInfo.swift
// Summaricon
//
// Created by tueno on 2017/04/25.
// Copyright © 2017年 Tomonori Ueno. All rights reserved.
//
final class AppInfo {
class var branchName: String {
get {
let branchName = bash(command:"git",
currentDirPath: ConsoleIO.environmentVariable(key: .projectRoot),
arguments: ["rev-parse", "--abbrev-ref", "HEAD"])
if branchName == "HEAD" {
// On Travis CI
return ConsoleIO.environmentVariable(key: .branchNameOnTravisCI)
} else {
return branchName
}
}
}
class var commitId: String {
get {
let commitId = bash(command: "git",
currentDirPath: ConsoleIO.environmentVariable(key: .projectRoot),
arguments: ["rev-parse", "--short", "HEAD"])
return commitId
}
}
class var buildNumber: String {
get {
let infoPlist = ConsoleIO.environmentVariable(key: .infoPlist)
let buildNumber = bash(command: "/usr/libexec/PlistBuddy",
currentDirPath: ConsoleIO.environmentVariable(key: .projectRoot),
arguments: ["-c", "Print CFBundleVersion", infoPlist])
return buildNumber
}
}
class var versionNumber: String {
get {
let infoPlist = ConsoleIO.environmentVariable(key: .infoPlist)
let versionNumber = bash(command: "/usr/libexec/PlistBuddy",
currentDirPath: ConsoleIO.environmentVariable(key: .projectRoot),
arguments: ["-c", "Print CFBundleShortVersionString", infoPlist])
return versionNumber
}
}
}
|
mit
|
d98cd1ea6391c1acb181b14db2ab34a1
| 34.277778 | 102 | 0.517585 | 5.190736 | false | false | false | false |
CoderST/DYZB
|
DYZB/DYZB/Class/Profile/View/BasicSettingCell.swift
|
1
|
3828
|
//
// BasicSettingCell.swift
// DYZB
//
// Created by xiudou on 2017/7/10.
// Copyright © 2017年 xiudo. All rights reserved.
//
import UIKit
fileprivate let settingMargin : CGFloat = 20
fileprivate let rightImageViewWH : CGFloat = 40
class BasicSettingCell: UICollectionViewCell {
fileprivate lazy var leftImageView : UIImageView = {
let leftImageView = UIImageView()
leftImageView.image = UIImage(named: "")
return leftImageView
}()
fileprivate lazy var titleLabel : UILabel = {
let titleLabel = UILabel()
titleLabel.textAlignment = .center
titleLabel.font = UIFont.systemFont(ofSize: 12)
return titleLabel
}()
fileprivate lazy var subTitleLabel : UILabel = {
let subTitleLabel = UILabel()
subTitleLabel.textAlignment = .center
subTitleLabel.font = UIFont.systemFont(ofSize: 12)
return subTitleLabel
}()
fileprivate lazy var arrowView : UIImageView = {
let arrowView = UIImageView()
arrowView.image = UIImage(named: "Image_arrow_right")
return arrowView
}()
fileprivate lazy var rightImageView : UIImageView = {
let rightImageView = UIImageView()
return rightImageView
}()
fileprivate lazy var bottomLineView : UIView = {
let bottomLineView = UIView()
bottomLineView.backgroundColor = .gray
return bottomLineView
}()
var accessoryView : UIView?
override init(frame: CGRect) {
super.init(frame : frame)
contentView.backgroundColor = .white
contentView.addSubview(leftImageView)
contentView.addSubview(arrowView)
contentView.addSubview(titleLabel)
contentView.addSubview(subTitleLabel)
contentView.addSubview(rightImageView)
contentView.addSubview(bottomLineView)
}
// 根据settingItem模型来显示内容
var settingItemFrame : SettingItemFrame?{
didSet{
guard let settingItemFrame = settingItemFrame else { return }
setupData(settingItemFrame)
setupFrame(settingItemFrame)
}
}
// 设置每一组的背景图片的方法
func setIndexPath(indexPath : NSIndexPath,rowCount : NSInteger){
}
func setupData(_ settingItemFrame : SettingItemFrame){
leftImageView.image = UIImage(named: settingItemFrame.settingItem.icon!)
titleLabel.text = settingItemFrame.settingItem.title
subTitleLabel.text = settingItemFrame.settingItem.subTitle
if settingItemFrame.settingItem is ArrowImageItem{
let arroeImageItem = settingItemFrame.settingItem as!ArrowImageItem
if let url = URL(string: arroeImageItem.rightImageName){
rightImageView.sd_setImage(with: url, placeholderImage: UIImage(named : "profile_user_375x375"), options: .allowInvalidSSLCertificates)
}
}
}
func setupFrame(_ settingItemFrame : SettingItemFrame){
leftImageView.frame = settingItemFrame.iconImageViewFrame
titleLabel.frame = settingItemFrame.titleFrame
subTitleLabel.frame = settingItemFrame.subTitleFrame
rightImageView.frame = settingItemFrame.headImageViewFrame
arrowView.frame = settingItemFrame.arrowFrame
bottomLineView.frame = settingItemFrame.bottomLineFrame
rightImageView.layer.cornerRadius = settingItemFrame.headImageViewFrame.width * 0.5
rightImageView.clipsToBounds = true
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
}
|
mit
|
6d655cef5900766d366c6d06d598e808
| 29.491935 | 151 | 0.643745 | 5.455988 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.