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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
1457792186/JWSwift | SwiftLearn/SwiftDemo/Pods/LTMorphingLabel/LTMorphingLabel/LTMorphingLabel+Pixelate.swift | 2 | 3611 | //
// LTMorphingLabel+Pixelate.swift
// https://github.com/lexrus/LTMorphingLabel
//
// The MIT License (MIT)
// Copyright (c) 2017 Lex Tang, http://lexrus.com
//
// Permission is hereby granted, free of charge, to any person obtaining a
// copy of this software and associated documentation files
// (the “Software”), to deal in the Software without restriction,
// including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software,
// and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included
// in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS
// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
// CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
// TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
// SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
import UIKit
extension LTMorphingLabel {
@objc
func PixelateLoad() {
effectClosures["Pixelate\(LTMorphingPhases.disappear)"] = {
char, index, progress in
return LTCharacterLimbo(
char: char,
rect: self.previousRects[index],
alpha: CGFloat(1.0 - progress),
size: self.font.pointSize,
drawingProgress: CGFloat(progress))
}
effectClosures["Pixelate\(LTMorphingPhases.appear)"] = {
char, index, progress in
return LTCharacterLimbo(
char: char,
rect: self.newRects[index],
alpha: CGFloat(progress),
size: self.font.pointSize,
drawingProgress: CGFloat(1.0 - progress)
)
}
drawingClosures["Pixelate\(LTMorphingPhases.draw)"] = {
limbo in
if limbo.drawingProgress > 0.0 {
let charImage = self.pixelateImageForCharLimbo(
limbo,
withBlurRadius: limbo.drawingProgress * 6.0
)
charImage.draw(in: limbo.rect)
return true
}
return false
}
}
fileprivate func pixelateImageForCharLimbo(
_ charLimbo: LTCharacterLimbo,
withBlurRadius blurRadius: CGFloat
) -> UIImage {
let scale = min(UIScreen.main.scale, 1.0 / blurRadius)
UIGraphicsBeginImageContextWithOptions(charLimbo.rect.size, false, scale)
let fadeOutAlpha = min(1.0, max(0.0, charLimbo.drawingProgress * -2.0 + 2.0 + 0.01))
let rect = CGRect(
x: 0,
y: 0,
width: charLimbo.rect.size.width,
height: charLimbo.rect.size.height
)
String(charLimbo.char).draw(in: rect, withAttributes: [
.font: self.font,
.foregroundColor: self.textColor.withAlphaComponent(fadeOutAlpha)
])
let newImage = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return newImage!
}
}
| apache-2.0 | 4ccb7310d497f55dcf0be27b49d15486 | 35.393939 | 96 | 0.587843 | 5.018106 | false | false | false | false |
beeth0ven/BNKit | BNKit/Source/Fundation+/Number+random.swift | 1 | 3392 | //
// Number+random.swift
// BNKit
//
// Created by luojie on 2016/11/19.
// Copyright © 2016年 LuoJie. All rights reserved.
//
import Foundation
/**
Generate random Number
# Usage Exampe #
```swift
let randomInt = (1..<5).random() // randomInt is in [1, 2, 3, 4]
let randomInt = (1...5).random() // randomInt is in [1, 2, 3, 4, 5]
let randomUInt = (1...5).random() as UInt // randomUInt is UInt Type
let randomDouble = (1.0..<5.0).random() // 1.0 <= randomDouble < 5.0
let randomDouble = (1.0...5.0).random() // 1.0 <= randomDouble <= 5.0
let randomFloat = (1.0...5.0).random() as Float // randomFloat is Float Type
```
*/
public protocol IntegerHasRandom: Integer {
init(_ value: UInt32)
func toUInt32() -> UInt32
}
public protocol FloatingPointHasRandom: FloatingPoint {
init(_ value: UInt32)
func toUInt32() -> UInt32
}
extension Range where Bound: IntegerHasRandom {
public func random() -> Bound {
let delta = upperBound - lowerBound
return lowerBound + Bound(arc4random_uniform(delta.toUInt32()))
}
}
extension ClosedRange where Bound: IntegerHasRandom {
public func random() -> Bound {
let delta = upperBound - lowerBound + 1
return lowerBound + Bound(arc4random_uniform(delta.toUInt32()))
}
}
extension Range where Bound: FloatingPointHasRandom {
public func random() -> Bound {
let delta = upperBound - lowerBound, randomOne = Bound(arc4random_uniform(UInt32.max)) / Bound(UInt32.max)
return lowerBound + randomOne * delta
}
}
extension ClosedRange where Bound: FloatingPointHasRandom {
public func random() -> Bound {
let delta = upperBound - lowerBound, randomOne = Bound(arc4random_uniform(UInt32.max)) / Bound(UInt32.max - 1)
return lowerBound + randomOne * delta
}
}
// ------ IntegerHasRandom
extension Int: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension Int8: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension Int16: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension Int32: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension Int64: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension UInt: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension UInt8: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension UInt16: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension UInt32: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension UInt64: IntegerHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
// ------ FloatingPointHasRandom
extension Float: FloatingPointHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension Double: FloatingPointHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
extension CGFloat: FloatingPointHasRandom {
public func toUInt32() -> UInt32 {
return UInt32(self)
}
}
| mit | cfa28c911320421474882641f07e9eb4 | 20.864516 | 118 | 0.638832 | 3.936121 | false | false | false | false |
manGoweb/MimeLib | Generator/MimeLibGenerator/String+Tools.swift | 1 | 837 | //
// String+Tools.swift
// MimeLibGenerator
//
// Created by Ondrej Rafaj on 14/12/2016.
// Copyright © 2016 manGoweb UK Ltd. All rights reserved.
//
import Foundation
extension String {
var lines: [String] {
var result: [String] = []
enumerateLines { line, _ in result.append(line) }
return result
}
func substr(_ i: Int) -> String {
guard i >= 0 && i < characters.count else { return "" }
return String(self[self.index(self.startIndex, offsetBy: i)])
}
func capitalizingFirstLetter() -> String {
let first = String(characters.prefix(1)).capitalized
let other = String(characters.dropFirst())
return first + other
}
mutating func capitalizeFirstLetter() {
self = self.capitalizingFirstLetter()
}
}
| mit | 9efc81b4c24ef9a5d6c90658a3e2584a | 22.885714 | 69 | 0.600478 | 4.118227 | false | false | false | false |
tianbinbin/DouYuShow | DouYuShow/DouYuShow/Classes/Tools/Extention/NetWorkTools.swift | 1 | 1080 | //
// NetWorkTools.swift
// AlamofireDemp
//
// Created by 田彬彬 on 2017/6/4.
// Copyright © 2017年 田彬彬. All rights reserved.
//
import UIKit
import Alamofire
// 定义请求方式
enum MethodType{
case GET
case POST
}
class NetWorkTools {
class func RequestData(type:MethodType,URLString:String,parameters:[String:Any]? = nil,SuccessCallBack:@escaping(_ Success:AnyObject)->(),FalseCallBack:@escaping (_ false:AnyObject)->()){
//1. 获取类型
let method = type == .GET ? HTTPMethod.get: HTTPMethod.post
// post 请求
Alamofire.request(URLString, method: method, parameters: parameters).responseJSON { (response) in
guard let result = response.result.value else{
// 请求失败
FalseCallBack(response.result.error as AnyObject)
return
}
// 请求成功
SuccessCallBack(result as AnyObject)
}
}
}
| mit | 77ad820fb9ee8e9ac4b66e206e346ce4 | 21.282609 | 191 | 0.552195 | 4.812207 | false | false | false | false |
danielsaidi/iExtra | iExtra/UI/Extensions/UIView/UIView+Nib.swift | 1 | 1073 | //
// UIView+Nib.swift
// iExtra
//
// Created by Daniel Saidi on 2016-11-09.
// Copyright © 2018 Daniel Saidi. All rights reserved.
//
import UIKit
public extension UIView {
static var defaultNib: UINib {
defaultNib()
}
static var defaultNibName: String {
String(describing: self)
}
static func defaultNib(in bundle: Bundle = .main) -> UINib {
UINib(nibName: defaultNibName, bundle: bundle)
}
static func fromNib(
named nibName: String = defaultNibName,
in bundle: Bundle = .main,
owner: Any? = nil) -> Self {
return fromNibTyped(named: nibName, in: bundle, owner: owner)
}
static func fromNibTyped<T: UIView>(
named nibName: String = T.defaultNibName,
in bundle: Bundle = .main,
owner: Any? = nil) -> T {
let nibs = bundle.loadNibNamed(nibName, owner: owner, options: nil)
guard let nib = nibs?[0] as? T else { fatalError("fromNibTyped failed to create a view of correct type") }
return nib
}
}
| mit | 442f40666b5f3dbce73d5dda5c453adc | 25.8 | 114 | 0.603545 | 4.10728 | false | false | false | false |
syncloud/ios | Syncloud/Keychain.swift | 1 | 2865 | import UIKit
import Security
import Foundation
import Security
struct KeychainConstants {
static var klass: String { return toString(kSecClass) }
static var classGenericPassword: String { return toString(kSecClassGenericPassword) }
static var attrAccount: String { return toString(kSecAttrAccount) }
static var valueData: String { return toString(kSecValueData) }
static var returnData: String { return toString(kSecReturnData) }
static var matchLimit: String { return toString(kSecMatchLimit) }
fileprivate static func toString(_ value: CFString) -> String {
return value as String
}
}
open class Keychain {
open class func set(_ key: String, value: String) -> Bool {
if let data = value.data(using: String.Encoding.utf8) {
return set(key, value: data)
}
return false
}
open class func set(_ key: String, value: Data) -> Bool {
let query = [
KeychainConstants.klass : KeychainConstants.classGenericPassword,
KeychainConstants.attrAccount : key,
KeychainConstants.valueData : value ] as [String : Any]
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
return status == noErr
}
open class func get(_ key: String) -> String? {
if let data = getData(key),
let currentString = NSString(data: data, encoding: String.Encoding.utf8.rawValue) as String? {
return currentString
}
return nil
}
open class func getData(_ key: String) -> Data? {
let query = [
KeychainConstants.klass : kSecClassGenericPassword,
KeychainConstants.attrAccount : key,
KeychainConstants.returnData : kCFBooleanTrue,
KeychainConstants.matchLimit : kSecMatchLimitOne ] as [String : Any]
var result: AnyObject?
let status = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
if status == noErr { return result as? Data }
return nil
}
open class func delete(_ key: String) -> Bool {
let query = [
KeychainConstants.klass : kSecClassGenericPassword,
KeychainConstants.attrAccount : key ] as [String : Any]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
open class func clear() -> Bool {
let query = [ kSecClass as String : kSecClassGenericPassword ]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
}
| gpl-3.0 | 5198fd3e62a9fd765d1d9b61b5b923aa | 31.556818 | 106 | 0.605236 | 5.488506 | false | false | false | false |
getsentry/sentry-swift | Samples/Carthage-Validation/XCFramework/XCFramework/SceneDelegate.swift | 2 | 2612 | import SwiftUI
import UIKit
class SceneDelegate: UIResponder, UIWindowSceneDelegate {
var window: UIWindow?
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
// Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
// If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
// This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).
// Create the SwiftUI view that provides the window contents.
let contentView = ContentView()
// Use a UIHostingController as window root view controller.
if let windowScene = scene as? UIWindowScene {
let window = UIWindow(windowScene: windowScene)
window.rootViewController = UIHostingController(rootView: contentView)
self.window = window
window.makeKeyAndVisible()
}
}
func sceneDidDisconnect(_ scene: UIScene) {
// Called as the scene is being released by the system.
// This occurs shortly after the scene enters the background, or when its session is discarded.
// Release any resources associated with this scene that can be re-created the next time the scene connects.
// The scene may re-connect later, as its session was not necessarily discarded (see `application:didDiscardSceneSessions` instead).
}
func sceneDidBecomeActive(_ scene: UIScene) {
// Called when the scene has moved from an inactive state to an active state.
// Use this method to restart any tasks that were paused (or not yet started) when the scene was inactive.
}
func sceneWillResignActive(_ scene: UIScene) {
// Called when the scene will move from an active state to an inactive state.
// This may occur due to temporary interruptions (ex. an incoming phone call).
}
func sceneWillEnterForeground(_ scene: UIScene) {
// Called as the scene transitions from the background to the foreground.
// Use this method to undo the changes made on entering the background.
}
func sceneDidEnterBackground(_ scene: UIScene) {
// Called as the scene transitions from the foreground to the background.
// Use this method to save data, release shared resources, and store enough scene-specific state information
// to restore the scene back to its current state.
}
}
| mit | d2022c50bb1bd24c36b57b0ca001b15e | 48.283019 | 147 | 0.706738 | 5.522199 | false | false | false | false |
codestergit/swift | stdlib/public/SDK/Foundation/NSStringAPI.swift | 2 | 67844 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
//
// Exposing the API of NSString on Swift's String
//
//===----------------------------------------------------------------------===//
@_exported import Foundation // Clang module
// Open Issues
// ===========
//
// Property Lists need to be properly bridged
//
func _toNSArray<T, U : AnyObject>(_ a: [T], f: (T) -> U) -> NSArray {
let result = NSMutableArray(capacity: a.count)
for s in a {
result.add(f(s))
}
return result
}
func _toNSRange(_ r: Range<String.Index>) -> NSRange {
return NSRange(
location: r.lowerBound._utf16Index,
length: r.upperBound._utf16Index - r.lowerBound._utf16Index)
}
// We only need this for UnsafeMutablePointer, but there's not currently a way
// to write that constraint.
extension Optional {
/// Invokes `body` with `nil` if `self` is `nil`; otherwise, passes the
/// address of `object` to `body`.
///
/// This is intended for use with Foundation APIs that return an Objective-C
/// type via out-parameter where it is important to be able to *ignore* that
/// parameter by passing `nil`. (For some APIs, this may allow the
/// implementation to avoid some work.)
///
/// In most cases it would be simpler to just write this code inline, but if
/// `body` is complicated than that results in unnecessarily repeated code.
internal func _withNilOrAddress<NSType : AnyObject, ResultType>(
of object: inout NSType?,
_ body:
(AutoreleasingUnsafeMutablePointer<NSType?>?) -> ResultType
) -> ResultType {
return self == nil ? body(nil) : body(&object)
}
}
extension String {
//===--- Bridging Helpers -----------------------------------------------===//
//===--------------------------------------------------------------------===//
/// The corresponding `NSString` - a convenience for bridging code.
var _ns: NSString {
return self as NSString
}
/// Return an `Index` corresponding to the given offset in our UTF-16
/// representation.
func _index(_ utf16Index: Int) -> Index {
return Index(
_base: String.UnicodeScalarView.Index(_position: utf16Index),
in: characters
)
}
/// Return a `Range<Index>` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _range(_ r: NSRange) -> Range<Index> {
return _index(r.location)..<_index(r.location + r.length)
}
/// Return a `Range<Index>?` corresponding to the given `NSRange` of
/// our UTF-16 representation.
func _optionalRange(_ r: NSRange) -> Range<Index>? {
if r.location == NSNotFound {
return nil
}
return _range(r)
}
/// Invoke `body` on an `Int` buffer. If `index` was converted from
/// non-`nil`, convert the buffer to an `Index` and write it into the
/// memory referred to by `index`
func _withOptionalOutParameter<Result>(
_ index: UnsafeMutablePointer<Index>?,
_ body: (UnsafeMutablePointer<Int>?) -> Result
) -> Result {
var utf16Index: Int = 0
let result = (index != nil ? body(&utf16Index) : body(nil))
index?.pointee = self._index(utf16Index)
return result
}
/// Invoke `body` on an `NSRange` buffer. If `range` was converted
/// from non-`nil`, convert the buffer to a `Range<Index>` and write
/// it into the memory referred to by `range`
func _withOptionalOutParameter<Result>(
_ range: UnsafeMutablePointer<Range<Index>>?,
_ body: (UnsafeMutablePointer<NSRange>?) -> Result
) -> Result {
var nsRange = NSRange(location: 0, length: 0)
let result = (range != nil ? body(&nsRange) : body(nil))
range?.pointee = self._range(nsRange)
return result
}
//===--- Class Methods --------------------------------------------------===//
//===--------------------------------------------------------------------===//
// @property (class) const NSStringEncoding *availableStringEncodings;
/// Returns an Array of the encodings string objects support
/// in the application's environment.
public static var availableStringEncodings: [Encoding] {
var result = [Encoding]()
var p = NSString.availableStringEncodings
while p.pointee != 0 {
result.append(Encoding(rawValue: p.pointee))
p += 1
}
return result
}
// @property (class) NSStringEncoding defaultCStringEncoding;
/// Returns the C-string encoding assumed for any method accepting
/// a C string as an argument.
public static var defaultCStringEncoding: Encoding {
return Encoding(rawValue: NSString.defaultCStringEncoding)
}
// + (NSString *)localizedNameOfStringEncoding:(NSStringEncoding)encoding
/// Returns a human-readable string giving the name of a given encoding.
public static func localizedName(
of encoding: Encoding
) -> String {
return NSString.localizedName(of: encoding.rawValue)
}
// + (instancetype)localizedStringWithFormat:(NSString *)format, ...
/// Returns a string created by using a given format string as a
/// template into which the remaining argument values are substituted
/// according to the user's default locale.
public static func localizedStringWithFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return String(format: format, locale: Locale.current,
arguments: arguments)
}
// + (NSString *)pathWithComponents:(NSArray *)components
/// Returns a string built from the strings in a given array
/// by concatenating them with a path separator between each pair.
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func path(withComponents components: [String]) -> String {
return NSString.path(withComponents: components)
}
//===--------------------------------------------------------------------===//
// NSString factory functions that have a corresponding constructor
// are omitted.
//
// + (instancetype)string
//
// + (instancetype)
// stringWithCharacters:(const unichar *)chars length:(NSUInteger)length
//
// + (instancetype)stringWithFormat:(NSString *)format, ...
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
//
// + (instancetype)
// stringWithCString:(const char *)cString
// encoding:(NSStringEncoding)enc
//===--------------------------------------------------------------------===//
//===--- Adds nothing for String beyond what String(s) does -------------===//
// + (instancetype)stringWithString:(NSString *)aString
//===--------------------------------------------------------------------===//
// + (instancetype)stringWithUTF8String:(const char *)bytes
/// Produces a string created by copying the data from a given
/// C array of UTF8-encoded bytes.
public init?(utf8String bytes: UnsafePointer<CChar>) {
if let ns = NSString(utf8String: bytes) {
self = ns as String
} else {
return nil
}
}
//===--- Instance Methods/Properties-------------------------------------===//
//===--------------------------------------------------------------------===//
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// @property BOOL boolValue;
// - (BOOL)canBeConvertedToEncoding:(NSStringEncoding)encoding
/// Returns a Boolean value that indicates whether the
/// `String` can be converted to a given encoding without loss of
/// information.
public func canBeConverted(to encoding: Encoding) -> Bool {
return _ns.canBeConverted(to: encoding.rawValue)
}
// @property NSString* capitalizedString
/// Produce a string with the first character from each word changed
/// to the corresponding uppercase value.
public var capitalized: String {
return _ns.capitalized as String
}
// @property (readonly, copy) NSString *localizedCapitalizedString NS_AVAILABLE(10_11, 9_0);
/// A capitalized representation of the `String` that is produced
/// using the current locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedCapitalized: String {
return _ns.localizedCapitalized
}
// - (NSString *)capitalizedStringWithLocale:(Locale *)locale
/// Returns a capitalized representation of the `String`
/// using the specified locale.
public func capitalized(with locale: Locale?) -> String {
return _ns.capitalized(with: locale) as String
}
// - (NSComparisonResult)caseInsensitiveCompare:(NSString *)aString
/// Returns the result of invoking `compare:options:` with
/// `NSCaseInsensitiveSearch` as the only option.
public func caseInsensitiveCompare(_ aString: String) -> ComparisonResult {
return _ns.caseInsensitiveCompare(aString)
}
//===--- Omitted by agreement during API review 5/20/2014 ---------------===//
// - (unichar)characterAtIndex:(NSUInteger)index
//
// We have a different meaning for "Character" in Swift, and we are
// trying not to expose error-prone UTF-16 integer indexes
// - (NSString *)
// commonPrefixWithString:(NSString *)aString
// options:(StringCompareOptions)mask
/// Returns a string containing characters the `String` and a
/// given string have in common, starting from the beginning of each
/// up to the first characters that aren't equivalent.
public func commonPrefix(
with aString: String, options: CompareOptions = []) -> String {
return _ns.commonPrefix(with: aString, options: options)
}
// - (NSComparisonResult)
// compare:(NSString *)aString
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range
//
// - (NSComparisonResult)
// compare:(NSString *)aString options:(StringCompareOptions)mask
// range:(NSRange)range locale:(id)locale
/// Compares the string using the specified options and
/// returns the lexical ordering for the range.
public func compare(
_ aString: String,
options mask: CompareOptions = [],
range: Range<Index>? = nil,
locale: Locale? = nil
) -> ComparisonResult {
// According to Ali Ozer, there may be some real advantage to
// dispatching to the minimal selector for the supplied options.
// So let's do that; the switch should compile away anyhow.
return locale != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(
range ?? self.characters.startIndex..<self.characters.endIndex
),
locale: locale
)
: range != nil ? _ns.compare(
aString,
options: mask,
range: _toNSRange(range!)
)
: !mask.isEmpty ? _ns.compare(aString, options: mask)
: _ns.compare(aString)
}
// - (NSUInteger)
// completePathIntoString:(NSString **)outputName
// caseSensitive:(BOOL)flag
// matchesIntoArray:(NSArray **)outputArray
// filterTypes:(NSArray *)filterTypes
/// Interprets the `String` as a path in the file system and
/// attempts to perform filename completion, returning a numeric
/// value that indicates whether a match was possible, and by
/// reference the longest path that matches the `String`.
/// Returns the actual number of matching paths.
public func completePath(
into outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto outputArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
var nsMatches: NSArray?
var nsOutputName: NSString?
let result: Int = outputName._withNilOrAddress(of: &nsOutputName) {
outputName in outputArray._withNilOrAddress(of: &nsMatches) {
outputArray in
// FIXME: completePath(...) is incorrectly annotated as requiring
// non-optional output parameters. rdar://problem/25494184
let outputNonOptionalName = unsafeBitCast(
outputName, to: AutoreleasingUnsafeMutablePointer<NSString?>.self)
let outputNonOptionalArray = unsafeBitCast(
outputArray, to: AutoreleasingUnsafeMutablePointer<NSArray?>.self)
return self._ns.completePath(
into: outputNonOptionalName,
caseSensitive: caseSensitive,
matchesInto: outputNonOptionalArray,
filterTypes: filterTypes
)
}
}
if let matches = nsMatches {
// Since this function is effectively a bridge thunk, use the
// bridge thunk semantics for the NSArray conversion
outputArray?.pointee = matches as! [String]
}
if let n = nsOutputName {
outputName?.pointee = n as String
}
return result
}
// - (NSArray *)
// componentsSeparatedByCharactersInSet:(NSCharacterSet *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by characters in a given set.
public func components(separatedBy separator: CharacterSet) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (NSArray *)componentsSeparatedByString:(NSString *)separator
/// Returns an array containing substrings from the `String`
/// that have been divided by a given separator.
public func components(separatedBy separator: String) -> [String] {
return _ns.components(separatedBy: separator)
}
// - (const char *)cStringUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` as a C string
/// using a given encoding.
public func cString(using encoding: Encoding) -> [CChar]? {
return withExtendedLifetime(_ns) {
(s: NSString) -> [CChar]? in
_persistCString(s.cString(using: encoding.rawValue))
}
}
// - (NSData *)dataUsingEncoding:(NSStringEncoding)encoding
//
// - (NSData *)
// dataUsingEncoding:(NSStringEncoding)encoding
// allowLossyConversion:(BOOL)flag
/// Returns a `Data` containing a representation of
/// the `String` encoded using a given encoding.
public func data(
using encoding: Encoding,
allowLossyConversion: Bool = false
) -> Data? {
return _ns.data(
using: encoding.rawValue,
allowLossyConversion: allowLossyConversion)
}
// @property NSString* decomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form D.
public var decomposedStringWithCanonicalMapping: String {
return _ns.decomposedStringWithCanonicalMapping
}
// @property NSString* decomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form KD.
public var decomposedStringWithCompatibilityMapping: String {
return _ns.decomposedStringWithCompatibilityMapping
}
//===--- Importing Foundation should not affect String printing ---------===//
// Therefore, we're not exposing this:
//
// @property NSString* description
//===--- Omitted for consistency with API review results 5/20/2014 -----===//
// @property double doubleValue;
// - (void)
// enumerateLinesUsing:(void (^)(NSString *line, BOOL *stop))block
/// Enumerates all the lines in a string.
public func enumerateLines(
invoking body: @escaping (_ line: String, _ stop: inout Bool) -> Void
) {
_ns.enumerateLines {
(line: String, stop: UnsafeMutablePointer<ObjCBool>)
in
var stop_ = false
body(line, &stop_)
if stop_ {
stop.pointee = true
}
}
}
// - (void)
// enumerateLinguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// usingBlock:(
// void (^)(
// NSString *tag, NSRange tokenRange,
// NSRange sentenceRange, BOOL *stop)
// )block
/// Performs linguistic analysis on the specified string by
/// enumerating the specific range of the string, providing the
/// Block with the located tags.
public func enumerateLinguisticTags(
in range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
invoking body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
_ns.enumerateLinguisticTags(
in: _toNSRange(range),
scheme: tagScheme,
options: opts,
orthography: orthography != nil ? orthography! : nil
) {
var stop_ = false
body($0, self._range($1), self._range($2), &stop_)
if stop_ {
$3.pointee = true
}
}
}
// - (void)
// enumerateSubstringsInRange:(NSRange)range
// options:(NSStringEnumerationOptions)opts
// usingBlock:(
// void (^)(
// NSString *substring,
// NSRange substringRange,
// NSRange enclosingRange,
// BOOL *stop)
// )block
/// Enumerates the substrings of the specified type in the
/// specified range of the string.
public func enumerateSubstrings(
in range: Range<Index>,
options opts: EnumerationOptions = [],
_ body: @escaping (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
_ns.enumerateSubstrings(in: _toNSRange(range), options: opts) {
var stop_ = false
body($0,
self._range($1),
self._range($2),
&stop_)
if stop_ {
UnsafeMutablePointer($3).pointee = true
}
}
}
// @property NSStringEncoding fastestEncoding;
/// Returns the fastest encoding to which the `String` may be
/// converted without loss of information.
public var fastestEncoding: Encoding {
return Encoding(rawValue: _ns.fastestEncoding)
}
// - (const char *)fileSystemRepresentation
/// Returns a file system-specific representation of the `String`.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public var fileSystemRepresentation: [CChar] {
return _persistCString(_ns.fileSystemRepresentation)!
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property float floatValue;
// - (BOOL)
// getBytes:(void *)buffer
// maxLength:(NSUInteger)maxBufferCount
// usedLength:(NSUInteger*)usedBufferCount
// encoding:(NSStringEncoding)encoding
// options:(StringEncodingConversionOptions)options
// range:(NSRange)range
// remainingRange:(NSRangePointer)leftover
/// Writes the given `range` of characters into `buffer` in a given
/// `encoding`, without any allocations. Does not NULL-terminate.
///
/// - Parameter buffer: A buffer into which to store the bytes from
/// the receiver. The returned bytes are not NUL-terminated.
///
/// - Parameter maxBufferCount: The maximum number of bytes to write
/// to buffer.
///
/// - Parameter usedBufferCount: The number of bytes used from
/// buffer. Pass `nil` if you do not need this value.
///
/// - Parameter encoding: The encoding to use for the returned bytes.
///
/// - Parameter options: A mask to specify options to use for
/// converting the receiver's contents to `encoding` (if conversion
/// is necessary).
///
/// - Parameter range: The range of characters in the receiver to get.
///
/// - Parameter leftover: The remaining range. Pass `nil` If you do
/// not need this value.
///
/// - Returns: `true` iff some characters were converted.
///
/// - Note: Conversion stops when the buffer fills or when the
/// conversion isn't possible due to the chosen encoding.
///
/// - Note: will get a maximum of `min(buffer.count, maxLength)` bytes.
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: Encoding,
options: EncodingConversionOptions = [],
range: Range<Index>,
remaining leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
return _withOptionalOutParameter(leftover) {
self._ns.getBytes(
&buffer,
maxLength: min(buffer.count, maxBufferCount),
usedLength: usedBufferCount,
encoding: encoding.rawValue,
options: options,
range: _toNSRange(range),
remaining: $0)
}
}
// - (BOOL)
// getCString:(char *)buffer
// maxLength:(NSUInteger)maxBufferCount
// encoding:(NSStringEncoding)encoding
/// Converts the `String`'s content to a given encoding and
/// stores them in a buffer.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
public func getCString(
_ buffer: inout [CChar], maxLength: Int, encoding: Encoding
) -> Bool {
return _ns.getCString(&buffer, maxLength: min(buffer.count, maxLength),
encoding: encoding.rawValue)
}
// - (BOOL)
// getFileSystemRepresentation:(char *)buffer
// maxLength:(NSUInteger)maxLength
/// Interprets the `String` as a system-independent path and
/// fills a buffer with a C-string in a format and encoding suitable
/// for use with file-system calls.
/// - Note: will store a maximum of `min(buffer.count, maxLength)` bytes.
@available(*, unavailable, message: "Use getFileSystemRepresentation on URL instead.")
public func getFileSystemRepresentation(
_ buffer: inout [CChar], maxLength: Int) -> Bool {
return _ns.getFileSystemRepresentation(
&buffer, maxLength: min(buffer.count, maxLength))
}
// - (void)
// getLineStart:(NSUInteger *)startIndex
// end:(NSUInteger *)lineEndIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first line and
/// the end of the last line touched by the given range.
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getLineStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (void)
// getParagraphStart:(NSUInteger *)startIndex
// end:(NSUInteger *)endIndex
// contentsEnd:(NSUInteger *)contentsEndIndex
// forRange:(NSRange)aRange
/// Returns by reference the beginning of the first paragraph
/// and the end of the last paragraph touched by the given range.
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
for range: Range<Index>
) {
_withOptionalOutParameter(start) {
start in self._withOptionalOutParameter(end) {
end in self._withOptionalOutParameter(contentsEnd) {
contentsEnd in self._ns.getParagraphStart(
start, end: end,
contentsEnd: contentsEnd,
for: _toNSRange(range))
}
}
}
}
// - (NSUInteger)hash
/// An unsigned integer that can be used as a hash table address.
public var hash: Int {
return _ns.hash
}
//===--- Already provided by String's core ------------------------------===//
// - (instancetype)init
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithBytes:(const void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
/// Produces an initialized `NSString` object equivalent to the given
/// `bytes` interpreted in the given `encoding`.
public init? <S: Sequence>(bytes: S, encoding: Encoding)
where S.Iterator.Element == UInt8 {
let byteArray = Array(bytes)
if let ns = NSString(
bytes: byteArray, length: byteArray.count, encoding: encoding.rawValue) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithBytesNoCopy:(void *)bytes
// length:(NSUInteger)length
// encoding:(NSStringEncoding)encoding
// freeWhenDone:(BOOL)flag
/// Produces an initialized `String` object that contains a
/// given number of bytes from a given buffer of bytes interpreted
/// in a given encoding, and optionally frees the buffer. WARNING:
/// this initializer is not memory-safe!
public init?(
bytesNoCopy bytes: UnsafeMutableRawPointer, length: Int,
encoding: Encoding, freeWhenDone flag: Bool
) {
if let ns = NSString(
bytesNoCopy: bytes, length: length, encoding: encoding.rawValue,
freeWhenDone: flag) {
self = ns as String
} else {
return nil
}
}
// - (instancetype)
// initWithCharacters:(const unichar *)characters
// length:(NSUInteger)length
/// Returns an initialized `String` object that contains a
/// given number of characters from a given array of Unicode
/// characters.
public init(
utf16CodeUnits: UnsafePointer<unichar>,
count: Int
) {
self = NSString(characters: utf16CodeUnits, length: count) as String
}
// - (instancetype)
// initWithCharactersNoCopy:(unichar *)characters
// length:(NSUInteger)length
// freeWhenDone:(BOOL)flag
/// Returns an initialized `String` object that contains a given
/// number of characters from a given array of UTF-16 Code Units
public init(
utf16CodeUnitsNoCopy: UnsafePointer<unichar>,
count: Int,
freeWhenDone flag: Bool
) {
self = NSString(
charactersNoCopy: UnsafeMutablePointer(mutating: utf16CodeUnitsNoCopy),
length: count,
freeWhenDone: flag) as String
}
//===--- Initializers that can fail -------------------------------------===//
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
//
/// Produces a string created by reading data from the file at a
/// given path interpreted using a given encoding.
public init(
contentsOfFile path: String,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOfFile: path, encoding: enc.rawValue)
self = ns as String
}
// - (instancetype)
// initWithContentsOfFile:(NSString *)path
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from the file at
/// a given path and returns by reference the encoding used to
/// interpret the file.
public init(
contentsOfFile path: String,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOfFile: path, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns as String
}
public init(
contentsOfFile path: String
) throws {
let ns = try NSString(contentsOfFile: path, usedEncoding: nil)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// encoding:(NSStringEncoding)enc
// error:(NSError**)error
/// Produces a string created by reading data from a given URL
/// interpreted using a given encoding. Errors are written into the
/// inout `error` argument.
public init(
contentsOf url: URL,
encoding enc: Encoding
) throws {
let ns = try NSString(contentsOf: url, encoding: enc.rawValue)
self = ns as String
}
// - (instancetype)
// initWithContentsOfURL:(NSURL *)url
// usedEncoding:(NSStringEncoding *)enc
// error:(NSError **)error
/// Produces a string created by reading data from a given URL
/// and returns by reference the encoding used to interpret the
/// data. Errors are written into the inout `error` argument.
public init(
contentsOf url: URL,
usedEncoding: inout Encoding
) throws {
var enc: UInt = 0
let ns = try NSString(contentsOf: url as URL, usedEncoding: &enc)
usedEncoding = Encoding(rawValue: enc)
self = ns as String
}
public init(
contentsOf url: URL
) throws {
let ns = try NSString(contentsOf: url, usedEncoding: nil)
self = ns as String
}
// - (instancetype)
// initWithCString:(const char *)nullTerminatedCString
// encoding:(NSStringEncoding)encoding
/// Produces a string containing the bytes in a given C array,
/// interpreted according to a given encoding.
public init?(
cString: UnsafePointer<CChar>,
encoding enc: Encoding
) {
if let ns = NSString(cString: cString, encoding: enc.rawValue) {
self = ns as String
} else {
return nil
}
}
// FIXME: handle optional locale with default arguments
// - (instancetype)
// initWithData:(NSData *)data
// encoding:(NSStringEncoding)encoding
/// Returns a `String` initialized by converting given `data` into
/// Unicode characters using a given `encoding`.
public init?(data: Data, encoding: Encoding) {
guard let s = NSString(data: data, encoding: encoding.rawValue) else { return nil }
self = s as String
}
// - (instancetype)initWithFormat:(NSString *)format, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted.
public init(format: String, _ arguments: CVarArg...) {
self = String(format: format, arguments: arguments)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to the user's default locale.
public init(format: String, arguments: [CVarArg]) {
self = String(format: format, locale: nil, arguments: arguments)
}
// - (instancetype)initWithFormat:(NSString *)format locale:(id)locale, ...
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, _ args: CVarArg...) {
self = String(format: format, locale: locale, arguments: args)
}
// - (instancetype)
// initWithFormat:(NSString *)format
// locale:(id)locale
// arguments:(va_list)argList
/// Returns a `String` object initialized by using a given
/// format string as a template into which the remaining argument
/// values are substituted according to given locale information.
public init(format: String, locale: Locale?, arguments: [CVarArg]) {
self = withVaList(arguments) {
NSString(format: format, locale: locale, arguments: $0) as String
}
}
//===--- Already provided by core Swift ---------------------------------===//
// - (instancetype)initWithString:(NSString *)aString
//===--- Initializers that can fail dropped for factory functions -------===//
// - (instancetype)initWithUTF8String:(const char *)bytes
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property NSInteger integerValue;
// @property Int intValue;
//===--- Omitted by apparent agreement during API review 5/20/2014 ------===//
// @property BOOL absolutePath;
// - (BOOL)isEqualToString:(NSString *)aString
//===--- Kept for consistency with API review results 5/20/2014 ---------===//
// We decided to keep pathWithComponents, so keeping this too
// @property NSString lastPathComponent;
/// Returns the last path component of the `String`.
@available(*, unavailable, message: "Use lastPathComponent on URL instead.")
public var lastPathComponent: String {
return _ns.lastPathComponent
}
//===--- Renamed by agreement during API review 5/20/2014 ---------------===//
// @property NSUInteger length;
/// Returns the number of Unicode characters in the `String`.
@available(*, unavailable,
message: "Take the count of a UTF-16 view instead, i.e. str.utf16.count")
public var utf16Count: Int {
return _ns.length
}
// - (NSUInteger)lengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the number of bytes required to store the
/// `String` in a given encoding.
public func lengthOfBytes(using encoding: Encoding) -> Int {
return _ns.lengthOfBytes(using: encoding.rawValue)
}
// - (NSRange)lineRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the line or lines
/// containing a given range.
public func lineRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.lineRange(for: _toNSRange(aRange)))
}
// - (NSArray *)
// linguisticTagsInRange:(NSRange)range
// scheme:(NSString *)tagScheme
// options:(LinguisticTaggerOptions)opts
// orthography:(Orthography *)orthography
// tokenRanges:(NSArray**)tokenRanges
/// Returns an array of linguistic tags for the specified
/// range and requested tags within the receiving string.
public func linguisticTags(
in range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil // FIXME:Can this be nil?
) -> [String] {
var nsTokenRanges: NSArray?
let result = tokenRanges._withNilOrAddress(of: &nsTokenRanges) {
self._ns.linguisticTags(
in: _toNSRange(range), scheme: tagScheme, options: opts,
orthography: orthography, tokenRanges: $0) as NSArray
}
if nsTokenRanges != nil {
tokenRanges?.pointee = (nsTokenRanges! as [AnyObject]).map {
self._range($0.rangeValue)
}
}
return result as! [String]
}
// - (NSComparisonResult)localizedCaseInsensitiveCompare:(NSString *)aString
/// Compares the string and a given string using a
/// case-insensitive, localized, comparison.
public
func localizedCaseInsensitiveCompare(_ aString: String) -> ComparisonResult {
return _ns.localizedCaseInsensitiveCompare(aString)
}
// - (NSComparisonResult)localizedCompare:(NSString *)aString
/// Compares the string and a given string using a localized
/// comparison.
public func localizedCompare(_ aString: String) -> ComparisonResult {
return _ns.localizedCompare(aString)
}
/// Compares strings as sorted by the Finder.
public func localizedStandardCompare(_ string: String) -> ComparisonResult {
return _ns.localizedStandardCompare(string)
}
//===--- Omitted for consistency with API review results 5/20/2014 ------===//
// @property long long longLongValue
// @property (readonly, copy) NSString *localizedLowercase NS_AVAILABLE(10_11, 9_0);
/// A lowercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedLowercase: String {
return _ns.localizedLowercase
}
// - (NSString *)lowercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to lowercase, taking into account the specified
/// locale.
public func lowercased(with locale: Locale?) -> String {
return _ns.lowercased(with: locale)
}
// - (NSUInteger)maximumLengthOfBytesUsingEncoding:(NSStringEncoding)enc
/// Returns the maximum number of bytes needed to store the
/// `String` in a given encoding.
public
func maximumLengthOfBytes(using encoding: Encoding) -> Int {
return _ns.maximumLengthOfBytes(using: encoding.rawValue)
}
// - (NSRange)paragraphRangeForRange:(NSRange)aRange
/// Returns the range of characters representing the
/// paragraph or paragraphs containing a given range.
public func paragraphRange(for aRange: Range<Index>) -> Range<Index> {
return _range(_ns.paragraphRange(for: _toNSRange(aRange)))
}
// @property NSArray* pathComponents
/// Returns an array of NSString objects containing, in
/// order, each path component of the `String`.
@available(*, unavailable, message: "Use pathComponents on URL instead.")
public var pathComponents: [String] {
return _ns.pathComponents
}
// @property NSString* pathExtension;
/// Interprets the `String` as a path and returns the
/// `String`'s extension, if any.
@available(*, unavailable, message: "Use pathExtension on URL instead.")
public var pathExtension: String {
return _ns.pathExtension
}
// @property NSString* precomposedStringWithCanonicalMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form C.
public var precomposedStringWithCanonicalMapping: String {
return _ns.precomposedStringWithCanonicalMapping
}
// @property NSString * precomposedStringWithCompatibilityMapping;
/// Returns a string made by normalizing the `String`'s
/// contents using Form KC.
public var precomposedStringWithCompatibilityMapping: String {
return _ns.precomposedStringWithCompatibilityMapping
}
// - (id)propertyList
/// Parses the `String` as a text representation of a
/// property list, returning an NSString, NSData, NSArray, or
/// NSDictionary object, according to the topmost element.
public func propertyList() -> Any {
return _ns.propertyList()
}
// - (NSDictionary *)propertyListFromStringsFileFormat
/// Returns a dictionary object initialized with the keys and
/// values found in the `String`.
public
func propertyListFromStringsFileFormat() -> [String : String] {
return _ns.propertyListFromStringsFileFormat() as! [String : String]? ?? [:]
}
// - (NSRange)rangeOfCharacterFromSet:(NSCharacterSet *)aSet
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfCharacterFromSet:(NSCharacterSet *)aSet
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
/// Finds and returns the range in the `String` of the first
/// character from a given character set found in a given range with
/// given options.
public func rangeOfCharacter(
from aSet: CharacterSet,
options mask: CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
return _optionalRange(
_ns.rangeOfCharacter(
from: aSet,
options: mask,
range: _toNSRange(
aRange ?? self.characters.startIndex..<self.characters.endIndex
)
)
)
}
// - (NSRange)rangeOfComposedCharacterSequenceAtIndex:(NSUInteger)anIndex
/// Returns the range in the `String` of the composed
/// character sequence located at a given index.
public
func rangeOfComposedCharacterSequence(at anIndex: Index) -> Range<Index> {
return _range(
_ns.rangeOfComposedCharacterSequence(at: anIndex._utf16Index))
}
// - (NSRange)rangeOfComposedCharacterSequencesForRange:(NSRange)range
/// Returns the range in the string of the composed character
/// sequences for a given range.
public func rangeOfComposedCharacterSequences(
for range: Range<Index>
) -> Range<Index> {
// Theoretically, this will be the identity function. In practice
// I think users will be able to observe differences in the input
// and output ranges due (if nothing else) to locale changes
return _range(
_ns.rangeOfComposedCharacterSequences(for: _toNSRange(range)))
}
// - (NSRange)rangeOfString:(NSString *)aString
//
// - (NSRange)
// rangeOfString:(NSString *)aString options:(StringCompareOptions)mask
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)aRange
//
// - (NSRange)
// rangeOfString:(NSString *)aString
// options:(StringCompareOptions)mask
// range:(NSRange)searchRange
// locale:(Locale *)locale
/// Finds and returns the range of the first occurrence of a
/// given string within a given range of the `String`, subject to
/// given options, using the specified locale, if any.
public func range(
of aString: String,
options mask: CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
return _optionalRange(
locale != nil ? _ns.range(
of: aString,
options: mask,
range: _toNSRange(
searchRange ?? self.characters.startIndex..<self.characters.endIndex
),
locale: locale
)
: searchRange != nil ? _ns.range(
of: aString, options: mask, range: _toNSRange(searchRange!)
)
: !mask.isEmpty ? _ns.range(of: aString, options: mask)
: _ns.range(of: aString)
)
}
// - (BOOL)localizedStandardContainsString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Returns `true` if `self` contains `string`, taking the current locale
/// into account.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardContains(_ string: String) -> Bool {
return _ns.localizedStandardContains(string)
}
// - (NSRange)localizedStandardRangeOfString:(NSString *)str NS_AVAILABLE(10_11, 9_0);
/// Finds and returns the range of the first occurrence of a given string,
/// taking the current locale into account. Returns `nil` if the string was
/// not found.
///
/// This is the most appropriate method for doing user-level string searches,
/// similar to how searches are done generally in the system. The search is
/// locale-aware, case and diacritic insensitive. The exact list of search
/// options applied may change over time.
@available(OSX 10.11, iOS 9.0, *)
public func localizedStandardRange(of string: String) -> Range<Index>? {
return _optionalRange(_ns.localizedStandardRange(of: string))
}
// @property NSStringEncoding smallestEncoding;
/// Returns the smallest encoding to which the `String` can
/// be converted without loss of information.
public var smallestEncoding: Encoding {
return Encoding(rawValue: _ns.smallestEncoding)
}
// @property NSString *stringByAbbreviatingWithTildeInPath;
/// Returns a new string that replaces the current home
/// directory portion of the current path with a tilde (`~`)
/// character.
@available(*, unavailable, message: "Use abbreviatingWithTildeInPath on NSString instead.")
public var abbreviatingWithTildeInPath: String {
return _ns.abbreviatingWithTildeInPath
}
// - (NSString *)
// stringByAddingPercentEncodingWithAllowedCharacters:
// (NSCharacterSet *)allowedCharacters
/// Returns a new string made from the `String` by replacing
/// all characters not in the specified set with percent encoded
/// characters.
public func addingPercentEncoding(
withAllowedCharacters allowedCharacters: CharacterSet
) -> String? {
// FIXME: the documentation states that this method can return nil if the
// transformation is not possible, without going into further details. The
// implementation can only return nil if malloc() returns nil, so in
// practice this is not possible. Still, to be consistent with
// documentation, we declare the method as returning an optional String.
//
// <rdar://problem/17901698> Docs for -[NSString
// stringByAddingPercentEncodingWithAllowedCharacters] don't precisely
// describe when return value is nil
return _ns.addingPercentEncoding(withAllowedCharacters:
allowedCharacters
)
}
// - (NSString *)
// stringByAddingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a representation of the `String` using a given
/// encoding to determine the percent escapes necessary to convert
/// the `String` into a legal URL string.
@available(*, deprecated, message: "Use addingPercentEncoding(withAllowedCharacters:) instead, which always uses the recommended UTF-8 encoding, and which encodes for a specific URL component or subcomponent since each URL component or subcomponent has different rules for what characters are valid.")
public func addingPercentEscapes(
using encoding: Encoding
) -> String? {
return _ns.addingPercentEscapes(using: encoding.rawValue)
}
// - (NSString *)stringByAppendingFormat:(NSString *)format, ...
/// Returns a string made by appending to the `String` a
/// string constructed from a given format string and the following
/// arguments.
public func appendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
return _ns.appending(
String(format: format, arguments: arguments))
}
// - (NSString *)stringByAppendingPathComponent:(NSString *)aString
/// Returns a new string made by appending to the `String` a given string.
@available(*, unavailable, message: "Use appendingPathComponent on URL instead.")
public func appendingPathComponent(_ aString: String) -> String {
return _ns.appendingPathComponent(aString)
}
// - (NSString *)stringByAppendingPathExtension:(NSString *)ext
/// Returns a new string made by appending to the `String` an
/// extension separator followed by a given extension.
@available(*, unavailable, message: "Use appendingPathExtension on URL instead.")
public func appendingPathExtension(_ ext: String) -> String? {
// FIXME: This method can return nil in practice, for example when self is
// an empty string. OTOH, this is not documented, documentation says that
// it always returns a string.
//
// <rdar://problem/17902469> -[NSString stringByAppendingPathExtension] can
// return nil
return _ns.appendingPathExtension(ext)
}
// - (NSString *)stringByAppendingString:(NSString *)aString
/// Returns a new string made by appending a given string to
/// the `String`.
public func appending(_ aString: String) -> String {
return _ns.appending(aString)
}
// @property NSString* stringByDeletingLastPathComponent;
/// Returns a new string made by deleting the last path
/// component from the `String`, along with any final path
/// separator.
@available(*, unavailable, message: "Use deletingLastPathComponent on URL instead.")
public var deletingLastPathComponent: String {
return _ns.deletingLastPathComponent
}
// @property NSString* stringByDeletingPathExtension;
/// Returns a new string made by deleting the extension (if
/// any, and only the last) from the `String`.
@available(*, unavailable, message: "Use deletingPathExtension on URL instead.")
public var deletingPathExtension: String {
return _ns.deletingPathExtension
}
// @property NSString* stringByExpandingTildeInPath;
/// Returns a new string made by expanding the initial
/// component of the `String` to its full path value.
@available(*, unavailable, message: "Use expandingTildeInPath on NSString instead.")
public var expandingTildeInPath: String {
return _ns.expandingTildeInPath
}
// - (NSString *)
// stringByFoldingWithOptions:(StringCompareOptions)options
// locale:(Locale *)locale
@available(*, unavailable, renamed: "folding(options:locale:)")
public func folding(
_ options: CompareOptions = [], locale: Locale?
) -> String {
return folding(options: options, locale: locale)
}
/// Returns a string with the given character folding options
/// applied.
public func folding(
options: CompareOptions = [], locale: Locale?
) -> String {
return _ns.folding(options: options, locale: locale)
}
// - (NSString *)stringByPaddingToLength:(NSUInteger)newLength
// withString:(NSString *)padString
// startingAtIndex:(NSUInteger)padIndex
/// Returns a new string formed from the `String` by either
/// removing characters from the end, or by appending as many
/// occurrences as necessary of a given pad string.
public func padding(
toLength newLength: Int,
withPad padString: String,
startingAt padIndex: Int
) -> String {
return _ns.padding(
toLength: newLength, withPad: padString, startingAt: padIndex)
}
// @property NSString* stringByRemovingPercentEncoding;
/// Returns a new string made from the `String` by replacing
/// all percent encoded sequences with the matching UTF-8
/// characters.
public var removingPercentEncoding: String? {
return _ns.removingPercentEncoding
}
// - (NSString *)
// stringByReplacingCharactersInRange:(NSRange)range
// withString:(NSString *)replacement
/// Returns a new string in which the characters in a
/// specified range of the `String` are replaced by a given string.
public func replacingCharacters(
in range: Range<Index>, with replacement: String
) -> String {
return _ns.replacingCharacters(in: _toNSRange(range), with: replacement)
}
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
//
// - (NSString *)
// stringByReplacingOccurrencesOfString:(NSString *)target
// withString:(NSString *)replacement
// options:(StringCompareOptions)options
// range:(NSRange)searchRange
/// Returns a new string in which all occurrences of a target
/// string in a specified range of the `String` are replaced by
/// another given string.
public func replacingOccurrences(
of target: String,
with replacement: String,
options: CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
return (searchRange != nil) || (!options.isEmpty)
? _ns.replacingOccurrences(
of: target,
with: replacement,
options: options,
range: _toNSRange(
searchRange ?? self.characters.startIndex..<self.characters.endIndex
)
)
: _ns.replacingOccurrences(of: target, with: replacement)
}
// - (NSString *)
// stringByReplacingPercentEscapesUsingEncoding:(NSStringEncoding)encoding
/// Returns a new string made by replacing in the `String`
/// all percent escapes with the matching characters as determined
/// by a given encoding.
@available(*, deprecated, message: "Use removingPercentEncoding instead, which always uses the recommended UTF-8 encoding.")
public func replacingPercentEscapes(
using encoding: Encoding
) -> String? {
return _ns.replacingPercentEscapes(using: encoding.rawValue)
}
// @property NSString* stringByResolvingSymlinksInPath;
/// Returns a new string made from the `String` by resolving
/// all symbolic links and standardizing path.
@available(*, unavailable, message: "Use resolvingSymlinksInPath on URL instead.")
public var resolvingSymlinksInPath: String {
return _ns.resolvingSymlinksInPath
}
// @property NSString* stringByStandardizingPath;
/// Returns a new string made by removing extraneous path
/// components from the `String`.
@available(*, unavailable, message: "Use standardizingPath on URL instead.")
public var standardizingPath: String {
return _ns.standardizingPath
}
// - (NSString *)stringByTrimmingCharactersInSet:(NSCharacterSet *)set
/// Returns a new string made by removing from both ends of
/// the `String` characters contained in a given character set.
public func trimmingCharacters(in set: CharacterSet) -> String {
return _ns.trimmingCharacters(in: set)
}
// - (NSArray *)stringsByAppendingPaths:(NSArray *)paths
/// Returns an array of strings made by separately appending
/// to the `String` each string in a given array.
@available(*, unavailable, message: "Map over paths with appendingPathComponent instead.")
public func strings(byAppendingPaths paths: [String]) -> [String] {
fatalError("This function is not available")
}
// - (NSString *)substringFromIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` from the one at a given index to the end.
public func substring(from index: Index) -> String {
return _ns.substring(from: index._utf16Index)
}
// - (NSString *)substringToIndex:(NSUInteger)anIndex
/// Returns a new string containing the characters of the
/// `String` up to, but not including, the one at a given index.
public func substring(to index: Index) -> String {
return _ns.substring(to: index._utf16Index)
}
// - (NSString *)substringWithRange:(NSRange)aRange
/// Returns a string object containing the characters of the
/// `String` that lie within a given range.
public func substring(with aRange: Range<Index>) -> String {
return _ns.substring(with: _toNSRange(aRange))
}
// @property (readonly, copy) NSString *localizedUppercaseString NS_AVAILABLE(10_11, 9_0);
/// An uppercase version of the string that is produced using the current
/// locale.
@available(OSX 10.11, iOS 9.0, *)
public var localizedUppercase: String {
return _ns.localizedUppercase as String
}
// - (NSString *)uppercaseStringWithLocale:(Locale *)locale
/// Returns a version of the string with all letters
/// converted to uppercase, taking into account the specified
/// locale.
public func uppercased(with locale: Locale?) -> String {
return _ns.uppercased(with: locale)
}
//===--- Omitted due to redundancy with "utf8" property -----------------===//
// - (const char *)UTF8String
// - (BOOL)
// writeToFile:(NSString *)path
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to a file at a given
/// path using a given encoding.
public func write(
toFile path: String, atomically useAuxiliaryFile:Bool,
encoding enc: Encoding
) throws {
try self._ns.write(
toFile: path, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (BOOL)
// writeToURL:(NSURL *)url
// atomically:(BOOL)useAuxiliaryFile
// encoding:(NSStringEncoding)enc
// error:(NSError **)error
/// Writes the contents of the `String` to the URL specified
/// by url using the specified encoding.
public func write(
to url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: Encoding
) throws {
try self._ns.write(
to: url, atomically: useAuxiliaryFile, encoding: enc.rawValue)
}
// - (nullable NSString *)stringByApplyingTransform:(NSString *)transform reverse:(BOOL)reverse NS_AVAILABLE(10_11, 9_0);
/// Perform string transliteration.
@available(OSX 10.11, iOS 9.0, *)
public func applyingTransform(
_ transform: StringTransform, reverse: Bool
) -> String? {
return _ns.applyingTransform(transform, reverse: reverse)
}
//===--- From the 10.10 release notes; not in public documentation ------===//
// No need to make these unavailable on earlier OSes, since they can
// forward trivially to rangeOfString.
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-sensitive, non-literal search.
///
/// Equivalent to `self.rangeOfString(other) != nil`
public func contains(_ other: String) -> Bool {
let r = self.range(of: other) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.contains(other))
}
return r
}
/// Returns `true` iff `other` is non-empty and contained within
/// `self` by case-insensitive, non-literal search, taking into
/// account the current locale.
///
/// Locale-independent case-insensitive operation, and other needs,
/// can be achieved by calling
/// `rangeOfString(_:options:_, range:_locale:_)`.
///
/// Equivalent to
///
/// self.rangeOf(
/// other, options: .CaseInsensitiveSearch,
/// locale: Locale.current) != nil
public func localizedCaseInsensitiveContains(_ other: String) -> Bool {
let r = self.range(
of: other, options: .caseInsensitive, locale: Locale.current
) != nil
if #available(OSX 10.10, iOS 8.0, *) {
_sanityCheck(r == _ns.localizedCaseInsensitiveContains(other))
}
return r
}
}
// Pre-Swift-3 method names
extension String {
@available(*, unavailable, renamed: "localizedName(of:)")
public static func localizedNameOfStringEncoding(
_ encoding: Encoding
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, message: "Use fileURL(withPathComponents:) on URL instead.")
public static func pathWithComponents(_ components: [String]) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "canBeConverted(to:)")
public func canBeConvertedToEncoding(_ encoding: Encoding) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "capitalizedString(with:)")
public func capitalizedStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "commonPrefix(with:options:)")
public func commonPrefixWith(
_ aString: String, options: CompareOptions) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "completePath(into:outputName:caseSensitive:matchesInto:filterTypes:)")
public func completePathInto(
_ outputName: UnsafeMutablePointer<String>? = nil,
caseSensitive: Bool,
matchesInto matchesIntoArray: UnsafeMutablePointer<[String]>? = nil,
filterTypes: [String]? = nil
) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "components(separatedBy:)")
public func componentsSeparatedByCharactersIn(
_ separator: CharacterSet
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "componentsSeparated(by:)")
public func componentsSeparatedBy(_ separator: String) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "cString(usingEncoding:)")
public func cStringUsingEncoding(_ encoding: Encoding) -> [CChar]? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "data(usingEncoding:allowLossyConversion:)")
public func dataUsingEncoding(
_ encoding: Encoding,
allowLossyConversion: Bool = false
) -> Data? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "enumerateLinguisticTags(in:scheme:options:orthography:_:)")
public func enumerateLinguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options,
orthography: NSOrthography?,
_ body:
(String, Range<Index>, Range<Index>, inout Bool) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "enumerateSubstrings(in:options:_:)")
public func enumerateSubstringsIn(
_ range: Range<Index>,
options opts: EnumerationOptions = [],
_ body: (
_ substring: String?, _ substringRange: Range<Index>,
_ enclosingRange: Range<Index>, inout Bool
) -> Void
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getBytes(_:maxLength:usedLength:encoding:options:range:remaining:)")
public func getBytes(
_ buffer: inout [UInt8],
maxLength maxBufferCount: Int,
usedLength usedBufferCount: UnsafeMutablePointer<Int>,
encoding: Encoding,
options: EncodingConversionOptions = [],
range: Range<Index>,
remainingRange leftover: UnsafeMutablePointer<Range<Index>>
) -> Bool {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getLineStart(_:end:contentsEnd:for:)")
public func getLineStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "getParagraphStart(_:end:contentsEnd:for:)")
public func getParagraphStart(
_ start: UnsafeMutablePointer<Index>,
end: UnsafeMutablePointer<Index>,
contentsEnd: UnsafeMutablePointer<Index>,
forRange: Range<Index>
) {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lengthOfBytes(using:)")
public func lengthOfBytesUsingEncoding(_ encoding: Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lineRange(for:)")
public func lineRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "linguisticTags(in:scheme:options:orthography:tokenRanges:)")
public func linguisticTagsIn(
_ range: Range<Index>,
scheme tagScheme: String,
options opts: NSLinguisticTagger.Options = [],
orthography: NSOrthography? = nil,
tokenRanges: UnsafeMutablePointer<[Range<Index>]>? = nil
) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "lowercased(with:)")
public func lowercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "maximumLengthOfBytes(using:)")
public
func maximumLengthOfBytesUsingEncoding(_ encoding: Encoding) -> Int {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "paragraphRange(for:)")
public func paragraphRangeFor(_ aRange: Range<Index>) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfCharacter(from:options:range:)")
public func rangeOfCharacterFrom(
_ aSet: CharacterSet,
options mask: CompareOptions = [],
range aRange: Range<Index>? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequence(at:)")
public
func rangeOfComposedCharacterSequenceAt(_ anIndex: Index) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "rangeOfComposedCharacterSequences(for:)")
public func rangeOfComposedCharacterSequencesFor(
_ range: Range<Index>
) -> Range<Index> {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "range(of:options:range:locale:)")
public func rangeOf(
_ aString: String,
options mask: CompareOptions = [],
range searchRange: Range<Index>? = nil,
locale: Locale? = nil
) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "localizedStandardRange(of:)")
public func localizedStandardRangeOf(_ string: String) -> Range<Index>? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEncoding(withAllowedCharacters:)")
public func addingPercentEncodingWithAllowedCharacters(
_ allowedCharacters: CharacterSet
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "addingPercentEscapes(using:)")
public func addingPercentEscapesUsingEncoding(
_ encoding: Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "appendingFormat")
public func stringByAppendingFormat(
_ format: String, _ arguments: CVarArg...
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "padding(toLength:with:startingAt:)")
public func byPaddingToLength(
_ newLength: Int, withString padString: String, startingAt padIndex: Int
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingCharacters(in:with:)")
public func replacingCharactersIn(
_ range: Range<Index>, withString replacement: String
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingOccurrences(of:with:options:range:)")
public func replacingOccurrencesOf(
_ target: String,
withString replacement: String,
options: CompareOptions = [],
range searchRange: Range<Index>? = nil
) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "replacingPercentEscapes(usingEncoding:)")
public func replacingPercentEscapesUsingEncoding(
_ encoding: Encoding
) -> String? {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "trimmingCharacters(in:)")
public func byTrimmingCharactersIn(_ set: CharacterSet) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "strings(byAppendingPaths:)")
public func stringsByAppendingPaths(_ paths: [String]) -> [String] {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(from:)")
public func substringFrom(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(to:)")
public func substringTo(_ index: Index) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "substring(with:)")
public func substringWith(_ aRange: Range<Index>) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "uppercased(with:)")
public func uppercaseStringWith(_ locale: Locale?) -> String {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(toFile:atomically:encoding:)")
public func writeToFile(
_ path: String, atomically useAuxiliaryFile:Bool,
encoding enc: Encoding
) throws {
fatalError("unavailable function can't be called")
}
@available(*, unavailable, renamed: "write(to:atomically:encoding:)")
public func writeToURL(
_ url: URL, atomically useAuxiliaryFile: Bool,
encoding enc: Encoding
) throws {
fatalError("unavailable function can't be called")
}
}
| apache-2.0 | 623e8ef3999f5af4a29ca3b5253769e7 | 33.702813 | 303 | 0.673413 | 4.778756 | false | false | false | false |
uraimo/SwiftyLISP | Sources/SwiftyLisp.swift | 1 | 15925 | /**
* SwiftyLisp
*
* Copyright (c) 2016 Umberto Raimondi. Licensed under the MIT license, as follows:
*
* 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
/**
Recursive Enum used to represent symbolic expressions for this LISP.
Create a new evaluable symbolic expression with a string literal:
let sexpr: SExpr = "(car (quote (a b c d e)))"
Or call explicitly the `read(sexpr:)` method:
let myexpression = "(car (quote (a b c d e)))"
let sexpr = SExpr.read(myexpression)
And evaluate it in the default environment (where the LISP builtins are registered) using the `eval()` method:
print(sexpr.eval()) // Prints the "a" atom
The default builtins are: quote,car,cdr,cons,equal,atom,cond,lambda,label,defun.
Additionally the expression can be evaluated in a custom environment with a different set of named functions that
trasform an input S-Expression in an output S-Expression:
let myenv: [String: (SExpr)->SExpr] = ...
print(sexpr.eval(myenv))
The default environment is available through the global constant `defaultEnvironment`
*/
public enum SExpr{
case Atom(String)
case List([SExpr])
/**
Evaluates this SExpression with the given functions environment
- Parameter environment: A set of named functions or the default environment
- Returns: the resulting SExpression after evaluation
*/
public func eval(with locals: [SExpr]? = nil, for values: [SExpr]? = nil) -> SExpr?{
var node = self
switch node {
case .Atom:
return evaluateVariable(node, with:locals, for:values)
case var .List(elements):
var skip = false
if elements.count > 1, case let .Atom(value) = elements[0] {
skip = Builtins.mustSkip(value)
}
// Evaluate all subexpressions
if !skip {
elements = elements.map{
return $0.eval(with:locals, for:values)!
}
}
node = .List(elements)
// Obtain a a reference to the function represented by the first atom and apply it, local definitions shadow global ones
if elements.count > 0, case let .Atom(value) = elements[0], let f = localContext[value] ?? defaultEnvironment[value] {
let r = f(node,locals,values)
return r
}
return node
}
}
private func evaluateVariable(_ v: SExpr, with locals: [SExpr]?, for values: [SExpr]?) -> SExpr {
guard let locals = locals, let values = values else {return v}
if locals.contains(v) {
// The current atom is a variable, replace it with its value
return values[locals.index(of: v)!]
}else{
// Not a variable, just return it
return v
}
}
}
/// Extension that implements a recursive Equatable, needed for the equal atom
extension SExpr : Equatable {
public static func ==(lhs: SExpr, rhs: SExpr) -> Bool{
switch(lhs,rhs){
case let (.Atom(l),.Atom(r)):
return l==r
case let (.List(l),.List(r)):
guard l.count == r.count else {return false}
for (idx,el) in l.enumerated() {
if el != r[idx] {
return false
}
}
return true
default:
return false
}
}
}
/// Extension that implements CustomStringConvertible to pretty-print the S-Expression
extension SExpr : CustomStringConvertible{
public var description: String {
switch self{
case let .Atom(value):
return "\(value) "
case let .List(subxexprs):
var res = "("
for expr in subxexprs{
res += "\(expr) "
}
res += ")"
return res
}
}
}
/// Extension needed to convert string literals to a SExpr
extension SExpr : ExpressibleByStringLiteral,ExpressibleByUnicodeScalarLiteral,ExpressibleByExtendedGraphemeClusterLiteral {
public init(stringLiteral value: String){
self = SExpr.read(value)
}
public init(extendedGraphemeClusterLiteral value: String){
self.init(stringLiteral: value)
}
public init(unicodeScalarLiteral value: String){
self.init(stringLiteral: value)
}
}
/// Read, Tokenize and parsing extension
extension SExpr {
/**
Read a LISP string and convert it to a hierarchical S-Expression
*/
public static func read(_ sexpr:String) -> SExpr{
enum Token{
case pOpen,pClose,textBlock(String)
}
/**
Break down a string to a series of tokens
- Parameter sexpr: Stringified S-Expression
- Returns: Series of tokens
*/
func tokenize(_ sexpr:String) -> [Token] {
var res = [Token]()
var tmpText = ""
for c in sexpr {
switch c {
case "(":
if tmpText != "" {
res.append(.textBlock(tmpText))
tmpText = ""
}
res.append(.pOpen)
case ")":
if tmpText != "" {
res.append(.textBlock(tmpText))
tmpText = ""
}
res.append(.pClose)
case " ":
if tmpText != "" {
res.append(.textBlock(tmpText))
tmpText = ""
}
default:
tmpText.append(c)
}
}
return res
}
func appendTo(list: SExpr?, node:SExpr) -> SExpr {
var list = list
if list != nil, case var .List(elements) = list! {
elements.append(node)
list = .List(elements)
}else{
list = node
}
return list!
}
/**
Parses a series of tokens to obtain a hierachical S-Expression
- Parameter tokens: Tokens to parse
- Parameter node: Parent S-Expression if available
- Returns: Tuple with remaning tokens and resulting S-Expression
*/
func parse(_ tokens: [Token], node: SExpr? = nil) -> (remaining:[Token], subexpr:SExpr?) {
var tokens = tokens
var node = node
var i = 0
repeat {
let t = tokens[i]
switch t {
case .pOpen:
//new sexpr
let (tr,n) = parse( Array(tokens[(i+1)..<tokens.count]), node: .List([]))
assert(n != nil) //Cannot be nil
(tokens, i) = (tr, 0)
node = appendTo(list: node, node: n!)
if tokens.count != 0 {
continue
}else{
break
}
case .pClose:
//close sexpr
return ( Array(tokens[(i+1)..<tokens.count]), node)
case let .textBlock(value):
node = appendTo(list: node, node: .Atom(value))
}
i += 1
}while(tokens.count > 0)
return ([],node)
}
let tokens = tokenize(sexpr)
let res = parse(tokens)
return res.subexpr ?? .List([])
}
}
/// Basic builtins
fileprivate enum Builtins:String{
case quote,car,cdr,cons,equal,atom,cond,lambda,defun,list,
println,eval
/**
True if the given parameter stop evaluation of sub-expressions.
Sub expressions will be evaluated lazily by the operator.
- Parameter atom: Stringified atom
- Returns: True if the atom is the quote operation
*/
public static func mustSkip(_ atom: String) -> Bool {
return (atom == Builtins.quote.rawValue) ||
(atom == Builtins.cond.rawValue) ||
(atom == Builtins.defun.rawValue) ||
(atom == Builtins.lambda.rawValue)
}
}
/// Local environment for locally defined functions
public var localContext = [String: (SExpr, [SExpr]?, [SExpr]?)->SExpr]()
/// Global default builtin functions environment
///
/// Contains definitions for: quote,car,cdr,cons,equal,atom,cond,lambda,label,defun.
private var defaultEnvironment: [String: (SExpr, [SExpr]?, [SExpr]?)->SExpr] = {
var env = [String: (SExpr, [SExpr]?, [SExpr]?)->SExpr]()
env[Builtins.quote.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 2 else {return .List([])}
return parameters[1]
}
env[Builtins.car.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 2 else {return .List([])}
guard case let .List(elements) = parameters[1], elements.count > 0 else {return .List([])}
return elements.first!
}
env[Builtins.cdr.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 2 else {return .List([])}
guard case let .List(elements) = parameters[1], elements.count > 1 else {return .List([])}
return .List(Array(elements.dropFirst(1)))
}
env[Builtins.cons.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 3 else {return .List([])}
guard case .List(let elRight) = parameters[2] else {return .List([])}
switch parameters[1].eval(with: locals,for: values)!{
case let .Atom(p):
return .List([.Atom(p)]+elRight)
default:
return .List([])
}
}
env[Builtins.equal.rawValue] = {params,locals,values in
guard case let .List(elements) = params, elements.count == 3 else {return .List([])}
var me = env[Builtins.equal.rawValue]!
switch (elements[1].eval(with: locals,for: values)!,elements[2].eval(with: locals,for: values)!) {
case (.Atom(let elLeft),.Atom(let elRight)):
return elLeft == elRight ? .Atom("true") : .List([])
case (.List(let elLeft),.List(let elRight)):
guard elLeft.count == elRight.count else {return .List([])}
for (idx,el) in elLeft.enumerated() {
let testeq:[SExpr] = [.Atom("Equal"),el,elRight[idx]]
if me(.List(testeq),locals,values) != SExpr.Atom("true") {
return .List([])
}
}
return .Atom("true")
default:
return .List([])
}
}
env[Builtins.atom.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 2 else {return .List([])}
switch parameters[1].eval(with: locals,for: values)! {
case .Atom:
return .Atom("true")
default:
return .List([])
}
}
env[Builtins.cond.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count > 1 else {return .List([])}
for el in parameters.dropFirst(1) {
guard case let .List(c) = el, c.count == 2 else {return .List([])}
if c[0].eval(with: locals,for: values) != .List([]) {
let res = c[1].eval(with: locals,for: values)
return res!
}
}
return .List([])
}
env[Builtins.defun.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 4 else {return .List([])}
guard case let .Atom(lname) = parameters[1] else {return .List([])}
guard case let .List(vars) = parameters[2] else {return .List([])}
let lambda = parameters[3]
let f: (SExpr, [SExpr]?, [SExpr]?)->SExpr = { params,locals,values in
guard case var .List(p) = params else {return .List([])}
p = Array(p.dropFirst(1))
// Replace parameters in the lambda with values
if let result = lambda.eval(with:vars, for:p){
return result
}else{
return .List([])
}
}
localContext[lname] = f
return .List([])
}
env[Builtins.lambda.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 3 else {return .List([])}
guard case let .List(vars) = parameters[1] else {return .List([])}
let lambda = parameters[2]
//Assign a name for this temporary closure
let fname = "TMP$"+String(arc4random_uniform(UInt32.max))
let f: (SExpr, [SExpr]?, [SExpr]?)->SExpr = { params,locals,values in
guard case var .List(p) = params else {return .List([])}
p = Array(p.dropFirst(1))
//Remove temporary closure
localContext[fname] = nil
// Replace parameters in the lambda with values
if let result = lambda.eval(with:vars, for:p){
return result
}else{
return .List([])
}
}
localContext[fname] = f
return .Atom(fname)
}
//List implemented as a classic builtin instead of a series of cons
env[Builtins.list.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count > 1 else {return .List([])}
var res: [SExpr] = []
for el in parameters.dropFirst(1) {
switch el {
case .Atom:
res.append(el)
case let .List(els):
res.append(contentsOf: els)
}
}
return .List(res)
}
env[Builtins.println.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count > 1 else {return .List([])}
print(parameters[1].eval(with: locals,for: values)!)
return .List([])
}
env[Builtins.eval.rawValue] = { params,locals,values in
guard case let .List(parameters) = params, parameters.count == 2 else {return .List([])}
return parameters[1].eval(with: locals,for: values)!
}
return env
}()
| mit | 9ac45f9568ed7813976e9b4f911761cb | 33.770742 | 132 | 0.541978 | 4.593308 | false | false | false | false |
darthpelo/TimerH2O | TimerH2O/TimerH2O/More/ViewControllers/TH2OHealthDataViewController.swift | 1 | 1366 | //
// TH2OHealthDataViewController.swift
// TimerH2O
//
// Created by Alessio Roberto on 22/01/2017.
// Copyright © 2017 Alessio Roberto. All rights reserved.
//
import UIKit
final class TH2OHealthDataViewController: UIViewController, Configurable {
@IBOutlet weak var firstLabel: UILabel!
@IBOutlet weak var secondLabel: UILabel!
@IBOutlet weak var switchLabel: UILabel!
@IBOutlet weak var healthSwitch: UISwitch!
private let healthManager = HealthManager()
lazy var presenter: HealthPresenter = HealthPresenter(healthManager: self.healthManager)
override func viewDidLoad() {
super.viewDidLoad()
configureView()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
healthSwitch.isOn = presenter.healthKitIsAuthorized()
if presenter.healthKitIsAuthorized() {
healthSwitch.isHidden = true
switchLabel.isHidden = true
}
}
@IBAction func switchValueChanged(_ sender: UISwitch) {
presenter.healthKitAuthorize { [weak self] (authorize) in
DispatchQueue.main.async { [weak self] in
self?.healthSwitch.isOn = authorize
}
if authorize { AnswerManager().log(event: "Health Connected") }
}
}
}
| mit | c05a6c18867752d30fd4b1e41295244d | 28.042553 | 92 | 0.644689 | 5.018382 | false | false | false | false |
tjw/swift | test/IRGen/sil_generic_witness_methods_objc.swift | 2 | 1726 | // RUN: %target-swift-frontend -assume-parsing-unqualified-ownership-sil -primary-file %s -emit-ir -disable-objc-attr-requires-foundation-module | %FileCheck %s
// REQUIRES: CPU=x86_64
// REQUIRES: objc_interop
// FIXME: These should be SIL tests, but we can't parse generic types in SIL
// yet.
@objc protocol ObjC {
func method()
}
// CHECK-LABEL: define hidden swiftcc void @"$S32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_method<T: ObjC>(_ x: T) {
x.method()
}
// CHECK-LABEL: define hidden swiftcc void @"$S32sil_generic_witness_methods_objc05call_f1_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object*, %swift.type* %T) {{.*}} {
// CHECK: call swiftcc void @"$S32sil_generic_witness_methods_objc05call_E7_method{{[_0-9a-zA-Z]*}}F"(%objc_object* %0, %swift.type* %T)
func call_call_objc_method<T: ObjC>(_ x: T) {
call_objc_method(x)
}
// CHECK-LABEL: define hidden swiftcc void @"$S32sil_generic_witness_methods_objc05call_E19_existential_method{{[_0-9a-zA-Z]*}}F"(%objc_object*) {{.*}} {
// CHECK: [[SEL:%.*]] = load i8*, i8** @"\01L_selector(method)", align 8
// CHECK: [[CAST:%.*]] = bitcast %objc_object* %0 to [[SELFTYPE:%?.*]]*
// CHECK: call void bitcast (void ()* @objc_msgSend to void ([[SELFTYPE]]*, i8*)*)([[SELFTYPE]]* [[CAST]], i8* [[SEL]])
func call_objc_existential_method(_ x: ObjC) {
x.method()
}
| apache-2.0 | aa75bdb79c8f33683ce11d4d036c1a85 | 51.30303 | 160 | 0.615875 | 3.087657 | false | false | false | false |
SwiftStudies/OysterKit | Sources/STLR/Generators/Swift/SwiftStructure.swift | 1 | 13580 | // Copyright (c) 2018, RED When Excited
// 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.
//
// 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 Foundation
import OysterKit
extension GrammarStructure {
func swift(to output:TextFile, scope:STLR, accessLevel:String){
for child in structure.children {
child.swift(to: output, scope: scope, accessLevel: accessLevel)
}
}
}
fileprivate extension CharacterSet {
func contains(_ character:Character)->Bool{
return contains(character.unicodeScalars.first!)
}
}
fileprivate extension Character {
var safeVariant : String {
let map : [Character : String] = ["1":"One","2":"Two","3":"Three","4":"Four","5":"Five","6":"Six","7":"Seven","8":"Eight","9" : "Nine",
"-":"Dash","!":"Ping","|":"Pipe","<":"LessThan",">":"GreaterThan","=":"Equals","@":"at","$":"Dollar",
"#":"Hash","£":"Pound","%":"Percent","^":"Hat","&":"Ampersand","*":"Star",
"(":"OpenRoundBrace",")":"CloseRoundBrace","+":"Plus","~":"Tilde","`":"OpenQuote",":":"Colon",";":"SemiColon",
"\"":"DoubleQuote","'":"SingleQuote","\\":"BackSlash","/":"ForwardSlash","?":"QuestionMark",".":"Period",
",":"Comma","§":"Snake","±":"PlusOrMinus"," ":"Space","[":"OpenSquareBracket","]":"CloseSquareBracket",
"{":"OpenCurlyBrace","}":"CloseCurlyBrace"
]
let safeCharacterSet = CharacterSet.letters.union(CharacterSet.decimalDigits).union(CharacterSet(charactersIn: "_"))
if safeCharacterSet.contains(self){
return String(self)
}
if let mappedCharacter = map[self] {
return mappedCharacter
}
return String(self.unicodeScalars.first!.value, radix:16).map({$0.safeVariant}).joined(separator: "")
}
}
fileprivate extension StringProtocol {
var caseName : String {
var remaining = String(self)
var caseName = ""
let firstCharacter = remaining.removeFirst()
if firstCharacter == "_" || CharacterSet.letters.contains(firstCharacter){
caseName += String(firstCharacter)
} else {
caseName += firstCharacter.safeVariant.instanceName
}
while let nextCharacter = remaining.first {
remaining = String(remaining.dropFirst())
caseName += nextCharacter.safeVariant
}
return caseName
}
}
fileprivate extension GrammarStructure.Node {
func stringEnum(to output:TextFile, accessLevel:String){
output.print("","// \(dataType(accessLevel))","\(accessLevel) enum \(dataType(accessLevel)) : Swift.String, Codable, CaseIterable {").indent()
let cases = children.map({
let caseMatchedString = $0.name.hasPrefix("\"") ? String($0.name.dropFirst().dropLast()) : $0.name
let caseMatchedName = caseMatchedString.caseName.propertyName
if caseMatchedString == caseMatchedName {
return "\(caseMatchedName)"
} else {
return "\(caseMatchedName) = \"\(caseMatchedString)\""
}
}).joined(separator: ",")
output.print("case \(cases)").outdent().print("}")
}
func swiftEnum(to output:TextFile, scope:STLR, accessLevel:String){
let _ = ""
if children.reduce(true, {$0 && $1.dataType(accessLevel) == "Swift.String?"}){
stringEnum(to: output, accessLevel:accessLevel)
return
}
output.print("","// \(dataType(accessLevel))","\(accessLevel) enum \(dataType(accessLevel)) : Codable {").indent()
for child in children {
output.print("case \(child.name.propertyName)(\(child.name.propertyName):\(child.dataType(accessLevel).dropLast()))")
}
output.print("")
output.print("enum CodingKeys : Swift.String, CodingKey {").indent().print(
"case \(children.map({$0.name.propertyName}).joined(separator: ","))"
).outdent().print(
"}",
""
)
output.print("\(accessLevel) init(from decoder: Decoder) throws {").indent().print(
"let container = try decoder.container(keyedBy: CodingKeys.self)",
""
)
children.map({
let propertyName = $0.name.propertyName
let dataType = $0.dataType(accessLevel).dropLast()
return "if let \(propertyName) = try? container.decode(\(dataType).self, forKey: .\(propertyName)){\n\tself = .\(propertyName)(\(propertyName): \(propertyName))\n\treturn\n}"
}).joined(separator: " else ").split(separator: "\n").forEach({output.print(String($0))})
output.print(
"throw DecodingError.valueNotFound(Expression.self, DecodingError.Context(codingPath: decoder.codingPath, debugDescription: \"Tried to decode one of \(children.map({$0.dataType(accessLevel).dropLast()}).joined(separator: ",")) but found none of those types\"))"
).outdent().print("}")
output.print("\(accessLevel) func encode(to encoder:Encoder) throws {").indent()
output.print(
"var container = encoder.container(keyedBy: CodingKeys.self)",
"switch self {"
)
for child in children {
output.print("case .\(child.name.propertyName)(let \(child.name.propertyName)):").indent()
output.print("try container.encode(\(child.name.propertyName), forKey: .\(child.name.propertyName))").outdent()
}
output.print("}")
output.outdent().print("}")
output.outdent().print("}")
}
func swift(to output:TextFile, scope:STLR, accessLevel:String){
var isClass = false
if type != .unknown {
if children.isEmpty{
output.print("\(accessLevel) let \(name.propertyName): \(dataType(accessLevel))")
} else {
switch type {
case .structure:
isClass = scope.identifierIsLeftHandRecursive(name)
output.print(
"",
"/// \(dataType(accessLevel)) ",
"\(accessLevel) \(isClass ? "class" : "struct") \(dataType(accessLevel)) : Codable {"
)
case.enumeration:
swiftEnum(to: output, scope: scope, accessLevel: accessLevel)
default:
output.print("",dataType(accessLevel))
}
}
} else {
output.print("\(name): \(dataType(accessLevel)) //\(kind)")
return
}
if type == .typealias || type == .enumeration {
return
}
output.indent()
for child in children {
child.swift(to: output, scope: scope, accessLevel: accessLevel)
}
output.outdent()
if isClass {
output.indent().print("","/// Default initializer")
var parameters = [String]()
let assignments = TextFile()
for child in children.sorted(by: {$0.name < $1.name}) {
let variableName = child.name.propertyName
let variableType = child.dataType(accessLevel)
parameters.append("\(variableName):\(variableType)")
assignments.print("self.\(variableName) = \(variableName)")
}
output.print("\(accessLevel) init(\(parameters.joined(separator: ", "))){").indent()
output.printFile(assignments)
output.print("")
output.outdent().print("}").outdent().print("")
}
if type == .structure && !children.isEmpty {
output.print("}")
}
}
}
fileprivate extension String {
var propertyName : String {
let lowerCased : String
/// If I'm all uppercased, just go all lowercased
if self.uppercased() == self {
lowerCased = self.lowercased()
} else {
lowerCased = String(prefix(1).lowercased()+dropFirst())
}
let keywords = ["switch","extension","protocol","in","for","case","if","while","do","catch","func","enum","let","var","struct","class","enum","import","private","fileprivate","internal","public","final","open","typealias","typedef","true","false","return","self","else","default","init","operator","throws","catch"]
if keywords.contains(lowerCased){
return "`\(lowerCased)`"
}
return lowerCased
}
}
/// Generates a Swift structure that you can use a ParsingDecoder with to rapidly build an AST or IR
public class SwiftStructure : Generator{
/// Generates a Swift `struct` for the supplied scope that could be used by a `ParsingDecoder`
///
/// - Parameter scope: The scope to use to generate
/// - Returns: A single `TextFile` containing the Swift source
public static func generate(for scope: STLR, grammar name:String, accessLevel:String) throws -> [Operation] {
let name = scope.grammar.scopeName
let output = TextFile("\(name).swift")
let tokenFile = TextFile("")
scope.swift(in: tokenFile)
var tokens = tokenFile.content
tokens = String(tokens[tokens.range(of: "enum")!.lowerBound...])
// Generate all of the structural elements required for rules
output.print(
"import Foundation",
"import OysterKit",
"",
"/// Intermediate Representation of the grammar"
)
var lines = tokens.components(separatedBy: CharacterSet.newlines)
let line = lines.removeFirst()
output.print("internal \(line)")
for line in lines{
output.print(line)
}
// Now the structure
let structure = GrammarStructure(for: scope, accessLevel:accessLevel)
output.print("public struct \(name) : Codable {").indent()
structure.swift(to: output, scope: scope, accessLevel: "public")
for rule in scope.grammar.rules.filter({scope.grammar.isRoot(identifier: $0.identifier)}) {
output.print("\(accessLevel) let \(rule.identifier) : \(rule.identifier.typeName)")
}
// Generate the code to build the source
output.print(
"/**",
" Parses the supplied string using the generated grammar into a new instance of",
" the generated data structure",
"",
" - Parameter source: The string to parse",
" - Returns: A new instance of the data-structure",
" */",
"\(accessLevel) static func build(_ source : Swift.String) throws ->\(name){").indent().print(
"let root = HomogenousTree(with: StringToken(\"root\"), matching: source, children: [try AbstractSyntaxTreeConstructor().build(source, using: \(name).generatedLanguage)])",
"// print(root.description)",
"return try ParsingDecoder().decode(\(name).self, using: root)").outdent().print(
"}",
"",
"\(accessLevel) static var generatedLanguage : Grammar {return Parser(grammar:\(name)Tokens.generatedRules)}"
)
output.outdent().print("}")
return [output]
}
}
internal extension String {
var fieldName : String {
let swiftKeywords = ["import"]
if swiftKeywords.contains(self){
return "`\(self)`"
}
return self
}
var typeName : String {
return prefix(1).uppercased() + dropFirst()
}
var instanceName : String {
return prefix(1).lowercased() + dropFirst()
}
func arrayElement(`is` type:String)->Bool{
guard hasPrefix("[") else {
return false
}
return self.dropFirst().dropLast() == type
}
}
| bsd-2-clause | 1bb7fbd5d9f607b4e8c02c885850a4d7 | 41.164596 | 323 | 0.569345 | 4.965984 | false | false | false | false |
itssofluffy/NanoMessage | Sources/NanoMessage/Core/SymbolPropertyUnit.swift | 1 | 3201 | /*
SymbolPropertyUnit.swift
Copyright (c) 2016, 2017 Stephen Whittle 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 CNanoMessage
public enum SymbolPropertyUnit: CInt {
case None
case Byte
case Milliseconds
case Priority
case Boolean
case Counter
case Messages
case Unknown
public var rawValue: CInt {
switch self {
case .None:
return NN_UNIT_NONE
case .Byte:
return NN_UNIT_BYTES
case .Milliseconds:
return NN_UNIT_MILLISECONDS
case .Priority:
return NN_UNIT_PRIORITY
case .Boolean:
return NN_UNIT_BOOLEAN
case .Counter:
return NN_UNIT_COUNTER
case .Messages:
return NN_UNIT_MESSAGES
case .Unknown:
return CInt.max
}
}
public init(rawValue: CInt) {
switch rawValue {
case NN_UNIT_NONE:
self = .None
case NN_UNIT_BYTES:
self = .Byte
case NN_UNIT_MILLISECONDS:
self = .Milliseconds
case NN_UNIT_PRIORITY:
self = .Priority
case NN_UNIT_BOOLEAN:
self = .Boolean
case NN_UNIT_COUNTER:
self = .Counter
case NN_UNIT_MESSAGES:
self = .Messages
default:
self = .Unknown
}
}
}
extension SymbolPropertyUnit: CustomDebugStringConvertible {
public var debugDescription: String {
switch self {
case .None:
return "none"
case .Byte:
return "byte"
case .Milliseconds:
return "milliseconds"
case .Priority:
return "priority"
case .Boolean:
return "boolean"
case .Counter:
return "counter"
case .Messages:
return "messages"
case .Unknown:
return "unknown"
}
}
}
| mit | 164f33c45bd56213aeea9d53cf2cff2a | 31.333333 | 80 | 0.57732 | 5.204878 | false | false | false | false |
alskipp/SwiftForms | SwiftForms/descriptors/FormDescriptor.swift | 2 | 1345 | //
// FormDescriptor.swift
// SwiftForms
//
// Created by Miguel Angel Ortuno on 20/08/14.
// Copyright (c) 2014 Miguel Angel Ortuño. All rights reserved.
//
import Foundation
public class FormDescriptor: NSObject {
public var title = ""
public var sections: [FormSectionDescriptor] = []
public func addSection(section: FormSectionDescriptor) {
sections.append(section)
}
public func removeSection(section: FormSectionDescriptor) {
if let index = sections.indexOf(section) {
sections.removeAtIndex(index)
}
}
public func formValues() -> Dictionary<String, AnyObject> {
var formValues: [String: AnyObject] = [:]
for section in sections {
for row in section.rows {
if let val = row.value where row.rowType != .Button {
formValues[row.tag] = val
}
}
}
return formValues
}
public func validateForm() -> FormRowDescriptor! {
for section in sections {
for row in section.rows {
if let required = row.configuration.required {
if required && row.value == nil {
return row
}
}
}
}
return nil
}
}
| mit | 0c54c37ffcd86dca1d3a56f457699e9a | 24.846154 | 69 | 0.541667 | 4.941176 | false | false | false | false |
shahmishal/swift | validation-test/compiler_crashers_fixed/00076-llvm-foldingset-swift-constraints-constraintlocator-nodeequals.swift | 65 | 683 | // 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
// RUN: not %target-swift-frontend %s -typecheck
a
}
struct e : f {
i f = g
}
func i<g : g, e : f where e.f == g> (c: e) {
}
func i<h : f where h.f == c> (c: h) {
}
i(e())
class a<f : g, g : g where f.f == g> {
}
protocol g {
typealias f
typealias e
}
struct c<h : g> : g {
typealias f = h
typealias e = a<c<h>, f>
| apache-2.0 | 4a08c4fe02b6351322a28dc7d5b09e9b | 24.296296 | 79 | 0.633968 | 2.982533 | false | false | false | false |
xedin/swift | test/Constraints/requirement_failures_in_contextual_type.swift | 6 | 738 | // RUN: %target-typecheck-verify-swift
struct A<T> {}
extension A where T == Int32 { // expected-note 2 {{where 'T' = 'Int'}}
struct B : ExpressibleByIntegerLiteral { // expected-note {{where 'T' = 'Int'}}
typealias E = Int
typealias IntegerLiteralType = Int
init(integerLiteral: IntegerLiteralType) {}
}
typealias C = Int
}
let _: A<Int>.B = 0
// expected-error@-1 {{referencing struct 'B' on 'A' requires the types 'Int' and 'Int32' be equivalent}}
let _: A<Int>.C = 0
// expected-error@-1 {{referencing type alias 'C' on 'A' requires the types 'Int' and 'Int32' be equivalent}}
let _: A<Int>.B.E = 0
// expected-error@-1 {{referencing type alias 'E' on 'A.B' requires the types 'Int' and 'Int32' be equivalent}}
| apache-2.0 | 9cf5c6f53dbeadfed37122b87f2cd174 | 34.142857 | 111 | 0.655827 | 3.354545 | false | false | false | false |
crazypoo/PTools | Pods/JXSegmentedView/Sources/Core/JXSegmentedBaseDataSource.swift | 1 | 8492 | //
// JXSegmentedBaseDataSource.swift
// JXSegmentedView
//
// Created by jiaxin on 2018/12/28.
// Copyright © 2018 jiaxin. All rights reserved.
//
import Foundation
import UIKit
open class JXSegmentedBaseDataSource: JXSegmentedViewDataSource {
/// 最终传递给JXSegmentedView的数据源数组
open var dataSource = [JXSegmentedBaseItemModel]()
/// cell的宽度。为JXSegmentedViewAutomaticDimension时就以内容计算的宽度为准,否则以itemWidth的具体值为准。
open var itemWidth: CGFloat = JXSegmentedViewAutomaticDimension
/// 真实的item宽度 = itemWidth + itemWidthIncrement。
open var itemWidthIncrement: CGFloat = 0
/// item之前的间距
open var itemSpacing: CGFloat = 20
/// 当collectionView.contentSize.width小于JXSegmentedView的宽度时,是否将itemSpacing均分。
open var isItemSpacingAverageEnabled: Bool = true
/// item左右滚动过渡时,是否允许渐变。比如JXSegmentedTitleDataSource的titleZoom、titleNormalColor、titleStrokeWidth等渐变。
open var isItemTransitionEnabled: Bool = true
/// 选中的时候,是否需要动画过渡。自定义的cell需要自己处理动画过渡逻辑,动画处理逻辑参考`JXSegmentedTitleCell`
open var isSelectedAnimable: Bool = false
/// 选中动画的时长
open var selectedAnimationDuration: TimeInterval = 0.25
/// 是否允许item宽度缩放
open var isItemWidthZoomEnabled: Bool = false
/// item宽度选中时的scale
open var itemWidthSelectedZoomScale: CGFloat = 1.5
@available(*, deprecated, renamed: "itemWidth")
open var itemContentWidth: CGFloat = JXSegmentedViewAutomaticDimension {
didSet {
itemWidth = itemContentWidth
}
}
private var animator: JXSegmentedAnimator?
deinit {
animator?.stop()
}
public init() {
}
/// 配置完各种属性之后,需要手动调用该方法,更新数据源
///
/// - Parameter selectedIndex: 当前选中的index
open func reloadData(selectedIndex: Int) {
dataSource.removeAll()
for index in 0..<preferredItemCount() {
let itemModel = preferredItemModelInstance()
preferredRefreshItemModel(itemModel, at: index, selectedIndex: selectedIndex)
dataSource.append(itemModel)
}
}
open func preferredItemCount() -> Int {
return 0
}
/// 子类需要重载该方法,用于返回自己定义的JXSegmentedBaseItemModel子类实例
open func preferredItemModelInstance() -> JXSegmentedBaseItemModel {
return JXSegmentedBaseItemModel()
}
/// 子类需要重载该方法,用于返回索引为index的item宽度
open func preferredSegmentedView(_ segmentedView: JXSegmentedView, widthForItemAt index: Int) -> CGFloat {
return itemWidthIncrement
}
/// 子类需要重载该方法,用于更新索引为index的itemModel
open func preferredRefreshItemModel(_ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int) {
itemModel.index = index
itemModel.isItemTransitionEnabled = isItemTransitionEnabled
itemModel.isSelectedAnimable = isSelectedAnimable
itemModel.selectedAnimationDuration = selectedAnimationDuration
itemModel.isItemWidthZoomEnabled = isItemWidthZoomEnabled
itemModel.itemWidthNormalZoomScale = 1
itemModel.itemWidthSelectedZoomScale = itemWidthSelectedZoomScale
if index == selectedIndex {
itemModel.isSelected = true
itemModel.itemWidthCurrentZoomScale = itemModel.itemWidthSelectedZoomScale
}else {
itemModel.isSelected = false
itemModel.itemWidthCurrentZoomScale = itemModel.itemWidthNormalZoomScale
}
}
//MARK: - JXSegmentedViewDataSource
open func itemDataSource(in segmentedView: JXSegmentedView) -> [JXSegmentedBaseItemModel] {
return dataSource
}
/// 自定义子类请继承方法`func preferredWidthForItem(at index: Int) -> CGFloat`
public final func segmentedView(_ segmentedView: JXSegmentedView, widthForItemAt index: Int) -> CGFloat {
return preferredSegmentedView(segmentedView, widthForItemAt: index)
}
public func segmentedView(_ segmentedView: JXSegmentedView, widthForItemContentAt index: Int) -> CGFloat {
return self.segmentedView(segmentedView, widthForItemAt: index)
}
open func registerCellClass(in segmentedView: JXSegmentedView) {
}
open func segmentedView(_ segmentedView: JXSegmentedView, cellForItemAt index: Int) -> JXSegmentedBaseCell {
return JXSegmentedBaseCell()
}
open func refreshItemModel(_ segmentedView: JXSegmentedView, currentSelectedItemModel: JXSegmentedBaseItemModel, willSelectedItemModel: JXSegmentedBaseItemModel, selectedType: JXSegmentedViewItemSelectedType) {
currentSelectedItemModel.isSelected = false
willSelectedItemModel.isSelected = true
if isItemWidthZoomEnabled {
if (selectedType == .scroll && !isItemTransitionEnabled) ||
selectedType == .click ||
selectedType == .code {
animator = JXSegmentedAnimator()
animator?.duration = selectedAnimationDuration
animator?.progressClosure = {[weak self] (percent) in
guard let self = self else { return }
currentSelectedItemModel.itemWidthCurrentZoomScale = JXSegmentedViewTool.interpolate(from: currentSelectedItemModel.itemWidthSelectedZoomScale, to: currentSelectedItemModel.itemWidthNormalZoomScale, percent: percent)
currentSelectedItemModel.itemWidth = self.itemWidthWithZoom(at: currentSelectedItemModel.index, model: currentSelectedItemModel)
willSelectedItemModel.itemWidthCurrentZoomScale = JXSegmentedViewTool.interpolate(from: willSelectedItemModel.itemWidthNormalZoomScale, to: willSelectedItemModel.itemWidthSelectedZoomScale, percent: percent)
willSelectedItemModel.itemWidth = self.itemWidthWithZoom(at: willSelectedItemModel.index, model: willSelectedItemModel)
segmentedView.collectionView.collectionViewLayout.invalidateLayout()
}
animator?.start()
}
}else {
currentSelectedItemModel.itemWidthCurrentZoomScale = currentSelectedItemModel.itemWidthNormalZoomScale
willSelectedItemModel.itemWidthCurrentZoomScale = willSelectedItemModel.itemWidthSelectedZoomScale
}
}
open func refreshItemModel(_ segmentedView: JXSegmentedView, leftItemModel: JXSegmentedBaseItemModel, rightItemModel: JXSegmentedBaseItemModel, percent: CGFloat) {
//如果正在进行itemWidth缩放动画,用户又立马滚动了contentScrollView,需要停止动画。
animator?.stop()
animator = nil
if isItemWidthZoomEnabled && isItemTransitionEnabled {
//允许itemWidth缩放动画且允许item渐变过渡
leftItemModel.itemWidthCurrentZoomScale = JXSegmentedViewTool.interpolate(from: leftItemModel.itemWidthSelectedZoomScale, to: leftItemModel.itemWidthNormalZoomScale, percent: percent)
leftItemModel.itemWidth = itemWidthWithZoom(at: leftItemModel.index, model: leftItemModel)
rightItemModel.itemWidthCurrentZoomScale = JXSegmentedViewTool.interpolate(from: rightItemModel.itemWidthNormalZoomScale, to: rightItemModel.itemWidthSelectedZoomScale, percent: percent)
rightItemModel.itemWidth = itemWidthWithZoom(at: rightItemModel.index, model: rightItemModel)
segmentedView.collectionView.collectionViewLayout.invalidateLayout()
}
}
/// 自定义子类请继承方法`func preferredRefreshItemModel(_ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int)`
public final func refreshItemModel(_ segmentedView: JXSegmentedView, _ itemModel: JXSegmentedBaseItemModel, at index: Int, selectedIndex: Int) {
preferredRefreshItemModel(itemModel, at: index, selectedIndex: selectedIndex)
}
private func itemWidthWithZoom(at index: Int, model: JXSegmentedBaseItemModel) -> CGFloat {
var width = self.segmentedView(JXSegmentedView(), widthForItemAt: index)
if isItemWidthZoomEnabled {
width *= model.itemWidthCurrentZoomScale
}
return width
}
}
| mit | b5763ce765395c1479fa961a79cd2491 | 45.970238 | 236 | 0.726651 | 5.888806 | false | false | false | false |
tresorit/ZeroKit-Realm-encrypted-tasks | ios/RealmTasks Shared/RealmColor.swift | 1 | 4585 | ////////////////////////////////////////////////////////////////////////////
//
// Copyright 2016 Realm Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
import Foundation
#if os(iOS)
import UIKit
typealias Color = UIColor
#elseif os(OSX)
import AppKit
typealias Color = NSColor
#endif
extension Color {
static func taskColors() -> [Color] {
return [
Color(red: 231/255, green: 167/255, blue: 118/255, alpha: 1),
Color(red: 228/255, green: 125/255, blue: 114/255, alpha: 1),
Color(red: 233/255, green: 99/255, blue: 111/255, alpha: 1),
Color(red: 242/255, green: 81/255, blue: 145/255, alpha: 1),
Color(red: 154/255, green: 80/255, blue: 164/255, alpha: 1),
Color(red: 88/255, green: 86/255, blue: 157/255, alpha: 1),
Color(red: 56/255, green: 71/255, blue: 126/255, alpha: 1)
]
}
static func listColors() -> [Color] {
return [
Color(red: 6/255, green: 147/255, blue: 251/255, alpha: 1),
Color(red: 16/255, green: 158/255, blue: 251/255, alpha: 1),
Color(red: 26/255, green: 169/255, blue: 251/255, alpha: 1),
Color(red: 33/255, green: 180/255, blue: 251/255, alpha: 1),
Color(red: 40/255, green: 190/255, blue: 251/255, alpha: 1),
Color(red: 46/255, green: 198/255, blue: 251/255, alpha: 1),
Color(red: 54/255, green: 207/255, blue: 251/255, alpha: 1)
]
}
static func shareColors() -> [Color] {
return [
Color(red: 6/255, green: 240/255, blue: 147/255, alpha: 1),
Color(red: 16/255, green: 240/255, blue: 158/255, alpha: 1),
Color(red: 26/255, green: 240/255, blue: 169/255, alpha: 1),
Color(red: 33/255, green: 240/255, blue: 180/255, alpha: 1),
Color(red: 40/255, green: 240/255, blue: 190/255, alpha: 1),
Color(red: 46/255, green: 240/255, blue: 198/255, alpha: 1),
Color(red: 54/255, green: 240/255, blue: 207/255, alpha: 1)
]
}
static func color(forRow row: Int, count: Int, colors: [Color]) -> Color {
let fraction = Double(row) / Double(max(13, count))
return colors.gradientColor(atFraction: fraction)
}
}
extension Collection where Iterator.Element == Color, Index == Int {
func gradientColor(atFraction fraction: Double) -> Color {
// Ensure offset is normalized to 1
let normalizedOffset = Swift.max(Swift.min(fraction, 1.0), 0.0)
// Work out the 'size' that each color stop spans
let colorStopRange = 1.0 / (Double(self.endIndex) - 1.0)
// Determine the base stop our offset is within
let colorRangeIndex = Int(floor(normalizedOffset / colorStopRange))
// Get the initial color which will serve as the origin
let topColor = self[colorRangeIndex]
var fromColors: [CGFloat] = [0, 0, 0]
topColor.getRed(&fromColors[0], green: &fromColors[1], blue: &fromColors[2], alpha: nil)
// Get the destination color we will lerp to
let bottomColor = self[colorRangeIndex + 1]
var toColors: [CGFloat] = [0, 0, 0]
bottomColor.getRed(&toColors[0], green: &toColors[1], blue: &toColors[2], alpha: nil)
// Work out the actual percentage we need to lerp, inside just that stop range
let stopOffset = CGFloat((normalizedOffset - (Double(colorRangeIndex) * colorStopRange)) / colorStopRange)
// Perform the interpolation
let finalColors = zip(fromColors, toColors).map { from, to in
return from + stopOffset * (to - from)
}
return Color(red: finalColors[0], green: finalColors[1], blue: finalColors[2], alpha: 1)
}
}
extension Color {
class var completeDimBackground: Color {
return Color(white: 0.2, alpha: 1)
}
class var completeGreenBackground: Color {
return Color(red: 0, green: 0.6, blue: 0, alpha: 1)
}
}
| bsd-3-clause | edf85fe28f95dc550ce6613ec13ea2d3 | 39.219298 | 114 | 0.59193 | 3.665068 | false | false | false | false |
honghaoz/CrackingTheCodingInterview | Swift/LeetCode/Graph/133_Clone Graph.swift | 1 | 4448 | // 133_Clone Graph
// https://leetcode.com/problems/clone-graph/
//
// Created by Honghao Zhang on 11/5/19.
// Copyright © 2019 Honghaoz. All rights reserved.
//
// Description:
// Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph. Each node in the graph contains a val (int) and a list (List[Node]) of its neighbors.
//
//
//
//Example:
//
//
//
//Input:
//{"$id":"1","neighbors":[{"$id":"2","neighbors":[{"$ref":"1"},{"$id":"3","neighbors":[{"$ref":"2"},{"$id":"4","neighbors":[{"$ref":"3"},{"$ref":"1"}],"val":4}],"val":3}],"val":2},{"$ref":"4"}],"val":1}
//
//Explanation:
//Node 1's value is 1, and it has two neighbors: Node 2 and 4.
//Node 2's value is 2, and it has two neighbors: Node 1 and 3.
//Node 3's value is 3, and it has two neighbors: Node 2 and 4.
//Node 4's value is 4, and it has two neighbors: Node 1 and 3.
//
//
//Note:
//
//The number of nodes will be between 1 and 100.
//The undirected graph is a simple graph, which means no repeated edges and no self-loops in the graph.
//Since the graph is undirected, if node p has node q as neighbor, then node q must have node p as neighbor too.
//You must return the copy of the given node as a reference to the cloned graph.
//
// Deep clone一个graph
import Foundation
class Num133 {
// MARK: - DFS
// 用一个全局的visited来保存original node -> copied node
// 然后对于每个neighbor,调用clone function,然后设置为新的neighbor。
// """
// # Definition for a Node.
// class Node(object):
// def __init__(self, val, neighbors):
// self.val = val
// self.neighbors = neighbors
// """
// class Solution(object):
// def __init__(self):
// # Dictionary to save the visited node and it's respective clone
// # as key and value respectively. This helps to avoid cycles.
// self.visited = {}
// # cloneGraph 返回的是node的clone。visited包含的是original -> clone。
// def cloneGraph(self, node):
// """
// :type node: Node
// :rtype: Node
// """
// if not node:
// return node
//
// # If the node was already visited before.
// # Return the clone from the visited dictionary.
// if node in self.visited:
// return self.visited[node]
//
// # Create a clone for the given node.
// # Note that we don't have cloned neighbors as of now, hence [].
// clone_node = Node(node.val, [])
//
// # The key is original node and value being the clone node.
// self.visited[node] = clone_node
//
// # Iterate through the neighbors to generate their clones
// # and prepare a list of cloned neighbors to be added to the cloned node.
// if node.neighbors:
// clone_node.neighbors = [self.cloneGraph(n) for n in node.neighbors]
//
// return clone_node
// MARK: - BFS
// from collections import deque
// class Solution(object):
//
// def cloneGraph(self, node):
// """
// :type node: Node
// :rtype: Node
// """
//
// if not node:
// return node
//
// # Dictionary to save the visited node and it's respective clone
// # as key and value respectively. This helps to avoid cycles.
// visited = {}
//
// # Put the first node in the queue
// queue = deque([node])
// # Clone the node and put it in the visited dictionary.
// visited[node] = Node(node.val, [])
//
// # Start BFS traversal
// while queue:
// # Pop a node say "n" from the from the front of the queue.
// n = queue.popleft()
// # Iterate through all the neighbors of the node
// for neighbor in n.neighbors:
// if neighbor not in visited:
// # Clone the neighbor and put in the visited, if not present already
// visited[neighbor] = Node(neighbor.val, [])
// # Add the newly encountered node to the queue.
// queue.append(neighbor)
// # Add the clone of the neighbor to the neighbors of the clone node "n".
// visited[n].neighbors.append(visited[neighbor])
//
// # Return the clone of the node from visited.
// return visited[node]
}
| mit | 8451b14416ccc89964fdeb7e958371a7 | 35.391667 | 202 | 0.572933 | 3.748498 | false | false | false | false |
movielala/TVOSSlideViewController | TVOSSlideViewController/TVOSSlideViewController/TVOSSlideViewController.swift | 1 | 14376 | //
// TVOSSlideViewController.swift
// TVOSSlideViewController
//
// Created by Cem Olcay on 23/02/16.
// Copyright © 2016 MovieLaLa. All rights reserved.
//
import UIKit
@objc public protocol TVOSSlideViewControllerDelegate {
optional func slideViewControllerDidBeginUpdateLeftDrawer(slideViewController: TVOSSlideViewController)
optional func slideViewControllerDidBeginUpdateRightDrawer(slideViewController: TVOSSlideViewController)
optional func slideViewControllerDidUpdateLeftDrawer(slideViewController: TVOSSlideViewController, amount: CGFloat)
optional func slideViewControllerDidUpdateRightDrawer(slideViewController: TVOSSlideViewController, amount: CGFloat)
optional func slideViewControllerDidEndUpdateLeftDrawer(slideViewController: TVOSSlideViewController, amount: CGFloat)
optional func slideViewControllerDidEndUpdateRightDrawer(slideViewController: TVOSSlideViewController, amount: CGFloat)
optional func slideViewControllerDidSelectLeftDrawer(slideViewController: TVOSSlideViewController)
optional func slideViewControllerDidSelectRightDrawer(slideViewController: TVOSSlideViewController)
}
public enum TVOSSlideViewControllerType {
case LeftRightDrawer
case LeftDrawer
case RightDrawer
case NoDrawer
}
@IBDesignable
public class TVOSSlideViewControllerShadow: NSObject {
@IBInspectable public var color: UIColor = UIColor.blackColor()
@IBInspectable public var opacity: CGFloat = 0.5
@IBInspectable public var radius: CGFloat = 50
@IBInspectable public var offset: CGSize = CGSize.zero
@IBInspectable public var cornerRadius: CGFloat = 0
public static var Empty: TVOSSlideViewControllerShadow {
let shadow = TVOSSlideViewControllerShadow()
shadow.color = UIColor.clearColor()
shadow.opacity = 0
shadow.radius = 0
shadow.offset = CGSize.zero
return shadow
}
public func apply(onLayer layer: CALayer?) {
if let layer = layer {
layer.shadowColor = color.CGColor
layer.shadowOffset = offset
layer.shadowRadius = radius
layer.shadowOpacity = Float(opacity)
layer.shadowPath = UIBezierPath(
roundedRect: CGRect(x: 0, y: 0, width: layer.frame.size.width, height: layer.frame.size.height),
cornerRadius: cornerRadius)
.CGPath
}
}
}
@IBDesignable
public class TVOSSlideViewController: UIViewController {
// MARK: Properties
private var contentView: UIView!
private var contentViewShadow: UIView?
@IBOutlet public var leftView: UIView?
@IBOutlet public var rightView: UIView?
// max value for selection
@IBInspectable public var leftValue: CGFloat = 400
@IBInspectable public var rightValue: CGFloat = 400
// if amount >= value - trashold than selected
@IBInspectable public var rightTrashold: CGFloat = 0.1
@IBInspectable public var leftTrashold: CGFloat = 0.1
// for smoothing pan gesture update speed
@IBInspectable public var panMultiplier: CGFloat = 1
// animate contentView autolayout enabled or not
@IBInspectable public var shrinks: Bool = false
// center horizontally content for parallax effect
@IBInspectable public var parallax: Bool = false
// shadow style
@IBOutlet public var shadow: TVOSSlideViewControllerShadow? {
didSet {
if let shadow = shadow {
shadow.apply(onLayer: contentViewShadow?.layer)
} else {
TVOSSlideViewControllerShadow.Empty.apply(onLayer: contentViewShadow?.layer)
}
}
}
private var leftConstraint: NSLayoutConstraint?
private var rightConstraint: NSLayoutConstraint?
public weak var delegate: TVOSSlideViewControllerDelegate?
private(set) var type: TVOSSlideViewControllerType = .NoDrawer
internal var panGestureRecognizer: UIPanGestureRecognizer!
// MARK: Init
public init(contentViewController: UIViewController, leftView: UIView?, rightView: UIView?) {
super.init(nibName: nil, bundle: nil)
self.leftView = leftView
self.rightView = rightView
if let leftView = leftView { view.addSubview(leftView) }
if let rightView = rightView { view.addSubview(rightView) }
setup(contentViewController: contentViewController)
}
public required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
public func setup(contentViewController contentVC: UIViewController?) {
// type
switch (leftView, rightView) {
case (.None, .None):
type = .NoDrawer
case (.Some(_), .None):
type = .LeftDrawer
case (.None, .Some(_)):
type = .RightDrawer
case (.Some(_), .Some(_)):
type = .LeftRightDrawer
}
// reset child view controllers
for child in childViewControllers {
child.removeFromParentViewController()
child.didMoveToParentViewController(nil)
}
// content view
if contentView != nil {
contentView.removeFromSuperview()
}
contentView = UIView()
contentView.translatesAutoresizingMaskIntoConstraints = false
contentView.layer.masksToBounds = true
view.addSubview(contentView)
let topConstraint = NSLayoutConstraint(
item: contentView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 0)
let bottomConstraint = NSLayoutConstraint(
item: contentView,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0)
leftConstraint = NSLayoutConstraint(
item: contentView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Leading,
multiplier: 1,
constant: 0)
rightConstraint = NSLayoutConstraint(
item: contentView,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: view,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1,
constant: 0)
view.addConstraints([
topConstraint,
bottomConstraint,
leftConstraint!,
rightConstraint!])
// content view shadow
contentViewShadow?.removeFromSuperview()
contentViewShadow = nil
if let shadow = shadow {
let shadowView = UIView()
shadowView.backgroundColor = UIColor.clearColor()
shadowView.translatesAutoresizingMaskIntoConstraints = false
shadowView.userInteractionEnabled = false
shadowView.layer.masksToBounds = false
view.addSubview(shadowView)
view.addSubview(contentView)
// shadow constraints
view.addConstraints([
NSLayoutConstraint(
item: shadowView,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: shadowView,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: shadowView,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Leading,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: shadowView,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1,
constant: 0)
])
contentViewShadow = shadowView
shadow.apply(onLayer: contentViewShadow?.layer)
} else {
TVOSSlideViewControllerShadow.Empty.apply(onLayer: contentViewShadow?.layer)
}
// content view controller
if let contentViewController = contentVC {
contentView.addSubview(contentViewController.view)
contentViewController.view.translatesAutoresizingMaskIntoConstraints = false
if parallax {
shrinks = true
contentView.addConstraints([
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.CenterX,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.CenterX,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Width,
relatedBy: NSLayoutRelation.Equal,
toItem: nil,
attribute: NSLayoutAttribute.NotAnAttribute,
multiplier: 1,
constant: contentViewController.view.frame.size.width)
])
} else {
contentView.addConstraints([
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Top,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Top,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Bottom,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Bottom,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Leading,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Leading,
multiplier: 1,
constant: 0),
NSLayoutConstraint(
item: contentViewController.view,
attribute: NSLayoutAttribute.Trailing,
relatedBy: NSLayoutRelation.Equal,
toItem: contentView,
attribute: NSLayoutAttribute.Trailing,
multiplier: 1,
constant: 0)
])
}
addChildViewController(contentViewController)
contentViewController.didMoveToParentViewController(self)
}
view.setNeedsLayout()
view.layoutIfNeeded()
// pan gesture
panGestureRecognizer = UIPanGestureRecognizer(target: self, action: "panGestureDidChange:")
contentView.addGestureRecognizer(panGestureRecognizer)
}
// MARK: Pan Gesture Recognizer
public func enablePanGestureRecognizer() {
panGestureRecognizer?.enabled = true
}
public func disablePanGestureRecognizer() {
panGestureRecognizer?.enabled = false
}
internal func panGestureDidChange(pan: UIPanGestureRecognizer) {
if pan == panGestureRecognizer {
let translation = pan.translationInView(view)
let value = translation.x * panMultiplier
switch type {
case .LeftRightDrawer:
if value > 0 {
updateLeftDrawer(value, state: pan.state)
} else {
updateRightDrawer(value, state: pan.state)
}
case .LeftDrawer:
if value > 0 {
updateLeftDrawer(value, state: pan.state)
}
case .RightDrawer:
if value < 0 {
updateRightDrawer(value, state: pan.state)
}
case .NoDrawer:
break
}
}
}
// MARK: Update
private func resetConstraints() {
view.layoutIfNeeded()
leftConstraint?.constant = 0
rightConstraint?.constant = 0
shadow?.apply(onLayer: contentViewShadow?.layer)
UIView.animateWithDuration(0.2, animations: view.layoutIfNeeded)
}
private func updateLeftDrawer(translation: CGFloat, state: UIGestureRecognizerState) {
let translationAmount = max(0, min(CGFloat(abs(Int32(translation))), leftValue))
let amount = translationAmount / leftValue
view.layoutIfNeeded()
leftConstraint?.constant = leftValue * amount
rightConstraint?.constant = shrinks ? 0 : leftValue * amount
shadow?.apply(onLayer: contentViewShadow?.layer)
UIView.animateWithDuration(0.1, animations: view.layoutIfNeeded)
switch state {
case .Began:
delegate?.slideViewControllerDidBeginUpdateLeftDrawer?(self)
case .Changed:
delegate?.slideViewControllerDidUpdateLeftDrawer?(self, amount: amount)
case .Cancelled, .Ended, .Failed:
resetConstraints()
if amount >= 1.0 - leftTrashold {
delegate?.slideViewControllerDidSelectLeftDrawer?(self)
} else {
delegate?.slideViewControllerDidEndUpdateLeftDrawer?(self, amount: amount)
}
default:
break
}
}
private func updateRightDrawer(translation: CGFloat, state: UIGestureRecognizerState) {
let translationAmount = max(0, min(CGFloat(abs(Int32(translation))), rightValue))
let amount = translationAmount / rightValue
view.layoutIfNeeded()
rightConstraint?.constant = -rightValue * amount
leftConstraint?.constant = shrinks ? 0 : -rightValue * amount
shadow?.apply(onLayer: contentViewShadow?.layer)
UIView.animateWithDuration(0.1, animations: view.layoutIfNeeded)
switch state {
case .Began:
delegate?.slideViewControllerDidBeginUpdateRightDrawer?(self)
case .Changed:
delegate?.slideViewControllerDidUpdateRightDrawer?(self, amount: amount)
case .Cancelled, .Ended, .Failed:
resetConstraints()
if amount >= 1.0 - rightTrashold {
delegate?.slideViewControllerDidSelectRightDrawer?(self)
} else {
delegate?.slideViewControllerDidEndUpdateRightDrawer?(self, amount: amount)
}
default:
break
}
}
}
| apache-2.0 | 6024223436c73f4f98e7837e6372faf9 | 32.430233 | 121 | 0.684522 | 5.64168 | false | false | false | false |
JasdipChauhan/SceneIt | sceneIt-app/SceneIt/RegistrationViewController.swift | 1 | 2565 | //
// ViewController.swift
// SceneIt
//
// Created by Jasdip Chauhan on 2017-04-22.
// Copyright © 2017 Jasdip Chauhan. All rights reserved.
//
import UIKit
class RegistrationViewController: UIViewController {
//MARK: UI Objects
@IBOutlet weak var usernameTextField: UITextField!
@IBOutlet weak var passwordTextField: UITextField!
@IBOutlet weak var emailTextField: UITextField!
@IBOutlet weak var firstNameTextField: UITextField!
@IBOutlet weak var lastNameTextField: UITextField!
//Singletons
override func viewDidLoad() {
super.viewDidLoad()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
//MARK: ButtonClicks
@IBAction func registerButtonClick(_ sender: Any) {
if usernameTextField.text!.isEmpty ||
passwordTextField.text!.isEmpty ||
emailTextField.text!.isEmpty ||
firstNameTextField.text!.isEmpty ||
lastNameTextField.text!.isEmpty {
usernameTextField.attributedPlaceholder = NSAttributedString(string: "Username", attributes: [NSForegroundColorAttributeName: UIColor.red])
passwordTextField.attributedPlaceholder = NSAttributedString(string: "Password", attributes: [NSForegroundColorAttributeName: UIColor.red])
emailTextField.attributedPlaceholder = NSAttributedString(string: "Email", attributes: [NSForegroundColorAttributeName: UIColor.red])
firstNameTextField.attributedPlaceholder = NSAttributedString(string: "First Name", attributes: [NSForegroundColorAttributeName: UIColor.red])
lastNameTextField.attributedPlaceholder = NSAttributedString(string: "Last Name", attributes: [NSForegroundColorAttributeName: UIColor.red])
} else {
// create the new user in MySQL DB
Backend.getInstance().registerUser(username: usernameTextField.text!.lowercased(),
password: passwordTextField.text!.lowercased(),
email: emailTextField.text!.lowercased(),
fullname: firstNameTextField.text!.appending("%20".appending(lastNameTextField.text!.lowercased())).lowercased())
}
}
@IBAction func accountButtonClick(_ sender: Any) {
}
}
| mit | a23c35bb6de5630ff34a17065561d613 | 35.628571 | 160 | 0.634945 | 6.299754 | false | false | false | false |
mathiasquintero/Sweeft | Sources/Sweeft/Networking/Authentication/Auth.swift | 2 | 1197 | //
// Auth.swift
// Pods
//
// Created by Mathias Quintero on 12/29/16.
//
//
import Foundation
/// Authentication protocol
public protocol Auth {
func apply(to request: URLRequest) -> Promise<URLRequest, APIError>
}
/// Object that doesn't do anything to authenticate the user
public struct NoAuth: Auth {
/// Shared instance
public static let standard = NoAuth()
public func apply(to request: URLRequest) -> Promise<URLRequest, APIError> {
return .successful(with: request)
}
}
/// Basic Http Auth
public struct BasicAuth {
fileprivate let username: String
fileprivate let password: String
public init(username: String, password: String) {
self.username = username
self.password = password
}
}
extension BasicAuth: Auth {
/// Adds authorization header
public func apply(to request: URLRequest) -> Promise<URLRequest, APIError> {
var request = request
let string = ("\(username):\(password)".base64Encoded).?
let auth = "Basic \(string)"
request.addValue(auth, forHTTPHeaderField: "Authorization")
return .successful(with: request)
}
}
| mit | 5b96051db3b54dcff0b6ec1856238f73 | 22.019231 | 80 | 0.646617 | 4.516981 | false | false | false | false |
MaTriXy/androidtool-mac | AndroidTool/ShellTasker.swift | 1 | 4279 | //
// ShellTasker.swift
// AndroidTool
//
// Created by Morten Just Petersen on 4/23/15.
// Copyright (c) 2015 Morten Just Petersen. All rights reserved.
//
import Cocoa
protocol ShellTaskDelegate {
func shellTaskDidBegin()
func shellTaskDidFinish()
}
class ShellTasker: NSObject {
var scriptFile:String!
var task:NSTask!
var outputIsVerbose = false;
init(scriptFile:String){
// println("initiate with \(scriptFile)")
self.scriptFile = scriptFile
print("T:\(scriptFile)")
}
func stop(){
// println("shelltask stop")
task.terminate()
}
func postNotification(message:NSString, channel:String){
NSNotificationCenter.defaultCenter().postNotificationName(channel, object: message)
}
func run(arguments args:[String]=[], isUserScript:Bool = false, isIOS:Bool = false, complete:(output:NSString)-> Void) {
var output = NSString()
var data = NSData()
if scriptFile == nil {
return
}
// println("running \(scriptFile)")
var scriptPath:AnyObject!
if isUserScript {
scriptPath = scriptFile as AnyObject
} else {
scriptPath = NSBundle.mainBundle().pathForResource(scriptFile, ofType: "sh") as! AnyObject
}
let sp = scriptPath as! String
let resourcesUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("adb", ofType: "")!).URLByDeletingLastPathComponent
let resourcesPath = resourcesUrl?.path
//let resourcesPath = NSBundle.mainBundle().pathForResource("adb", ofType: "")?.stringByDeletingLastPathComponent
let bash = "/bin/bash"
task = NSTask()
let pipe = NSPipe()
task.launchPath = bash
var allArguments = [String]()
allArguments.append("\(scriptPath)") // $1
if !isIOS {
allArguments.append(resourcesPath!) // $1
} else
{
let imobileUrl = NSURL(fileURLWithPath: NSBundle.mainBundle().pathForResource("idevicescreenshot", ofType: "")!).URLByDeletingLastPathComponent
let imobilePath = imobileUrl?.path
//let imobilePath = NSBundle.mainBundle().pathForResource("idevicescreenshot", ofType: "")?.stringByDeletingLastPathComponent
allArguments.append(imobilePath!) // $1
}
for arg in args {
allArguments.append(arg)
}
task.arguments = allArguments
// was task.arguments = [scriptPath, resourcesPath!, args]
task.standardOutput = pipe
task.standardError = pipe
// post a notification with the command, for the rawoutput debugging window
let taskString = sp
if self.outputIsVerbose {
postNotification(taskString, channel: C.NOTIF_COMMANDVERBOSE)
} else {
postNotification(taskString, channel: C.NOTIF_COMMAND)
}
self.task.launch()
pipe.fileHandleForReading.waitForDataInBackgroundAndNotify()
NSNotificationCenter.defaultCenter().addObserverForName(NSFileHandleDataAvailableNotification, object: pipe.fileHandleForReading, queue: nil) { (notification) -> Void in
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), { () -> Void in
data = pipe.fileHandleForReading.readDataToEndOfFile() // use .availabledata instead to stream from the console, pretty cool
output = NSString(data: data, encoding: NSUTF8StringEncoding)!
dispatch_async(dispatch_get_main_queue(), { () -> Void in
var channel = ""
if self.outputIsVerbose {
channel = C.NOTIF_NEWDATAVERBOSE
} else {
channel = C.NOTIF_NEWDATA
}
self.postNotification(output, channel: channel)
complete(output: output)
})
})
}
}
} | apache-2.0 | 6a94ca7ffd2e3977b620ab319214a02d | 32.4375 | 177 | 0.576303 | 5.478873 | false | false | false | false |
wdkk/CAIM | Basic/answer/caim02_calc_A/basic/ImageToolBox.swift | 1 | 6985 | //
// ImageToolBox.swift
// CAIM Project
// https://kengolab.net/CreApp/wiki/
//
// Copyright (c) Watanabe-DENKI Inc.
// https://wdkk.co.jp/
//
// This software is released under the MIT License.
// https://opensource.org/licenses/mit-license.php
//
import Foundation
// 画像処理ツールクラス
class ImageToolBox
{
// 横方向グラデーションを作る関数
static func gradX(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数: x方向の位置によって計算 (α = 0.0~1.0)
let alpha = Float(x) / Float(wid)
// C = A(1.0-α) + Bα
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
// 縦方向グラデーションを作る関数
static func gradY(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数: y方向の位置によって計算 (α = 0.0~1.0)
let alpha = Float(y) / Float(hgt)
// C = A(1.0-α) + Bα
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
// 斜めのグラデーション
static func gradXY(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数xとyを混ぜて計算 (α = 0.0~1.0)
let alpha = Float(x+y) / Float(wid+hgt)
// 係数に合わせて色を混ぜる
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
// グラデーションSin(引数kは波を打つ回数)
static func gradSin(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor, k:Float) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数: x座標をsinカーブ角度に用いて計算
let sinv = sin(k * Float(x)/Float(wid) * Float(2*Double.pi)) // sin = -1.0 ~ 1.0
let alpha = (sinv + 1.0) / 2.0 // α = 0.0 ~ 1.0
// C = A(1.0-α) + Bα
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
// グラデーションSin(引数kは波を打つ回数)
static func gradSinCircle(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor, k:Float) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
// 中心座標(cx, cy)
let cx = wid / 2
let cy = hgt / 2
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数: 現在の(x,y)座標が中心(cx,cy)とどれくらいの距離にあるのか求める
let dx = Float(x-cx)
let dy = Float(y-cy)
let dist = sqrt(dx * dx + dy * dy) // 中心との距離(単位はピクセル)
let sinv = sin(k * dist/Float(wid) * Float(2*Double.pi)) // 中心から波が広がるようにするため、距離distを用いてsin値を計算
let alpha = (sinv + 1.0) / 2.0 // α = 0.0 ~ 1.0
// C = A(1.0-α) + Bα
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
// Cosドーム型
static func gradCosDome(_ img:CAIMImage, color1:CAIMColor, color2:CAIMColor) {
// 画像のデータを取得
let mat = img.matrix // 画像のピクセルデータ
let wid = img.width // 画像の横幅
let hgt = img.height // 画像の縦幅
// 中心座標(cx, cy)
let cx = wid / 2
let cy = hgt / 2
for y in 0 ..< hgt {
for x in 0 ..< wid {
// 2色を混ぜる係数: 現在の(x,y)座標が中心(cx,cy)とどれくらいの距離にあるのか求める
let dx = Float(x-cx)
let dy = Float(y-cy)
let dist = sqrt(dx * dx + dy * dy) // 中心との距離(単位はピクセル)
let cosv = cos(dist/Float(wid/2) * Float.pi*0.5) // 画面の端でcos(0.5π)になるようにする
let alpha = min(1.0-cosv, 1.0) // α = 1.0(cos0) ~ 0.0(cos0.5π)
// C = A(1.0-α) + Bα
mat[y][x].R = color1.R * (1.0-alpha) + color2.R * alpha
mat[y][x].G = color1.G * (1.0-alpha) + color2.G * alpha
mat[y][x].B = color1.B * (1.0-alpha) + color2.B * alpha
mat[y][x].A = color1.A * (1.0-alpha) + color2.A * alpha
}
}
}
}
| mit | 5716075f94d1ddbcf36598a4226e02b8 | 36.298137 | 113 | 0.450125 | 3.070041 | false | false | false | false |
russbishop/swift | stdlib/public/core/OutputStream.swift | 1 | 18630 | //===----------------------------------------------------------------------===//
//
// 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
//
//===----------------------------------------------------------------------===//
import SwiftShims
//===----------------------------------------------------------------------===//
// Input/Output interfaces
//===----------------------------------------------------------------------===//
/// A type that can be the target of text-streaming operations.
///
/// You can send the output of the standard library's `print(_:to:)` and
/// `dump(_:to:)` functions to an instance of a type that conforms to the
/// `OutputStream` protocol instead of to standard output. Swift's `String`
/// type conforms to `OutputStream` already, so you can capture the output
/// from `print(_:to:)` and `dump(_:to:)` in a string instead of logging it to
/// standard output.
///
/// var s = ""
/// for n in 1 ... 5 {
/// print(n, terminator: "", to: &s)
/// }
/// // s == "12345"
///
/// Conforming to the OutputStream Protocol
/// =======================================
///
/// To make your custom type conform to the `OutputStream` protocol, implement
/// the required `write(_:)` method. Functions that use an `OutputStream`
/// target may call `write(_:)` multiple times per writing operation.
///
/// As an example, here's an implementation of an output stream that converts
/// any input to its plain ASCII representation before sending it to standard
/// output.
///
/// struct ASCIILogger: OutputStream {
/// mutating func write(_ string: String) {
/// let ascii = string.unicodeScalars.lazy.map { scalar in
/// scalar == "\n"
/// ? "\n"
/// : scalar.escaped(asASCII: true)
/// }
/// print(ascii.joined(separator: ""), terminator: "")
/// }
/// }
///
/// The `ASCIILogger` type's `write(_:)` method processes its string input by
/// escaping each Unicode scalar, with the exception of `"\n"` line returns.
/// By sending the output of the `print(_:to:)` function to an instance of
/// `ASCIILogger`, you invoke its `write(_:)` method.
///
/// let s = "Hearts ♡ and Diamonds ♢"
/// print(s)
/// // Prints "Hearts ♡ and Diamonds ♢"
///
/// var asciiLogger = ASCIILogger()
/// print(s, to: &asciiLogger)
/// // Prints "Hearts \u{2661} and Diamonds \u{2662}"
public protocol OutputStream {
mutating func _lock()
mutating func _unlock()
/// Appends the given string to the stream.
mutating func write(_ string: String)
}
extension OutputStream {
public mutating func _lock() {}
public mutating func _unlock() {}
}
/// A source of text-streaming operations.
///
/// Instances of types that conform to the `Streamable` protocol can write
/// their value to instances of any type that conforms to the `OutputStream`
/// protocol. The Swift standard library's text-related types, `String`,
/// `Character`, and `UnicodeScalar`, all conform to `Streamable`.
///
/// Conforming to the Streamable Protocol
/// =====================================
///
/// To add `Streamable` conformance to a custom type, implement the required
/// `write(to:)` method. Call the given output stream's `write(_:)` method in
/// your implementation.
public protocol Streamable {
/// Writes a textual representation of this instance into the given output
/// stream.
func write<Target : OutputStream>(to target: inout Target)
}
/// A type with a customized textual representation.
///
/// Types that conform to the `CustomStringConvertible` protocol can provide
/// their own representation to be used when converting an instance to a
/// string. The `String(_:)` initializer is the preferred way to convert an
/// instance of *any* type to a string. If the passed instance conforms to
/// `CustomStringConvertible`, the `String(_:)` initializer and the
/// `print(_:)` function use the instance's custom `description` property.
///
/// Accessing a type's `description` property directly or using
/// `CustomStringConvertible` as a generic constraint is discouraged.
///
/// Conforming to the CustomStringConvertible Protocol
/// ==================================================
///
/// Add `CustomStringConvertible` conformance to your custom types by defining
/// a `description` property.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library:
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(p)
/// // Prints "Point(x: 21, y: 30)"
///
/// After implementing the `description` property and declaring
/// `CustomStringConvertible` conformance, the `Point` type provides its own
/// custom representation.
///
/// extension Point: CustomStringConvertible {
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// print(p)
/// // Prints "(21, 30)"
///
/// - SeeAlso: `String.init<T>(T)`, `CustomDebugStringConvertible`
public protocol CustomStringConvertible {
/// A textual representation of this instance.
///
/// Instead of accessing this property directly, convert an instance of any
/// type to a string by using the `String(_:)` initializer. For example:
///
/// struct Point: CustomStringConvertible {
/// let x: Int, y: Int
///
/// var description: String {
/// return "(\(x), \(y))"
/// }
/// }
///
/// let p = Point(x: 21, y: 30)
/// let s = String(p)
/// print(s)
/// // Prints "(21, 30)"
///
/// The conversion of `p` to a string in the assignment to `s` uses the
/// `Point` type's `description` property.
var description: String { get }
}
/// A type with a customized textual representation suitable for debugging
/// purposes.
///
/// Swift provides a default debugging textual representation for any type.
/// That default representation is used by the `String(reflecting:)`
/// initializer and the `debugPrint(_:)` function for types that don't provide
/// their own. To customize that representation, make your type conform to the
/// `CustomDebugStringConvertible` protocol.
///
/// Because the `String(reflecting:)` initializer works for instances of *any*
/// type, returning an instance's `debugDescription` if the value passed
/// conforms to `CustomDebugStringConvertible`, accessing a type's
/// `debugDescription` property directly or using
/// `CustomDebugStringConvertible` as a generic constraint is discouraged.
///
/// Conforming to the CustomDebugStringConvertible Protocol
/// =======================================================
///
/// Add `CustomDebugStringConvertible` conformance to your custom types by
/// defining a `debugDescription` property.
///
/// For example, this custom `Point` struct uses the default representation
/// supplied by the standard library:
///
/// struct Point {
/// let x: Int, y: Int
/// }
///
/// let p = Point(x: 21, y: 30)
/// print(String(reflecting: p))
/// // Prints "p: Point = {
/// // x = 21
/// // y = 30
/// // }"
///
/// After adding `CustomDebugStringConvertible` conformance by implementing the
/// `debugDescription` property, `Point` provides its own custom debugging
/// representation.
///
/// extension Point: CustomDebugStringConvertible {
/// var debugDescription: String {
/// return "Point(x: \(x), y: \(y))"
/// }
/// }
///
/// print(String(reflecting: p))
/// // Prints "Point(x: 21, y: 30)"
///
/// - SeeAlso: `String.init<T>(reflecting: T)`, `CustomStringConvertible`
public protocol CustomDebugStringConvertible {
/// A textual representation of this instance, suitable for debugging.
var debugDescription: String { get }
}
//===----------------------------------------------------------------------===//
// Default (ad-hoc) printing
//===----------------------------------------------------------------------===//
@_silgen_name("swift_EnumCaseName")
func _getEnumCaseName<T>(_ value: T) -> UnsafePointer<CChar>?
@_silgen_name("swift_OpaqueSummary")
func _opaqueSummary(_ metadata: Any.Type) -> UnsafePointer<CChar>?
/// Do our best to print a value that cannot be printed directly.
internal func _adHocPrint_unlocked<T, TargetStream : OutputStream>(
_ value: T, _ mirror: Mirror, _ target: inout TargetStream,
isDebugPrint: Bool
) {
func printTypeName(_ type: Any.Type) {
// Print type names without qualification, unless we're debugPrint'ing.
target.write(_typeName(type, qualified: isDebugPrint))
}
if let displayStyle = mirror.displayStyle {
switch displayStyle {
case .optional:
if let child = mirror.children.first {
_debugPrint_unlocked(child.1, &target)
} else {
_debugPrint_unlocked("nil", &target)
}
case .tuple:
target.write("(")
var first = true
for (_, value) in mirror.children {
if first {
first = false
} else {
target.write(", ")
}
_debugPrint_unlocked(value, &target)
}
target.write(")")
case .`struct`:
printTypeName(mirror.subjectType)
target.write("(")
var first = true
for (label, value) in mirror.children {
if let label = label {
if first {
first = false
} else {
target.write(", ")
}
target.write(label)
target.write(": ")
_debugPrint_unlocked(value, &target)
}
}
target.write(")")
case .`enum`:
if let cString = _getEnumCaseName(value),
let caseName = String(validatingUTF8: cString) {
// Write the qualified type name in debugPrint.
if isDebugPrint {
printTypeName(mirror.subjectType)
target.write(".")
}
target.write(caseName)
} else {
// If the case name is garbage, just print the type name.
printTypeName(mirror.subjectType)
}
if let (_, value) = mirror.children.first {
if (Mirror(reflecting: value).displayStyle == .tuple) {
_debugPrint_unlocked(value, &target)
} else {
target.write("(")
_debugPrint_unlocked(value, &target)
target.write(")")
}
}
default:
target.write(_typeName(mirror.subjectType))
}
} else if let metatypeValue = value as? Any.Type {
// Metatype
printTypeName(metatypeValue)
} else {
// Fall back to the type or an opaque summary of the kind
if let cString = _opaqueSummary(mirror.subjectType),
let opaqueSummary = String(validatingUTF8: cString) {
target.write(opaqueSummary)
} else {
target.write(_typeName(mirror.subjectType, qualified: true))
}
}
}
@inline(never)
@_semantics("stdlib_binary_only")
internal func _print_unlocked<T, TargetStream : OutputStream>(
_ value: T, _ target: inout TargetStream
) {
// Optional has no representation suitable for display; therefore,
// values of optional type should be printed as a debug
// string. Check for Optional first, before checking protocol
// conformance below, because an Optional value is convertible to a
// protocol if its wrapped type conforms to that protocol.
if _isOptional(value.dynamicType) {
let debugPrintable = value as! CustomDebugStringConvertible
debugPrintable.debugDescription.write(to: &target)
return
}
if case let streamableObject as Streamable = value {
streamableObject.write(to: &target)
return
}
if case let printableObject as CustomStringConvertible = value {
printableObject.description.write(to: &target)
return
}
if case let debugPrintableObject as CustomDebugStringConvertible = value {
debugPrintableObject.debugDescription.write(to: &target)
return
}
let mirror = Mirror(reflecting: value)
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: false)
}
/// Returns the result of `print`'ing `x` into a `String`.
///
/// Exactly the same as `String`, but annotated 'readonly' to allow
/// the optimizer to remove calls where results are unused.
///
/// This function is forbidden from being inlined because when building the
/// standard library inlining makes us drop the special semantics.
@inline(never) @effects(readonly)
func _toStringReadOnlyStreamable<T : Streamable>(_ x: T) -> String {
var result = ""
x.write(to: &result)
return result
}
@inline(never) @effects(readonly)
func _toStringReadOnlyPrintable<T : CustomStringConvertible>(_ x: T) -> String {
return x.description
}
//===----------------------------------------------------------------------===//
// `debugPrint`
//===----------------------------------------------------------------------===//
@inline(never)
public func _debugPrint_unlocked<T, TargetStream : OutputStream>(
_ value: T, _ target: inout TargetStream
) {
if let debugPrintableObject = value as? CustomDebugStringConvertible {
debugPrintableObject.debugDescription.write(to: &target)
return
}
if let printableObject = value as? CustomStringConvertible {
printableObject.description.write(to: &target)
return
}
if let streamableObject = value as? Streamable {
streamableObject.write(to: &target)
return
}
let mirror = Mirror(reflecting: value)
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)
}
internal func _dumpPrint_unlocked<T, TargetStream : OutputStream>(
_ value: T, _ mirror: Mirror, _ target: inout TargetStream
) {
if let displayStyle = mirror.displayStyle {
// Containers and tuples are always displayed in terms of their element count
switch displayStyle {
case .tuple:
let count = mirror.children.count
target.write(count == 1 ? "(1 element)" : "(\(count) elements)")
return
case .collection:
let count = mirror.children.count
target.write(count == 1 ? "1 element" : "\(count) elements")
return
case .dictionary:
let count = mirror.children.count
target.write(count == 1 ? "1 key/value pair" : "\(count) key/value pairs")
return
case .`set`:
let count = mirror.children.count
target.write(count == 1 ? "1 member" : "\(count) members")
return
default:
break
}
}
if let debugPrintableObject = value as? CustomDebugStringConvertible {
debugPrintableObject.debugDescription.write(to: &target)
return
}
if let printableObject = value as? CustomStringConvertible {
printableObject.description.write(to: &target)
return
}
if let streamableObject = value as? Streamable {
streamableObject.write(to: &target)
return
}
if let displayStyle = mirror.displayStyle {
switch displayStyle {
case .`class`, .`struct`:
// Classes and structs without custom representations are displayed as
// their fully qualified type name
target.write(_typeName(mirror.subjectType, qualified: true))
return
case .`enum`:
target.write(_typeName(mirror.subjectType, qualified: true))
if let cString = _getEnumCaseName(value),
let caseName = String(validatingUTF8: cString) {
target.write(".")
target.write(caseName)
}
return
default:
break
}
}
_adHocPrint_unlocked(value, mirror, &target, isDebugPrint: true)
}
//===----------------------------------------------------------------------===//
// OutputStreams
//===----------------------------------------------------------------------===//
internal struct _Stdout : OutputStream {
mutating func _lock() {
_swift_stdlib_flockfile_stdout()
}
mutating func _unlock() {
_swift_stdlib_funlockfile_stdout()
}
mutating func write(_ string: String) {
if string.isEmpty { return }
if string._core.isASCII {
defer { _fixLifetime(string) }
_swift_stdlib_fwrite_stdout(UnsafePointer(string._core.startASCII),
string._core.count, 1)
return
}
for c in string.utf8 {
_swift_stdlib_putchar_unlocked(Int32(c))
}
}
}
extension String : OutputStream {
/// Appends the given string to this string.
///
/// - Parameter other: A string to append.
public mutating func write(_ other: String) {
self += other
}
}
//===----------------------------------------------------------------------===//
// Streamables
//===----------------------------------------------------------------------===//
extension String : Streamable {
/// Writes the string into the given output stream.
///
/// - Parameter target: An output stream.
public func write<Target : OutputStream>(to target: inout Target) {
target.write(self)
}
}
extension Character : Streamable {
/// Writes the character into the given output stream.
///
/// - Parameter target: An output stream.
public func write<Target : OutputStream>(to target: inout Target) {
target.write(String(self))
}
}
extension UnicodeScalar : Streamable {
/// Writes the textual representation of the Unicode scalar into the given
/// output stream.
///
/// - Parameter target: An output stream.
public func write<Target : OutputStream>(to target: inout Target) {
target.write(String(Character(self)))
}
}
/// A hook for playgrounds to print through.
public var _playgroundPrintHook : ((String) -> Void)? = {_ in () }
internal struct _TeeStream<
L : OutputStream,
R : OutputStream
> : OutputStream {
var left: L
var right: R
/// Append the given `string` to this stream.
mutating func write(_ string: String)
{ left.write(string); right.write(string) }
mutating func _lock() { left._lock(); right._lock() }
mutating func _unlock() { right._unlock(); left._unlock() }
}
@available(*, unavailable, renamed: "OutputStream")
public typealias OutputStreamType = OutputStream
extension Streamable {
@available(*, unavailable, renamed: "write(to:)")
public func writeTo<Target : OutputStream>(_ target: inout Target) {
Builtin.unreachable()
}
}
| apache-2.0 | 0432142e1c8136a30f590b99a624e42e | 32.313059 | 81 | 0.606863 | 4.553056 | false | false | false | false |
UnsignedInt8/LightSwordX | LightSwordX/AppDelegate.swift | 2 | 1890 | //
// AppDelegate.swift
// LightSwordX
//
// Created by Neko on 12/17/15.
// Copyright © 2015 Neko. All rights reserved.
//
import Cocoa
@NSApplicationMain
class AppDelegate: NSObject, NSApplicationDelegate, NSUserNotificationCenterDelegate {
func applicationDidFinishLaunching(aNotification: NSNotification) {
if SettingsHelper.loadValue(defaultValue: "", forKey: "Servers").length > 0 {
NSApplication.sharedApplication().windows.last!.close()
}
if let button = statusItem.button {
button.image = NSImage(named: "TrayIcon")
button.image?.template = true
button.alternateImage = NSImage(named: "TrayIconHighlight")
}
let menu = NSMenu()
menu.addItem(NSMenuItem(title: NSLocalizedString("Preferences", comment: ""), action: Selector("openPreferences:"), keyEquivalent: ""))
menu.addItem(NSMenuItem(title: NSLocalizedString("Quit", comment: ""), action: Selector("quit:"), keyEquivalent: ""))
statusItem.menu = menu
NSUserNotificationCenter.defaultUserNotificationCenter().delegate = self
}
func userNotificationCenter(center: NSUserNotificationCenter, shouldPresentNotification notification: NSUserNotification) -> Bool {
return true
}
func applicationWillTerminate(aNotification: NSNotification) {
// Insert code here to tear down your application
}
let statusItem = NSStatusBar.systemStatusBar().statusItemWithLength(NSSquareStatusItemLength)
func openPreferences(sender: NSMenuItem) {
NSApplication.sharedApplication().windows.last!.makeKeyAndOrderFront(nil)
NSApplication.sharedApplication().activateIgnoringOtherApps(true)
}
func quit(sender: NSMenuItem) {
NSApplication.sharedApplication().terminate(self)
}
}
| gpl-2.0 | ae75949a0ccbd34fa4fe54e259d9db1e | 33.981481 | 143 | 0.68343 | 5.622024 | false | false | false | false |
justindhill/Facets | Facets/Presentation Controllers/OZLSheetPresentationController.swift | 1 | 2731 | //
// OZLSheetPresentationController.swift
// PresentationController
//
// Created by Justin Hill on 12/23/15.
// Copyright © 2015 Justin Hill. All rights reserved.
//
import UIKit
@objc class OZLSheetPresentationController: UIPresentationController {
let dimmingView = UIView()
let backgroundTapRecognizer = UITapGestureRecognizer()
override func presentationTransitionWillBegin() {
if let containerView = self.containerView {
containerView.addSubview(self.dimmingView)
self.dimmingView.frame = containerView.bounds
self.dimmingView.backgroundColor = UIColor.black
self.dimmingView.alpha = 0.0
self.dimmingView.isUserInteractionEnabled = true
self.dimmingView.addGestureRecognizer(self.backgroundTapRecognizer)
self.backgroundTapRecognizer.addTarget(self, action: #selector(OZLSheetPresentationController.backgroundTapAction))
self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in
self.dimmingView.alpha = 0.3
}, completion: nil)
}
}
override func dismissalTransitionWillBegin() {
self.presentingViewController.transitionCoordinator?.animate(alongsideTransition: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in
self.dimmingView.alpha = 0.0
}, completion: { (context: UIViewControllerTransitionCoordinatorContext) -> Void in
self.dimmingView.removeFromSuperview()
})
}
override func preferredContentSizeDidChange(forChildContentContainer container: UIContentContainer) {
UIView.animate(withDuration: 0.3, animations: { () -> Void in
self.containerViewWillLayoutSubviews()
self.containerView?.layoutSubviews()
self.containerViewDidLayoutSubviews()
})
}
override func containerViewWillLayoutSubviews() {
self.presentedViewController.view.frame = self.frameOfPresentedViewInContainerView
}
override var frameOfPresentedViewInContainerView : CGRect {
if let containerView = self.containerView {
let preferredHeight = self.presentedViewController.preferredContentSize.height
return CGRect(x: 0, y: containerView.frame.size.height - preferredHeight, width: containerView.frame.size.width, height: preferredHeight)
}
return CGRect.zero
}
@objc func backgroundTapAction() {
self.presentingViewController.dismiss(animated: true, completion: nil)
}
}
| mit | f1d5eaf8b4103fa243b47ffd9b78caa5 | 39.746269 | 162 | 0.688645 | 6.232877 | false | false | false | false |
NeilNie/Done- | Pods/Eureka/Source/Core/BaseRow.swift | 1 | 10312 | // BaseRow.swift
// Eureka ( https://github.com/xmartlabs/Eureka )
//
// Copyright (c) 2016 Xmartlabs ( http://xmartlabs.com )
//
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
open class BaseRow: BaseRowType {
var callbackOnChange: (() -> Void)?
var callbackCellUpdate: (() -> Void)?
var callbackCellSetup: Any?
var callbackCellOnSelection: (() -> Void)?
var callbackOnExpandInlineRow: Any?
var callbackOnCollapseInlineRow: Any?
var callbackOnCellHighlightChanged: (() -> Void)?
var callbackOnRowValidationChanged: (() -> Void)?
var _inlineRow: BaseRow?
var _cachedOptionsData: Any?
public var validationOptions: ValidationOptions = .validatesOnBlur
// validation state
public internal(set) var validationErrors = [ValidationError]() {
didSet {
guard validationErrors != oldValue else { return }
RowDefaults.onRowValidationChanged["\(type(of: self))"]?(baseCell, self)
callbackOnRowValidationChanged?()
updateCell()
}
}
public internal(set) var wasBlurred = false
public internal(set) var wasChanged = false
public var isValid: Bool { return validationErrors.isEmpty }
public var isHighlighted: Bool = false
/// The title will be displayed in the textLabel of the row.
public var title: String?
/// Parameter used when creating the cell for this row.
public var cellStyle = UITableViewCell.CellStyle.value1
/// String that uniquely identifies a row. Must be unique among rows and sections.
public var tag: String?
/// The untyped cell associated to this row.
public var baseCell: BaseCell! { return nil }
/// The untyped value of this row.
public var baseValue: Any? {
set {}
get { return nil }
}
public func validate() -> [ValidationError] {
return []
}
public static var estimatedRowHeight: CGFloat = 44.0
/// Condition that determines if the row should be disabled or not.
public var disabled: Condition? {
willSet { removeFromDisabledRowObservers() }
didSet { addToDisabledRowObservers() }
}
/// Condition that determines if the row should be hidden or not.
public var hidden: Condition? {
willSet { removeFromHiddenRowObservers() }
didSet { addToHiddenRowObservers() }
}
/// Returns if this row is currently disabled or not
public var isDisabled: Bool { return disabledCache }
/// Returns if this row is currently hidden or not
public var isHidden: Bool { return hiddenCache }
/// The section to which this row belongs.
open weak var section: Section?
public lazy var trailingSwipe = SwipeConfiguration(self)
//needs the accessor because if marked directly this throws "Stored properties cannot be marked potentially unavailable with '@available'"
private lazy var _leadingSwipe = SwipeConfiguration(self)
@available(iOS 11,*)
public var leadingSwipe: SwipeConfiguration{
get { return self._leadingSwipe }
set { self._leadingSwipe = newValue }
}
public required init(tag: String? = nil) {
self.tag = tag
}
/**
Method that reloads the cell
*/
open func updateCell() {}
/**
Method called when the cell belonging to this row was selected. Must call the corresponding method in its cell.
*/
open func didSelect() {}
open func prepare(for segue: UIStoryboardSegue) {}
/**
Helps to pick destination part of the cell after scrolling
*/
open var destinationScrollPosition = UITableView.ScrollPosition.bottom
/**
Returns the IndexPath where this row is in the current form.
*/
public final var indexPath: IndexPath? {
guard let sectionIndex = section?.index, let rowIndex = section?.index(of: self) else { return nil }
return IndexPath(row: rowIndex, section: sectionIndex)
}
var hiddenCache = false
var disabledCache = false {
willSet {
if newValue && !disabledCache {
baseCell.cellResignFirstResponder()
}
}
}
}
extension BaseRow {
// Reset validation
public func cleanValidationErrors(){
validationErrors = []
}
}
extension BaseRow {
/**
Evaluates if the row should be hidden or not and updates the form accordingly
*/
public final func evaluateHidden() {
guard let h = hidden, let form = section?.form else { return }
switch h {
case .function(_, let callback):
hiddenCache = callback(form)
case .predicate(let predicate):
hiddenCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
if hiddenCache {
section?.hide(row: self)
} else {
section?.show(row: self)
}
}
/**
Evaluates if the row should be disabled or not and updates it accordingly
*/
public final func evaluateDisabled() {
guard let d = disabled, let form = section?.form else { return }
switch d {
case .function(_, let callback):
disabledCache = callback(form)
case .predicate(let predicate):
disabledCache = predicate.evaluate(with: self, substitutionVariables: form.dictionaryValuesToEvaluatePredicate())
}
updateCell()
}
final func wasAddedTo(section: Section) {
self.section = section
if let t = tag {
assert(section.form?.rowsByTag[t] == nil, "Duplicate tag \(t)")
self.section?.form?.rowsByTag[t] = self
self.section?.form?.tagToValues[t] = baseValue != nil ? baseValue! : NSNull()
}
addToRowObservers()
evaluateHidden()
evaluateDisabled()
}
final func addToHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func addToDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.addRowObservers(to: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.addRowObservers(to: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func addToRowObservers() {
addToHiddenRowObservers()
addToDisabledRowObservers()
}
final func willBeRemovedFromForm() {
(self as? BaseInlineRowType)?.collapseInlineRow()
if let t = tag {
section?.form?.rowsByTag[t] = nil
section?.form?.tagToValues[t] = nil
}
removeFromRowObservers()
}
final func willBeRemovedFromSection() {
willBeRemovedFromForm()
section = nil
}
final func removeFromHiddenRowObservers() {
guard let h = hidden else { return }
switch h {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .hidden)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .hidden)
}
}
final func removeFromDisabledRowObservers() {
guard let d = disabled else { return }
switch d {
case .function(let tags, _):
section?.form?.removeRowObservers(from: self, rowTags: tags, type: .disabled)
case .predicate(let predicate):
section?.form?.removeRowObservers(from: self, rowTags: predicate.predicateVars, type: .disabled)
}
}
final func removeFromRowObservers() {
removeFromHiddenRowObservers()
removeFromDisabledRowObservers()
}
}
extension BaseRow: Equatable, Hidable, Disableable {}
extension BaseRow {
public func reload(with rowAnimation: UITableView.RowAnimation = .none) {
guard let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView, let indexPath = indexPath else { return }
tableView.reloadRows(at: [indexPath], with: rowAnimation)
}
public func deselect(animated: Bool = true) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.deselectRow(at: indexPath, animated: animated)
}
public func select(animated: Bool = false, scrollPosition: UITableView.ScrollPosition = .none) {
guard let indexPath = indexPath,
let tableView = baseCell?.formViewController()?.tableView ?? (section?.form?.delegate as? FormViewController)?.tableView else { return }
tableView.selectRow(at: indexPath, animated: animated, scrollPosition: scrollPosition)
}
}
public func == (lhs: BaseRow, rhs: BaseRow) -> Bool {
return lhs === rhs
}
| apache-2.0 | 9ecd28fa44dd2dec8bfeca2a79d47911 | 33.955932 | 177 | 0.654868 | 5.062347 | false | false | false | false |
wddwycc/DDWelcomeController | DDWelcomeController-Demo/DDWelcomeController-Demo/ViewController.swift | 2 | 3240 | //
// ViewController.swift
// DDWelcomeController-Demo
//
// Created by 端 闻 on 8/3/15.
// Copyright (c) 2015年 monk-studio. All rights reserved.
//
import UIKit
let segueToWelcomeID = "toTutorial"
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
}
override func viewDidAppear(animated: Bool) {
//distinguish whether is the first launch
var defaults = NSUserDefaults.standardUserDefaults()
if(defaults.boolForKey("everLaunchedBefore") == false){
self.performSegueWithIdentifier(segueToWelcomeID, sender: nil)
defaults.setBool(true, forKey: "everLaunchedBefore")
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
//these are all sample view setups
let view1 = UIView(frame: UIScreen.mainScreen().bounds)
let view2 = UIView(frame: UIScreen.mainScreen().bounds)
let view3 = UIView(frame: UIScreen.mainScreen().bounds)
view1.backgroundColor = UIColor(white: 0.3, alpha: 1)
view2.backgroundColor = UIColor(white: 0.5, alpha: 1)
view3.backgroundColor = UIColor(white: 0.7, alpha: 1)
let words1 = UILabel(frame: CGRectMake(100, 100, self.view.frame.width, self.view.frame.height))
words1.text = "VIEW1"
words1.textColor = UIColor.whiteColor()
words1.textAlignment = NSTextAlignment.Center
words1.font = UIFont.boldSystemFontOfSize(40)
words1.center = view1.center
view1.addSubview(words1)
let words2 = UILabel(frame: CGRectMake(100, 100, self.view.frame.width, self.view.frame.height))
words2.text = "VIEW2"
words2.textColor = UIColor.whiteColor()
words2.textAlignment = NSTextAlignment.Center
words2.font = UIFont.boldSystemFontOfSize(40)
words2.center = view2.center
view2.addSubview(words2)
let words3 = UILabel(frame: CGRectMake(100, 100, self.view.frame.width, self.view.frame.height))
words3.text = "VIEW3"
words3.textColor = UIColor.whiteColor()
words3.textAlignment = NSTextAlignment.Center
words3.font = UIFont.boldSystemFontOfSize(40)
words3.center = view3.center
view3.addSubview(words3)
let words4 = UILabel(frame: CGRectMake(100, 100, self.view.frame.width, self.view.frame.height))
words4.text = "Swipe up to Get In"
words4.textColor = UIColor.whiteColor()
words4.font = UIFont.italicSystemFontOfSize(20)
words4.textAlignment = NSTextAlignment.Center
words4.center = view3.center
words4.center = CGPointMake(words4.center.x, words4.center.y + 30)
view3.addSubview(words4)
//magic begin here
let destinationVC = segue.destinationViewController as DDWelcomeController
destinationVC.transitioningDelegate = destinationVC
destinationVC.views = [view1,view2,view3]
}
@IBAction func unwindToMainMenu(sender:UIStoryboardSegue!){
}
}
| mit | 9ea413ea9b9403cb84364fa90272f935 | 37.5 | 104 | 0.667904 | 4.283444 | false | false | false | false |
koba-uy/chivia-app-ios | src/Pods/MapboxCoreNavigation/MapboxCoreNavigation/RouteStepFormatter.swift | 1 | 2369 | import Foundation
import MapboxDirections
import OSRMTextInstructions
@objc(MBRouteStepFormatter)
public class RouteStepFormatter: Formatter {
let instructions = OSRMInstructionFormatter(version: "v5")
/**
Return an instruction as a `String`.
*/
public override func string(for obj: Any?) -> String? {
return string(for: obj, legIndex: nil, numberOfLegs: nil, markUpWithSSML: false)
}
/**
Returns an instruction as a `String`. Setting `markUpWithSSML` to `true` will return a string containing [SSML](https://www.w3.org/TR/speech-synthesis/) tag information around appropriate strings.
*/
public func string(for obj: Any?, legIndex: Int?, numberOfLegs: Int?, markUpWithSSML: Bool) -> String? {
guard let step = obj as? RouteStep else {
return nil
}
let modifyValueByKey = { (key: OSRMTextInstructions.TokenType, value: String) -> String in
if key == .wayName || key == .rotaryName, let phoneticName = step.phoneticNames?.first {
return value.withSSMLPhoneme(ipaNotation: phoneticName)
}
switch key {
case .wayName, .destination, .rotaryName, .code:
var value = value
value.enumerateSubstrings(in: value.wholeRange, options: [.byWords, .reverse]) { (substring, substringRange, enclosingRange, stop) in
guard var substring = substring?.addingXMLEscapes else {
return
}
if substring.containsDecimalDigit {
substring = substring.asSSMLAddress
}
value.replaceSubrange(substringRange, with: substring)
}
return value
default:
return value
}
}
return instructions.string(for: step, legIndex: legIndex, numberOfLegs: numberOfLegs, roadClasses: step.intersections?.first?.outletRoadClasses, modifyValueByKey: markUpWithSSML ? modifyValueByKey : nil)
}
public override func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?, for string: String, errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
return false
}
}
| lgpl-3.0 | d60ce651e0a88ea0531831bce5fa07d8 | 42.072727 | 211 | 0.610384 | 5.116631 | false | true | false | false |
mozilla-mobile/firefox-ios | Client/Frontend/DefaultBrowserOnboarding/DefaultBrowserOnboardingViewModel.swift | 2 | 2812 | // This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this
// file, You can obtain one at http://mozilla.org/MPL/2.0
import Foundation
import Shared
enum InstallType: String, Codable {
case fresh
case upgrade
case unknown
// Helper methods
static func get() -> InstallType {
guard let rawValue = UserDefaults.standard.string(forKey: PrefsKeys.InstallType),
let type = InstallType(rawValue: rawValue)
else { return unknown }
return type
}
static func set(type: InstallType) {
UserDefaults.standard.set(type.rawValue, forKey: PrefsKeys.InstallType)
}
static func persistedCurrentVersion() -> String {
guard let currentVersion = UserDefaults.standard.string(forKey: PrefsKeys.KeyCurrentInstallVersion) else { return "" }
return currentVersion
}
static func updateCurrentVersion(version: String) {
UserDefaults.standard.set(version, forKey: PrefsKeys.KeyCurrentInstallVersion)
}
}
// Data Model
struct DefaultBrowserOnboardingModel {
var titleText: String
var descriptionText: [String]
var imageText: String
}
class DefaultBrowserOnboardingViewModel {
var goToSettings: (() -> Void)?
var model: DefaultBrowserOnboardingModel?
private static let maxSessionCount = 3
init() {
setupModel()
}
private func setupModel() {
model = DefaultBrowserOnboardingModel(
titleText: String.FirefoxHomepage.HomeTabBanner.EvergreenMessage.HomeTabBannerTitle,
descriptionText: descriptionText,
imageText: String.DefaultBrowserOnboardingScreenshot
)
}
private var descriptionText: [String] {
[String.FirefoxHomepage.HomeTabBanner.EvergreenMessage.HomeTabBannerDescription,
String.DefaultBrowserOnboardingDescriptionStep1,
String.DefaultBrowserOnboardingDescriptionStep2,
String.DefaultBrowserOnboardingDescriptionStep3]
}
static func shouldShowDefaultBrowserOnboarding(userPrefs: Prefs) -> Bool {
// Only show on fresh install
guard InstallType.get() == .fresh else { return false }
let didShow = UserDefaults.standard.bool(forKey: PrefsKeys.KeyDidShowDefaultBrowserOnboarding)
guard !didShow else { return false }
var shouldShow = false
// Get the session count from preferences
let currentSessionCount = userPrefs.intForKey(PrefsKeys.SessionCount) ?? 0
if currentSessionCount == DefaultBrowserOnboardingViewModel.maxSessionCount {
shouldShow = true
UserDefaults.standard.set(true, forKey: PrefsKeys.KeyDidShowDefaultBrowserOnboarding)
}
return shouldShow
}
}
| mpl-2.0 | 4e9f60dd45db4cd332372833998232eb | 31.321839 | 126 | 0.701991 | 5.265918 | false | false | false | false |
ACChe/eidolon | KioskTests/Bid Fulfillment/PlaceBidNetworkModelTests.swift | 1 | 3894 | import Quick
import Nimble
import ReactiveCocoa
import Moya
@testable
import Kiosk
class PlaceBidNetworkModelTests: QuickSpec {
override func spec() {
var fulfillmentController: StubFulfillmentController!
var subject: PlaceBidNetworkModel!
beforeEach {
fulfillmentController = StubFulfillmentController()
subject = PlaceBidNetworkModel(fulfillmentController: fulfillmentController)
}
it("maps good responses to signal completions") {
var completed = false
waitUntil { done in
subject.bidSignal().subscribeCompleted {
completed = true
done()
}
}
expect(completed).to( beTrue() )
}
it("maps good responses to bidder positions") {
waitUntil { done in
subject.bidSignal().subscribeCompleted {
done()
}
}
// ID retrieved from CreateABid.json
expect(subject.bidderPosition?.id) == "5437dd107261692daa170000"
}
it("maps bid details into a proper request") {
var auctionID: String?
var artworkID: String?
var bidCents: String?
let provider = ReactiveCocoaMoyaProvider(endpointClosure: { target -> (Endpoint<ArtsyAPI>) in
if case .PlaceABid(let receivedAuctionID, let receivedArtworkID, let receivedBidCents) = target {
auctionID = receivedAuctionID
artworkID = receivedArtworkID
bidCents = receivedBidCents
}
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(200, stubbedResponse("CreateABid"))}, method: target.method, parameters: target.parameters)
}, stubClosure: MoyaProvider.ImmediatelyStub)
fulfillmentController.loggedInProvider = provider
waitUntil { done in
subject.bidSignal().subscribeCompleted {
done()
}
}
expect(auctionID) == fulfillmentController.bidDetails.saleArtwork?.auctionID
expect(artworkID) == fulfillmentController.bidDetails.saleArtwork?.artwork.id
expect(Int(bidCents!)) == Int(fulfillmentController.bidDetails.bidAmountCents!)
}
describe("failing network responses") {
beforeEach {
let provider = ReactiveCocoaMoyaProvider(endpointClosure: { target -> (Endpoint<ArtsyAPI>) in
let url = target.baseURL.URLByAppendingPathComponent(target.path).absoluteString
return Endpoint(URL: url, sampleResponseClosure: {.NetworkResponse(400, stubbedResponse("CreateABidFail"))}, method: target.method, parameters: target.parameters)
}, stubClosure: MoyaProvider.ImmediatelyStub)
fulfillmentController.loggedInProvider = provider
}
it("maps failures due to outbidding to correct error types") {
var error: NSError?
waitUntil { done in
subject.bidSignal().subscribeError { receivedError in
error = receivedError
done()
}
}
expect(error?.domain) == OutbidDomain
}
it("errors on non-200 status codes"){
var errored = false
waitUntil { done in
subject.bidSignal().subscribeError { _ in
errored = true
done()
}
}
expect(errored).to( beTrue() )
}
}
}
} | mit | 93350d765c655887a6bf3651f1105db3 | 35.064815 | 182 | 0.563431 | 6.200637 | false | false | false | false |
hjanuschka/fastlane | fastlane/swift/ArgumentProcessor.swift | 1 | 2897 | //
// ArgumentProcessor.swift
// FastlaneRunner
//
// Created by Joshua Liebowitz on 9/28/17.
// Copyright © 2017 Joshua Liebowitz. All rights reserved.
//
import Foundation
struct ArgumentProcessor {
let args: [RunnerArgument]
let currentLane: String
let commandTimeout: Int
init(args: [String]) {
// Dump the first arg which is the program name
let fastlaneArgs = stride(from: 1, to: args.count - 1, by: 2).map {
RunnerArgument(name: args[$0], value: args[$0+1])
}
self.args = fastlaneArgs
let fastlaneArgsMinusLanes = fastlaneArgs.filter { arg in
return arg.name.lowercased() != "lane"
}
let potentialLogMode = fastlaneArgsMinusLanes.filter { arg in
return arg.name.lowercased() == "logmode"
}
// Configure logMode since we might need to use it before we finish parsing
if let logModeArg = potentialLogMode.first {
let logModeString = logModeArg.value
Logger.logMode = Logger.LogMode(logMode: logModeString)
}
let lanes = self.args.filter { arg in
return arg.name.lowercased() == "lane"
}
verbose(message: lanes.description)
guard lanes.count == 1 else {
let message = "You must have exactly one lane specified as an arg, here's what I got: \(lanes)"
log(message: message)
fatalError(message)
}
let lane = lanes.first!
self.currentLane = lane.value
// User might have configured a timeout for the socket connection
let potentialTimeout = fastlaneArgsMinusLanes.filter { arg in
return arg.name.lowercased() == "timeoutseconds"
}
if let logModeArg = potentialLogMode.first {
let logModeString = logModeArg.value
Logger.logMode = Logger.LogMode(logMode: logModeString)
}
if let timeoutArg = potentialTimeout.first {
let timeoutString = timeoutArg.value
self.commandTimeout = (timeoutString as NSString).integerValue
} else {
self.commandTimeout = SocketClient.defaultCommandTimeoutSeconds
}
}
func laneParameters() -> [String : String] {
let laneParametersArgs = self.args.filter { arg in
let lowercasedName = arg.name.lowercased()
return lowercasedName != "timeoutseconds" && lowercasedName != "lane" && lowercasedName != "logmode"
}
var laneParameters = [String : String]()
for arg in laneParametersArgs {
laneParameters[arg.name] = arg.value
}
return laneParameters
}
}
// Please don't remove the lines below
// They are used to detect outdated files
// FastlaneRunnerAPIVersion [0.9.1]
| mit | 047f7b4349139be60533cf71d897f6ea | 33.47619 | 112 | 0.60221 | 4.708943 | false | false | false | false |
i-schuetz/SwiftCharts | Examples/Examples/MultipleAxesExample.swift | 1 | 9501 | //
// MultipleAxesExample.swift
// SwiftCharts
//
// Created by ischuetz on 05/05/15.
// Copyright (c) 2015 ivanschuetz. All rights reserved.
//
import UIKit
import SwiftCharts
class MultipleAxesExample: UIViewController {
fileprivate var chart: Chart? // arc
override func viewDidLoad() {
super.viewDidLoad()
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFontSmall)
let bgColors = [UIColor.red, UIColor.blue, UIColor(red: 0, green: 0.7, blue: 0, alpha: 1), UIColor(red: 1, green: 0.5, blue: 0, alpha: 1)]
func createChartPoints0(_ color: UIColor) -> [ChartPoint] {
return [
createChartPoint(0, 0, color),
createChartPoint(2, 2, color),
createChartPoint(5, 2, color),
createChartPoint(8, 11, color),
createChartPoint(10, 2, color),
createChartPoint(12, 3, color),
createChartPoint(16, 22, color),
createChartPoint(20, 5, color)
]
}
func createChartPoints1(_ color: UIColor) -> [ChartPoint] {
return [
createChartPoint(0, 7, color),
createChartPoint(1, 10, color),
createChartPoint(3, 9, color),
createChartPoint(9, 2, color),
createChartPoint(10, -5, color),
createChartPoint(13, -12, color)
]
}
func createChartPoints2(_ color: UIColor) -> [ChartPoint] {
return [
createChartPoint(-200, -10, color),
createChartPoint(-160, -30, color),
createChartPoint(-110, -10, color),
createChartPoint(-40, -80, color),
createChartPoint(-10, -50, color),
createChartPoint(20, 10, color)
]
}
func createChartPoints3(_ color: UIColor) -> [ChartPoint] {
return [
createChartPoint(10000, 70, color),
createChartPoint(20000, 100, color),
createChartPoint(30000, 160, color)
]
}
let chartPoints0 = createChartPoints0(bgColors[0])
let chartPoints1 = createChartPoints1(bgColors[1])
let chartPoints2 = createChartPoints2(bgColors[2])
let chartPoints3 = createChartPoints3(bgColors[3])
let xValues0 = chartPoints0.map{$0.x}
let xValues1 = chartPoints1.map{$0.x}
let xValues2 = chartPoints2.map{$0.x}
let xValues3 = chartPoints3.map{$0.x}
let chartSettings = ExamplesDefaults.chartSettingsWithPanZoom
let top: CGFloat = 80
let viewFrame = CGRect(x: 0, y: top, width: view.frame.size.width, height: view.frame.size.height - top - 10)
let yValues1 = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints0, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: ChartLabelSettings(font: ExamplesDefaults.labelFontSmall, fontColor: bgColors[0]))}, addPaddingSegmentIfEdge: false)
let yValues2 = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints1, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: ChartLabelSettings(font: ExamplesDefaults.labelFontSmall, fontColor: bgColors[1]))}, addPaddingSegmentIfEdge: false)
let yValues4 = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints2, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: ChartLabelSettings(font: ExamplesDefaults.labelFontSmall, fontColor: bgColors[2]))}, addPaddingSegmentIfEdge: false)
let yValues5 = ChartAxisValuesStaticGenerator.generateYAxisValuesWithChartPoints(chartPoints3, minSegmentCount: 10, maxSegmentCount: 20, multiple: 2, axisValueGenerator: {ChartAxisValueDouble($0, labelSettings: ChartLabelSettings(font: ExamplesDefaults.labelFontSmall, fontColor: bgColors[3]))}, addPaddingSegmentIfEdge: false)
let axisTitleFont = ExamplesDefaults.labelFontSmall
let yLowModels: [ChartAxisModel] = [
ChartAxisModel(axisValues: yValues2, lineColor: bgColors[1], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[1]).defaultVertical())]),
ChartAxisModel(axisValues: yValues1, lineColor: bgColors[0], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[0]).defaultVertical())])
]
let yHighModels: [ChartAxisModel] = [
ChartAxisModel(axisValues: yValues4, lineColor: bgColors[2], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[2]).defaultVertical())]),
ChartAxisModel(axisValues: yValues5, lineColor: bgColors[3], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[3]).defaultVertical())])
]
let xLowModels: [ChartAxisModel] = [
ChartAxisModel(axisValues: xValues0, lineColor: bgColors[0], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[0]))]),
ChartAxisModel(axisValues: xValues1, lineColor: bgColors[1], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[1]))])
]
let xHighModels: [ChartAxisModel] = [
ChartAxisModel(axisValues: xValues3, lineColor: bgColors[3], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[3]))]),
ChartAxisModel(axisValues: xValues2, lineColor: bgColors[2], axisTitleLabels: [ChartAxisLabel(text: "Axis title", settings: ChartLabelSettings(font: axisTitleFont, fontColor: bgColors[2]))])
]
// calculate coords space in the background to keep UI smooth
DispatchQueue.global(qos: .background).async {
let coordsSpace = ChartCoordsSpace(chartSettings: chartSettings, chartSize: viewFrame.size, yLowModels: yLowModels, yHighModels: yHighModels, xLowModels: xLowModels, xHighModels: xHighModels)
DispatchQueue.main.async {
let chartInnerFrame = coordsSpace.chartInnerFrame
// create axes
let yLowAxes = coordsSpace.yLowAxesLayers
let yHighAxes = coordsSpace.yHighAxesLayers
let xLowAxes = coordsSpace.xLowAxesLayers
let xHighAxes = coordsSpace.xHighAxesLayers
// create layers with references to axes
let lineModel0 = ChartLineModel(chartPoints: chartPoints0, lineColor: bgColors[0], animDuration: 1, animDelay: 0)
let lineModel1 = ChartLineModel(chartPoints: chartPoints1, lineColor: bgColors[1], animDuration: 1, animDelay: 0)
let lineModel2 = ChartLineModel(chartPoints: chartPoints2, lineColor: bgColors[2], animDuration: 1, animDelay: 0)
let lineModel3 = ChartLineModel(chartPoints: chartPoints3, lineColor: bgColors[3], animDuration: 1, animDelay: 0)
let chartPointsLineLayer0 = ChartPointsLineLayer<ChartPoint>(xAxis: xLowAxes[0].axis, yAxis: yLowAxes[1].axis, lineModels: [lineModel0])
let chartPointsLineLayer1 = ChartPointsLineLayer<ChartPoint>(xAxis: xLowAxes[1].axis, yAxis: yLowAxes[0].axis, lineModels: [lineModel1])
let chartPointsLineLayer3 = ChartPointsLineLayer<ChartPoint>(xAxis: xHighAxes[1].axis, yAxis: yHighAxes[0].axis, lineModels: [lineModel2])
let chartPointsLineLayer4 = ChartPointsLineLayer<ChartPoint>(xAxis: xHighAxes[0].axis, yAxis: yHighAxes[1].axis, lineModels: [lineModel3])
let lineLayers = [chartPointsLineLayer0, chartPointsLineLayer1, chartPointsLineLayer3, chartPointsLineLayer4]
let layers: [ChartLayer] = [
yLowAxes[1], xLowAxes[0], lineLayers[0],
yLowAxes[0], xLowAxes[1], lineLayers[1],
yHighAxes[0], xHighAxes[1], lineLayers[2],
yHighAxes[1], xHighAxes[0], lineLayers[3],
]
let chart = Chart(
frame: viewFrame,
innerFrame: chartInnerFrame,
settings: chartSettings,
layers: layers
)
self.view.addSubview(chart.view)
self.chart = chart
}
}
}
fileprivate func createChartPoint(_ x: Double, _ y: Double, _ labelColor: UIColor) -> ChartPoint {
let labelSettings = ChartLabelSettings(font: ExamplesDefaults.labelFontSmall, fontColor: labelColor)
return ChartPoint(x: ChartAxisValueDouble(x, labelSettings: labelSettings), y: ChartAxisValueDouble(y, labelSettings: labelSettings))
}
}
| apache-2.0 | 50ef1fc7cd583b3c3fd41e7696d29d3f | 57.288344 | 335 | 0.641827 | 5.491908 | false | false | false | false |
saagarjha/Swimat | SwimatTests/tests/n-newline-else/before.swift | 4 | 80 | if a == 1 {
a = 2
}
else {
a = 3
}
guard let a = a
else { return }
| mit | 8af6dc161a591aeda0c66fe7d6b0ebfe | 7.888889 | 19 | 0.4 | 2.424242 | false | false | false | false |
TMTBO/TTARefresher | TTARefresher/Classes/Footer/Back/TTARefresherBackGifFooter.swift | 1 | 3265 | //
// TTARefresherBackGifFooter.swift
// Pods
//
// Created by TobyoTenma on 13/05/2017.
//
//
import UIKit
open class TTARefresherBackGifFooter: TTARefresherBackStateFooter {
open lazy var gifImageView: UIImageView = {
let gifImageView = UIImageView()
self.addSubview(gifImageView)
return gifImageView
}()
lazy var stateImages: [TTARefresherState: [UIImage]] = [:]
lazy var stateDurations: [TTARefresherState: TimeInterval] = [:]
override open var pullingPercent: CGFloat {
didSet {
guard let images = stateImages[.idle] else { return }
if state != .idle || images.count == 0 { return }
gifImageView.stopAnimating()
var index = CGFloat(images.count) * pullingPercent
if index >= CGFloat(images.count) {
index = CGFloat(images.count) - 1
}
gifImageView.image = images[Int(index)]
}
}
override open var state: TTARefresherState {
didSet {
if oldValue == state { return }
if state == .pulling || state == .refreshing {
guard let images = stateImages[state],
images.count != 0 else { return }
gifImageView.isHidden = false
gifImageView.stopAnimating()
if images.count == 1 { // Single Image
gifImageView.image = images.last
} else { // More than one image
gifImageView.animationImages = images
gifImageView.animationDuration = stateDurations[state] ?? Double(images.count) * 0.1
gifImageView.startAnimating()
}
} else if state == .idle {
gifImageView.isHidden = false
} else if state == .noMoreData {
gifImageView.isHidden = true
}
}
}
}
// MARK: - Public Methods
extension TTARefresherBackGifFooter {
public func set(images: [UIImage]?, duration: TimeInterval?, for state: TTARefresherState) {
guard let images = images,
let duration = duration else { return }
stateImages[state] = images
stateDurations[state] = duration
guard let image = images.first,
image.size.height > bounds.height else { return }
bounds.size.height = image.size.height
}
public func set(images: [UIImage]?, for state: TTARefresherState) {
guard let images = images else { return }
set(images: images, duration: Double(images.count) * 0.1, for: state)
}
}
// MARK: - Override Methods
extension TTARefresherBackGifFooter {
override open func prepare() {
super.prepare()
labelLeftInset = 20
}
override open func placeSubviews() {
super.placeSubviews()
if gifImageView.constraints.count != 0 { return }
gifImageView.frame = bounds
if stateLabel.isHidden {
gifImageView.contentMode = .center
} else {
gifImageView.contentMode = .right
gifImageView.frame.size.width = bounds.width * 0.5 - stateLabel.ttaRefresher.textWidth() * 0.5 - labelLeftInset
}
}
}
| mit | 8602fb77c307c270a4889cfaa68f3d47 | 31.009804 | 123 | 0.577335 | 4.977134 | false | false | false | false |
inacioferrarini/York | Classes/Extensions/StringExtensions.swift | 1 | 2669 | // The MIT License (MIT)
//
// Copyright (c) 2016 Inácio Ferrarini
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
import Foundation
public extension String {
public func isNumber() -> Bool {
let badCharacters = CharacterSet.decimalDigits.inverted
return self.rangeOfCharacter(from: badCharacters) == nil
}
public func replaceString(inRange range: NSRange, withString string: String) -> String {
// let startIndex = self.characters.index(self.startIndex, offsetBy: range.location)
// let endIndex = <#T##String.CharacterView corresponding to `startIndex`##String.CharacterView#>.index(startIndex, offsetBy: range.length)
// let stringReplaceRange = startIndex..<endIndex
// return self.replacingCharacters(in: stringReplaceRange, with: string)
return "Recheck this function :("
}
public func replaceStrings(pairing strings: [String : String]) -> String {
var string = self
for (key, value) in strings {
string = string.replacingOccurrences(of: key, with: value)
}
return string
}
public func removeStrings(_ strings: [String]) -> String {
let pairDictionary = strings.reduce([String : String]()) { (currentPairDictionary: [String : String], currentString: String) -> [String : String] in
var updatedCurrentPairDictionary = currentPairDictionary
updatedCurrentPairDictionary[currentString] = ""
return updatedCurrentPairDictionary
}
return self.replaceStrings(pairing: pairDictionary)
}
}
| mit | b491cf2608cc594082c50731528ce135 | 45 | 156 | 0.698276 | 4.688928 | false | false | false | false |
djera/MRTableViewCellCountScrollIndicator | Example/MRTableViewCellCountScrollIndicator/ViewController.swift | 1 | 4308 | import UIKit
import RestKit
import MRTableViewCellCountScrollIndicator
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
@IBOutlet weak var tableView: UITableView!
var articles:[Article] = []
var cellCounter:MRTableViewCellCountScrollIndicator?
override func viewDidLoad() {
super.viewDidLoad()
tableView.delegate = self
tableView.dataSource = self
tableView.estimatedRowHeight = 100
tableView.rowHeight = UITableViewAutomaticDimension
cellCounter = MRTableViewCellCountScrollIndicator(tableView: tableView)
cellCounter!.scrollCountView.mainBackgroundColor = UIColor.blueColor()
cellCounter!.opacity = 0.7
cellCounter!.rightOffset = 0
//cellCounter!.showCellScrollCount(false)
requestData()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: RestKit
func requestData() {self.fetchArticlesFromContext()
let requestPath:String = "/articles.json"
RKObjectManager.sharedManager().getObjectsAtPath(requestPath,
parameters: nil,
success: {(RKObjectRequestOperation, RKMappingResult) in
print("success")
self.fetchArticlesFromContext()
},
failure: {(RKObjectRequestOperation, NSError) in
print("failure")
})
}
func fetchArticlesFromContext() {
let context:NSManagedObjectContext = RKManagedObjectStore.defaultStore().mainQueueManagedObjectContext
let fetchRequest:NSFetchRequest = NSFetchRequest(entityName: "ArticleList")
let descriptor:NSSortDescriptor = NSSortDescriptor(key:"title", ascending: true)
fetchRequest.sortDescriptors = [descriptor]
let error:NSError
var fetchedObjects:[AnyObject] = []
do {
fetchedObjects = try context.executeFetchRequest(fetchRequest)
} catch {
print("fetch error")
return
}
guard let articleList:ArticleList = fetchedObjects.first as? ArticleList else {
return
}
articles = articleList.articles!.allObjects as! [Article]
cellCounter!.totalScrollCountNum = articles.count
tableView.reloadData()
}
// MARK: UITableViewDelegate & UITableViewDataSource
func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return articles.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("ArticleCell")!
let article = articles[indexPath.row]
(cell as! ArticleTableViewCell).mainTitle.text = article.title
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
print("A row has been selected")
}
func scrollViewDidEndDecelerating(scrollView: UIScrollView) {
print("end decelerating")
UIView.animateWithDuration(0.5, delay: 0.5, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.cellCounter!.scrollCountView.alpha = 0.0
}, completion: nil)
}
func scrollViewWillBeginDragging(scrollView: UIScrollView) {
print("begindragging")
UIView.animateWithDuration(0.5, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: {
self.cellCounter!.scrollCountView.alpha = self.cellCounter!.opacity
}, completion: nil)
}
}
| mit | e7c297248700f71f983b93fb1bdf97ad | 38.888889 | 113 | 0.609331 | 6.363368 | false | false | false | false |
SASAbus/SASAbus-ios | SASAbus/Controller/MasterTabBarController.swift | 1 | 2031 | //
// MasterTabBarController.swift
// SASAbus
//
// Copyright (C) 2011-2015 Raiffeisen Online GmbH (Norman Marmsoler, Jürgen Sprenger, Aaron Falk) <[email protected]>
//
// This file is part of SASAbus.
//
// SASAbus 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.
//
// SASAbus 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 SASAbus. If not, see <http://www.gnu.org/licenses/>.
//
import UIKit
import DrawerController
class MasterTabBarController: UITabBarController {
init(nibName nibNameOrNil: String?, title: String?) {
super.init(nibName: nibNameOrNil, bundle: nil)
self.title = title
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override func viewDidLoad() {
super.viewDidLoad()
self.setupLeftMenuButton()
}
func setupLeftMenuButton() {
let image = Asset.menuIcon.image.withRenderingMode(UIImageRenderingMode.alwaysTemplate)
let leftDrawerButton = UIBarButtonItem(
image: image, style: UIBarButtonItemStyle.plain,
target: self,
action: #selector(MasterTabBarController.leftDrawerButtonPress(_:))
)
leftDrawerButton.tintColor = Theme.white
leftDrawerButton.accessibilityLabel = L10n.Accessibility.menu
self.navigationItem.setLeftBarButton(leftDrawerButton, animated: true)
}
// MARK: - Button Handlers
func leftDrawerButtonPress(_ sender: AnyObject?) {
self.evo_drawerController?.toggleDrawerSide(.left, animated: true, completion: nil)
}
}
| gpl-3.0 | 54e406f3a0f8481882441e89382ac271 | 31.222222 | 118 | 0.702956 | 4.582393 | false | false | false | false |
DikeyKing/WeCenterMobile-iOS | WeCenterMobile/Controller/SettingsViewController.swift | 1 | 7431 | //
// SettingsViewController.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/5/30.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import CoreData
import UIKit
class SettingsViewController: UITableViewController {
@IBOutlet weak var noImagesModeSwitch: UISwitch!
@IBOutlet weak var nightModeSwitch: UISwitch!
@IBOutlet weak var fontSizeSlider: UISlider!
@IBOutlet weak var tintColorDisplayView: UIView!
@IBOutlet weak var weiboAccountConnectionSwitch: UISwitch!
@IBOutlet weak var qqAccountConnectionSwitch: UISwitch!
@IBOutlet weak var logoutButton: UIButton!
@IBOutlet weak var cacheSizeLabel: UILabel!
@IBOutlet weak var cacheSizeCalculationActivityIndicatorView: UIActivityIndicatorView!
@IBOutlet weak var clearCachesButton: UIButton!
@IBOutlet weak var noImagesModeView: UIView!
@IBOutlet weak var nightModeView: UIView!
@IBOutlet weak var fontSizeView: UIView!
@IBOutlet weak var tintColorView: UIView!
@IBOutlet weak var weiboAccountConnectionView: UIView!
@IBOutlet weak var qqAccountConnectionView: UIView!
@IBOutlet weak var updateServerConfigurationsView: UIView!
@IBOutlet weak var clearCacheView: UIView!
@IBOutlet weak var noImagesModeLabel: UILabel!
@IBOutlet weak var nightModeLabel: UILabel!
@IBOutlet weak var fontSizeLabel: UILabel!
@IBOutlet weak var tintColorLabel: UILabel!
@IBOutlet weak var weiboAccountConnectionLabel: UILabel!
@IBOutlet weak var qqAccountConnectionLabel: UILabel!
@IBOutlet weak var updateServerConfigurationsLabel: UILabel!
@IBOutlet weak var clearCachesLabel: UILabel!
override func awakeFromNib() {
super.awakeFromNib()
navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "Navigation-Root"), style: .Plain, target: self, action: "showSidebar")
tableView.msr_setTouchesShouldCancel(true, inContentViewWhichIsKindOfClass: UIButton.self)
tableView.delaysContentTouches = false
tableView.msr_wrapperView?.delaysContentTouches = false
tableView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.contentViewController.interactivePopGestureRecognizer)
tableView.panGestureRecognizer.requireGestureRecognizerToFail(appDelegate.mainViewController.sidebar.screenEdgePanGestureRecognizer)
logoutButton.msr_setBackgroundImageWithColor(UIColor.blackColor().colorWithAlphaComponent(0.5), forState: .Highlighted)
clearCachesButton.msr_setBackgroundImageWithColor(UIColor.blackColor().colorWithAlphaComponent(0.5), forState: .Highlighted)
}
override func viewDidLoad() {
super.viewDidLoad()
NSNotificationCenter.defaultCenter().addObserver(self, selector: "currentThemeDidChange", name: CurrentThemeDidChangeNotificationName, object: nil)
reloadData()
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateTheme()
}
func showSidebar() {
appDelegate.mainViewController.sidebar.expand()
}
@IBAction func didPressLogoutButton() {
logout()
}
func logout() {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func toggleNightTheme(sender: UISwitch) {
if sender === nightModeSwitch {
let path = NSBundle.mainBundle().pathForResource("Themes", ofType: "plist")!
let configurations = NSDictionary(contentsOfFile: path)!
let source = SettingsManager.defaultManager.currentTheme.name
let target = source == "Night" ? "Day" : "Night"
let configuration = configurations[target] as! NSDictionary
let theme = Theme(name: target, configuration: configuration)
SettingsManager.defaultManager.currentTheme = theme
}
}
func currentThemeDidChange() {
updateTheme()
}
func reloadData() {
let manager = SettingsManager.defaultManager
nightModeSwitch.on = manager.currentTheme.name == "Night"
var bytes: UInt64 = 0
let stores = DataManager.defaultManager?.managedObjectContext?.persistentStoreCoordinator?.persistentStores as? [NSPersistentStore] ?? []
for store in stores {
let path = store.URL!.path!
bytes += (NSFileManager.defaultManager().attributesOfItemAtPath(path, error: nil)?[NSFileSize] as? NSNumber ?? 0).unsignedLongLongValue
}
cacheSizeLabel.text = "\(bytes / 1024 / 1024) MB"
}
func updateTheme() {
let theme = SettingsManager.defaultManager.currentTheme
msr_navigationBar!.barStyle = theme.navigationBarStyle /// @TODO: Wrong behaviour will occur if put it into the animation block. This might be produced by the reinstallation of navigation bar background view.
msr_navigationBar!.tintColor = theme.navigationItemColor
setNeedsStatusBarAppearanceUpdate()
tableView.indicatorStyle = theme.scrollViewIndicatorStyle
tableView.backgroundColor = theme.backgroundColorA
let views = [
noImagesModeView,
nightModeView,
fontSizeView,
tintColorView,
weiboAccountConnectionView,
qqAccountConnectionView,
updateServerConfigurationsView,
clearCacheView]
for view in views {
view.backgroundColor = theme.backgroundColorB
view.msr_borderColor = theme.borderColorA
}
let labels = [
noImagesModeLabel,
nightModeLabel,
fontSizeLabel,
tintColorLabel,
weiboAccountConnectionLabel,
qqAccountConnectionLabel,
updateServerConfigurationsLabel,
clearCachesLabel]
for label in labels {
label.textColor = theme.titleTextColor
}
let switchs = [
noImagesModeSwitch,
nightModeSwitch,
weiboAccountConnectionSwitch,
qqAccountConnectionSwitch]
for s in switchs {
s.onTintColor = theme.controlColorA
s.tintColor = theme.controlColorB
}
let sliders = [
fontSizeSlider]
for slider in sliders {
slider.minimumTrackTintColor = theme.controlColorA
slider.maximumTrackTintColor = theme.controlColorB
slider.tintColor = theme.controlColorB
}
cacheSizeLabel.textColor = theme.subtitleTextColor
}
@IBAction func clearCaches() {
let ac = UIAlertController(title: "注意", message: "此操作需要您重新登录。", preferredStyle: .ActionSheet)
ac.addAction(UIAlertAction(title: "好的", style: .Default) {
_ in
appDelegate.clearCaches()
appDelegate.mainViewController.dismissViewControllerAnimated(true, completion: nil)
})
ac.addAction(UIAlertAction(title: "取消", style: .Cancel, handler: nil))
presentViewController(ac, animated: true, completion: nil)
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return SettingsManager.defaultManager.currentTheme.statusBarStyle
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
}
| gpl-2.0 | 640008164ffe022bcb5281d571d1ecab | 41.017045 | 216 | 0.689249 | 5.65367 | false | true | false | false |
Kicksort/KSSwipeStack | KSSwipeStack/Classes/SwipeView.swift | 1 | 14327 | //
// SwipeView.swift
// KSSwipeStack
//
// Created by Simon Arneson on 2017-03-24.
// Copyright © 2017 Kicksort Consulting AB. All rights reserved.
//
import RxSwift
import UIKit
struct SwipeHistoryItem {
let data: SwipableData
let origin: CGPoint
}
/// Represents a swipable view to be rendered in the swipe stack.
/// The visual representation of a SwipeData object.
public class SwipeView: UIView {
private lazy var swipeHelper = SwipeHelper(with: frame)
private lazy var horizontalPan = PanDirectionGestureRecognizer(direction: .Horizontal, target: self, action: #selector(respondToHorizontalPan))
private lazy var verticalPan = PanDirectionGestureRecognizer(direction: .Vertical, target: self, action: #selector(respondToVerticalPan))
fileprivate var dataset: [SwipableData] = []
fileprivate var renderedCards: [SwipableView] = []
fileprivate var swipeHistory: [SwipeHistoryItem] = []
fileprivate var options = SwipeOptions()
fileprivate var swipeDelegate: SwipeDelegate?
fileprivate var swipeSubject: PublishSubject<Swipe>?
fileprivate var refillSubject: PublishSubject<Swipe>?
public func setup() {
setup(options: self.options, swipeDelegate: nil)
}
public func setup(options: SwipeOptions) {
setup(options: options, swipeDelegate: nil)
}
public func setup(swipeDelegate: SwipeDelegate?) {
setup(options: self.options, swipeDelegate: swipeDelegate)
}
public func setup(options: SwipeOptions, swipeDelegate: SwipeDelegate?) {
self.options = options
swipeHelper.options = options
if let swipeDelegate = swipeDelegate {
self.swipeDelegate = swipeDelegate
}
setSwipeDirections(horizontal: options.allowHorizontalSwipes, vertical: options.allowVerticalSwipes)
}
/**
Sets whether it should be possible to swipe cards horizontally and/or vertically.
- parameter horizontal: Set to true if the SwipeView should respond to horizontal swipes.
- parameter vertical: Set to true if the SwipeView should respond to vertical swipes.
*/
public func setSwipeDirections(horizontal: Bool, vertical: Bool) {
if horizontal {
addGestureRecognizer(horizontalPan)
} else {
removeGestureRecognizer(horizontalPan)
}
if vertical {
addGestureRecognizer(verticalPan)
} else {
removeGestureRecognizer(verticalPan)
}
}
/**
Adds a card to the stack and calls notifyDatasetUpdated to make sure it is rendered if needed.
- parameter data: The data the new card represents.
*/
public func addCard(_ data: SwipableData) {
dataset.append(data)
notifyDatasetUpdated()
}
/**
Adds a card to the top of the stack and calls notifyDatasetUpdated to make sure it is rendered if needed.
- parameter data: The data the new card represents.
*/
public func addCardToTop(_ data: SwipableData) {
let cardFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
let renderedCard = renderCard(data.getView(with: cardFrame))
renderedCards.insert(renderedCard, at: 0)
addSubview(renderedCard)
bringSubview(toFront: renderedCard)
}
/**
Adds a card to the top of the stack and calls notifyDatasetUpdated to make sure it is rendered if needed.
- parameter data: The data the new card represents.
*/
public func addCardToTop(_ data: SwipableData, from origin: CGPoint) {
let cardFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
let renderedCard = renderCard(data.getView(with: cardFrame))
renderedCard.frame.origin = origin
renderedCards.insert(renderedCard, at: 0)
addSubview(renderedCard)
swipeHelper.transformCard(renderedCard)
bringSubview(toFront: renderedCard)
snapBack()
}
/**
Get swipe events generated by the SwipeView
- returns: RxObservable firing once for each swipe
*/
public func getSwipes() -> Observable<Swipe> {
if let swipeSubject = swipeSubject {
return swipeSubject.asObserver()
}
swipeSubject = PublishSubject<Swipe>()
return getSwipes()
}
/**
Get notifications when the card stack has reached the refillThreshold defined in SwipeOptions
- returns: RxObservable firing with the swipe which put the stack below the refillThreshold
*/
public func needsRefill() -> Observable<Swipe> {
if let refillSubject = refillSubject {
return refillSubject.asObserver()
}
refillSubject = PublishSubject<Swipe>()
return needsRefill()
}
// Undoes last swipe
public func undoSwipe() {
guard options.allowUndo else {
return
}
if let cardToUndo = swipeHistory.popLast() {
addCardToTop(cardToUndo.data, from: cardToUndo.origin)
}
}
fileprivate func setupSwipeCards() {
}
/**
Fetch the card currently visible at the top of the stack.
- returns: The top card (the currently visible) in the stack.
*/
fileprivate func getCurrentCard() -> SwipableView? {
return renderedCards.first
}
/**
Notify the swipe view that the dataset has changed.
*/
public func notifyDatasetUpdated() {
if self.renderedCards.count < options.maxRenderedCards, !dataset.isEmpty {
fillStack()
}
}
/**
Fills the card stack by rendering new cards from the dataset if needed.
*/
private func fillStack() {
let cardFrame = CGRect(x: 0, y: 0, width: frame.width, height: frame.height)
let card = renderCard(dataset.removeFirst().getView(with: cardFrame))
self.renderedCards.append(card)
if self.renderedCards.count < options.maxRenderedCards, !dataset.isEmpty {
fillStack()
}
}
/**
Renders a Swipeble View onto the screen and puts it in the correct postion in the stack.
- parameter view: The SwipeableView to render.
*/
func renderCard(_ view: SwipableView) -> SwipableView {
if !renderedCards.isEmpty, let lastCard = renderedCards.last {
insertSubview(view, belowSubview: lastCard)
} else {
addSubview(view)
sendSubview(toBack: view)
}
return view
}
/// Renders the next card from the stack
func showNextCard() {
if !renderedCards.isEmpty {
let swipedCard = renderedCards.removeFirst()
self.isUserInteractionEnabled = true
swipedCard.removeFromSuperview()
swipedCard.respondToDismiss()
}
if self.renderedCards.count < options.maxRenderedCards, !dataset.isEmpty {
fillStack()
}
isUserInteractionEnabled = true
}
/// Handles horizontal pan gestures (drags) in the view
///
/// - Parameter gesture: the gesture itself
@objc func respondToHorizontalPan(gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: self)
let velocity = gesture.velocity(in: self)
let magnitude = swipeHelper.calculateThrowMagnitude(for: velocity)
if let card = getCurrentCard() {
let previousOrigin = card.frame.origin
let nextOrigin = CGPoint(x: self.frame.origin.x + translation.x, y: self.frame.origin.y + translation.y)
card.center = CGPoint(x: frame.width / 2 + translation.x, y: frame.height / 2 + translation.y)
swipeHelper.transformCard(card)
let distance = abs(Float(card.center.x.distance(to: self.center.x) / (frame.width / 4)))
card.respondToSwipe(direction: translation.x > 0 ? .right : .left, distance: distance)
if gesture.state == .ended {
let throwingThresholdExceeded = magnitude > options.throwingThreshold
let panThresholdExceeded = abs(nextOrigin.x) > frame.width * options.horizontalPanThreshold
if throwingThresholdExceeded {
if velocity.x > 0 {
respondToSwipe(.right, gesture: gesture)
} else {
respondToSwipe(.left, gesture: gesture)
}
} else if panThresholdExceeded {
if previousOrigin.x < options.visibleImageOrigin.x {
respondToSwipe(.left, gesture: gesture)
} else {
respondToSwipe(.right, gesture: gesture)
}
} else {
snapBack()
}
} else if gesture.state == .cancelled {
snapBack()
}
}
}
/// Handles vertical pan gestures (drags) in the view
///
/// - Parameter gesture: the gesture itself
@objc func respondToVerticalPan(gesture: UIPanGestureRecognizer) {
let translation = gesture.translation(in: self)
let velocity = gesture.velocity(in: self)
let magnitude = swipeHelper.calculateThrowMagnitude(for: velocity)
if let card = getCurrentCard() {
let previousOrigin = card.frame.origin
let nextOrigin = CGPoint(x: self.frame.origin.x + translation.x, y: self.frame.origin.y + translation.y)
card.center = CGPoint(x: frame.width / 2 + translation.x, y: frame.height / 2 + translation.y)
swipeHelper.transformCard(card)
let distance = abs(Float(card.center.y.distance(to: self.center.y) / (frame.height / 4)))
card.respondToSwipe(direction: translation.y > 0 ? .down : .up, distance: distance)
if gesture.state == .ended {
let throwingThresholdExceeded = magnitude > options.throwingThreshold
let panThresholdExceeded = abs(nextOrigin.y) > frame.height * options.verticalPanThreshold
if throwingThresholdExceeded {
if velocity.y > 0 {
respondToSwipe(.down, gesture: gesture)
} else {
respondToSwipe(.up, gesture: gesture)
}
} else if panThresholdExceeded {
if previousOrigin.y < options.visibleImageOrigin.y {
respondToSwipe(.up, gesture: gesture)
} else {
respondToSwipe(.down, gesture: gesture)
}
} else {
snapBack()
}
} else if gesture.state == .cancelled {
snapBack()
}
}
}
/// Handles when a view is swiped in the view
///
/// - Parameters:
/// - direction: The direction in which the view was swiped
/// - gesture: The gesture generating the swipe
open func respondToSwipe(_ direction: SwipeDirection, gesture: UIGestureRecognizer? = nil) {
guard let card = getCurrentCard() else {
// TODO:
return
}
if card.isUndoable(), let data = card.getData() {
swipeHistory.append(SwipeHistoryItem(data: data, origin: card.frame.origin))
}
dismissCard(direction: direction, gesture: gesture, completion: { [weak self] in
let swipe = Swipe(direction: direction, data: card.getData())
if let swipeHandler = self?.swipeDelegate {
swipeHandler.onNext(swipe)
}
if let swipeSubject = self?.swipeSubject {
swipeSubject.onNext(swipe)
}
if self?.needsRefill() ?? false, let refillSubject = self?.refillSubject {
refillSubject.onNext(swipe)
}
})
}
/// Resets the currently visible view to the original position with a 'snap' effect.
func snapBack() {
if let currentCard = getCurrentCard() {
swipeHelper.resetCard(currentCard)
swipeHelper.move(currentCard, duration: options.snapDuration, toPoint: options.visibleImageOrigin)
currentCard.resetView()
}
}
/// Get the number of items in the swipe view, both rendered and unrendered.
///
/// - Returns: The number of items in the dataset
func getDataCount() -> Int {
return self.renderedCards.count + self.dataset.count
}
/// Checks if the refill threshold is surpassed
///
/// - Returns: true if the data count is below the refill threshold
func needsRefill() -> Bool {
return getDataCount() <= options.refillThreshold
}
/// Used to dismiss a swipable view through an end position.
/// Animates a movement to specified position and then dismisses the swipable view.
/// - Parameters:
/// - toPoint: destination of dismissal animation
/// - gesture: the gesture generating the dismissal
/// - completion: callback firing when the animation is completed and the view is dismissed.
fileprivate func dismissCard(direction: SwipeDirection, gesture: UIGestureRecognizer?, completion: @escaping () -> Void) {
guard let card = getCurrentCard() else {
return
}
isUserInteractionEnabled = !options.freezeWhenDismissing
var toPoint = swipeHelper.convertToCenter(origin: direction.getSwipeEndpoint())
if options.allowHorizontalSwipes && !options.allowVerticalSwipes {
// Special case to better handle rapid flicks
if !(card.frame.origin.x == 0 && card.frame.origin.y == 0) {
if card.center.x > frame.width / 2 {
toPoint = swipeHelper.calculateEndpoint(card)
} else if let gesture = gesture as? UIPanGestureRecognizer {
let velocity = gesture.velocity(in: self)
if !(velocity.x == 0 && velocity.y == 0) {
toPoint = swipeHelper.calculateEndpoint(card, basedOn: velocity)
}
}
}
}
swipeHelper.moveFastAndTransform(card, toPoint: toPoint, completion: {
completion()
self.showNextCard()
})
}
}
| mit | d7f0b9b1e421d3fc6a4ccfcef6298f24 | 37.101064 | 147 | 0.61699 | 4.976033 | false | false | false | false |
rdhiggins/SPZUtilityKit | SPZUtilityKit/Conversion.swift | 1 | 2143 | //
// Conversion.swift
// SPZUtilityKit
//
// Created by Rodger Higgins on 5/26/15.
// Copyright (c) 2015 Spazstik Software. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import Foundation
public extension String {
public func toDouble() -> Double? {
let scanner = NSScanner(string: self)
var double: Double = 0
if scanner.scanDouble(&double) {
return double
}
return nil
}
public func toFloat() -> Float? {
let scanner = NSScanner(string: self)
var float: Float = 0
if scanner.scanFloat(&float) {
return float
}
return nil
}
public func toUInt() -> UInt? {
if let val = Int(self.trim()) {
if val >= 0 {
return UInt(val)
}
}
return nil
}
public func toBool() -> Bool? {
let text = self.trim().lowercaseString
if text == "true" || text == "false" || text == "yes" || text == "no" {
return (text as NSString).boolValue
}
return nil
}
} | mit | 79261d65dcdce3e9939d12a0d54c7861 | 29.628571 | 80 | 0.642557 | 4.436853 | false | false | false | false |
bigL055/Routable | Example/Pods/SPKit/Sources/UITextField/SP+UITextField.swift | 1 | 3484 | //
// SPKit
//
// Copyright (c) 2017 linhay - https:// github.com/linhay
//
// 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
import UIKit
public extension UITextField{
/// 占位文字颜色
public var placeholderColor: UIColor? {
get{
guard var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil),
let color = attr[NSAttributedStringKey.foregroundColor] as? UIColor else{ return textColor }
return color
}
set {
guard let placeholder = self.placeholder, let color = newValue else { return }
if var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) {
attr[NSAttributedStringKey.foregroundColor] = newValue
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
return
}
let attr = [NSAttributedStringKey.foregroundColor: color]
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
}
}
/// 占位文字字体
public var placeholderFont: UIFont? {
get{
guard var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil),
let ft = attr[.font] as? UIFont else{ return font }
return ft
}
set {
guard let placeholder = self.placeholder, let font = newValue else { return }
if var attr = attributedPlaceholder?.attributes(at: 0, effectiveRange: nil) {
attr[NSAttributedStringKey.font] = newValue
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
return
}
let attr = [NSAttributedStringKey.font: font]
attributedPlaceholder = NSAttributedString(string: placeholder, attributes: attr)
}
}
/// 左边间距
public var leftPadding: CGFloat{
get{
return leftView?.frame.width ?? 0
}
set{
guard let view = leftView else {
self.leftViewMode = .always
leftView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: bounds.height))
return
}
view.bounds.size.width = newValue
}
}
/// 右边间距
public var rightPadding: CGFloat{
get{
return rightView?.frame.width ?? 0
}
set{
guard let view = rightView else {
self.rightViewMode = .always
leftView = UIView(frame: CGRect(x: 0, y: 0, width: newValue, height: bounds.height))
return
}
view.bounds.size.width = newValue
}
}
}
| mit | f547f835cd4573b61bc5ae5d8782edb5 | 34.505155 | 100 | 0.681765 | 4.549538 | false | false | false | false |
steelwheels/Canary | Source/CNAuthorize.swift | 2 | 539 | /**
* @file CNAuthorize.swift
* @brief Define CNAuthorize class
* @par Copyright
* Copyright (C) 2018 Steel Wheels Project
*/
import Foundation
public enum CNAuthorizeState: Int
{
case Undetermined = 0
case Examinating = 1
case Denied = 2
case Authorized = 3
public var description: String {
var result: String
switch self {
case .Undetermined: result = "undetermined"
case .Examinating: result = "examinating"
case .Denied: result = "denied"
case .Authorized: result = "authorized"
}
return result
}
}
| gpl-2.0 | cc1d1988d5cd71f61b1a0c8a68c40af3 | 18.25 | 45 | 0.697588 | 3.170588 | false | false | false | false |
mcxiaoke/learning-ios | LineDraw/LineDraw/Extensions.swift | 1 | 4005 | //
// Extensions.swift
// TouchTracker
//
// Created by Xiaoke Zhang on 2017/8/17.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
extension UIResponder {
var viewController: UIViewController? {
return self as? UIViewController ?? next?.viewController
// if let vc = self as? UIViewController {
// return vc
// }
//
// return next?.viewController
}
}
extension UIImage{
convenience init(view: UIView) {
UIGraphicsBeginImageContextWithOptions(view.bounds.size, view.isOpaque, 0.0)
view.drawHierarchy(in: view.bounds, afterScreenUpdates: false)
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
self.init(cgImage: (image?.cgImage)!)
}
}
extension Array where Element: Equatable {
static func -= (lhs: inout Array, rhs: Element) {
lhs.remove(object: rhs)
}
static func += (lhs: inout Array, rhs: Element) {
lhs.append(rhs)
}
@discardableResult mutating func remove(object: Element) -> Bool {
if let index = index(of: object) {
self.remove(at: index)
return true
}
return false
}
@discardableResult mutating func remove(where predicate: (Array.Iterator.Element) -> Bool) -> Bool {
if let index = self.index(where: { (element) -> Bool in
return predicate(element)
}) {
self.remove(at: index)
return true
}
return false
}
}
extension CGPoint : Hashable {
func distance(point: CGPoint) -> Float {
let dx = Float(x - point.x)
let dy = Float(y - point.y)
return sqrt((dx * dx) + (dy * dy))
}
public var hashValue: Int {
// iOS Swift Game Development Cookbook
// https://books.google.se/books?id=QQY_CQAAQBAJ&pg=PA304&lpg=PA304&dq=swift+CGpoint+hashvalue&source=bl&ots=1hp2Fph274&sig=LvT36RXAmNcr8Ethwrmpt1ynMjY&hl=sv&sa=X&ved=0CCoQ6AEwAWoVChMIu9mc4IrnxgIVxXxyCh3CSwSU#v=onepage&q=swift%20CGpoint%20hashvalue&f=false
return x.hashValue << 32 ^ y.hashValue
}
}
func ==(lhs: CGPoint, rhs: CGPoint) -> Bool {
// return lhs.distance(point: rhs) < 0.000001
//CGPointEqualToPoint(lhs, rhs)
return lhs.hashValue == rhs.hashValue
}
extension CGFloat {
static func random() -> CGFloat {
return CGFloat(arc4random()) / CGFloat(UInt32.max)
}
static func random(_ max: UInt32) -> CGFloat {
return CGFloat(arc4random() % max)
}
}
extension UIColor {
static func random() -> UIColor {
return UIColor(red: .random(),
green: .random(),
blue: .random(),
alpha: 1.0)
}
static func random2() -> UIColor {
return UIColor(hue: .random(256)/256.0,
saturation: .random(256)/256.0,
brightness: .random(256)/256.0,
alpha:1)
}
// http://crunchybagel.com/working-with-hex-colors-in-swift-3/
convenience init(hex: String) {
let scanner = Scanner(string: hex)
scanner.scanLocation = 0
var rgbValue: UInt64 = 0
scanner.scanHexInt64(&rgbValue)
let r = (rgbValue & 0xff0000) >> 16
let g = (rgbValue & 0xff00) >> 8
let b = rgbValue & 0xff
self.init(
red: CGFloat(r) / 0xff,
green: CGFloat(g) / 0xff,
blue: CGFloat(b) / 0xff, alpha: 1
)
}
var toHexString: String {
var r: CGFloat = 0
var g: CGFloat = 0
var b: CGFloat = 0
var a: CGFloat = 0
self.getRed(&r, green: &g, blue: &b, alpha: &a)
return String(
format: "%02X%02X%02X",
Int(r * 0xff),
Int(g * 0xff),
Int(b * 0xff)
)
}
}
| apache-2.0 | 1a3b039cdcfb5ce474f46d5049245456 | 26.986014 | 264 | 0.554973 | 3.877907 | false | false | false | false |
mcxiaoke/learning-ios | ios_programming_4th/HypnoNerd-ch7/HypnoNerd/ReminderViewController.swift | 2 | 1730 | //
// ReminderViewController.swift
// HypnoNerd
//
// Created by Xiaoke Zhang on 2017/8/15.
// Copyright © 2017年 Xiaoke Zhang. All rights reserved.
//
import UIKit
class ReminderViewController: UIViewController {
@IBOutlet weak var datePicker:UIDatePicker!
@IBOutlet weak var colorPicker:UISegmentedControl!
@IBAction func addReminder(_ sender:AnyObject) {
let date = datePicker.date
print("Setting a reminder at \(date)")
let note = UILocalNotification()
note.alertBody = "Hypnotize Me!"
note.fireDate = date
UIApplication.shared.scheduleLocalNotification(note)
}
@IBAction func setColor(_ sender:AnyObject) {
setCircleColor()
}
func setCircleColor() {
let index = colorPicker.selectedSegmentIndex
let colors = [UIColor.red, UIColor.green, UIColor.blue]
print("Set color index to \(index)")
guard let vc = self.tabBarController?.viewControllers?[0] else { return }
guard let hv = vc.view as? HypnosisterView else { return }
hv.circleColor = colors[index]
}
override func viewDidLoad() {
super.viewDidLoad()
setCircleColor()
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
datePicker.minimumDate = Date()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
self.tabBarItem.title = "Reminder"
self.tabBarItem.image = UIImage(named:"Time.png")
}
}
| apache-2.0 | 6abad44f19cfe946b5057843bdc755f4 | 28.271186 | 82 | 0.643312 | 4.770718 | false | false | false | false |
ben-ng/swift | validation-test/compiler_crashers_fixed/00948-swift-modulefile-readmembers.swift | 1 | 578 | // This source file is part of the Swift.org open source project
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// RUN: not %target-swift-frontend %s -typecheck
if c == D>() -> ()
var d = {
let c: String = g> String
}
}
extension String {
struct c: a {
}
get
func a: Boolean)
}(g, y: Any] = B<T
func a: T) {
}
}
protocol b {
func b<S : b =
| apache-2.0 | 33b5762eb3b502d512a3db167c35f169 | 23.083333 | 79 | 0.679931 | 3.22905 | false | false | false | false |
mcomisso/hellokiwi | kiwi/FirstViewController.swift | 1 | 18631 | //
// FirstViewController.swift
// kiwi
//
// Created by Matteo Comisso on 03/01/15.
// Copyright (c) 2015 Blue-Mate. All rights reserved.
//
import UIKit
import AVFoundation
import CoreBluetooth
class FirstViewController: UIViewController, PFLogInViewControllerDelegate, PFSignUpViewControllerDelegate, AVAudioPlayerDelegate, BWWalkthroughViewControllerDelegate, CBCentralManagerDelegate {
//////////////////////////////////////////////////////
//MARK: Properties
//////////////////////////////////////////////////////
@IBOutlet weak var nameLabel: UILabel!
@IBOutlet weak var emailLabel: UILabel!
@IBOutlet weak var avatarImage: UIImageView!
@IBOutlet weak var collectedStarsLabel: UILabel!
//Places star
@IBOutlet weak var hfarmStar: UIImageView!
@IBOutlet weak var lifeStar: UIImageView!
@IBOutlet weak var serraStar: UIImageView!
@IBOutlet weak var conviviumStar: UIImageView!
//People star
@IBOutlet weak var edoStar: UIImageView!
@IBOutlet weak var marcoStar: UIImageView!
@IBOutlet weak var ennioStar: UIImageView!
// class variables
var starsFound = [String]()
var audioPlayer: AVAudioPlayer?
var bluetoothManager: CBCentralManager?
//////////////////////////////////////////////////////
//MARK:- View Controller methods
//////////////////////////////////////////////////////
override func viewDidLoad() {
super.viewDidLoad()
self.setNeedsStatusBarAppearanceUpdate()
self.addBeaconsObservers()
self.setupViews()
self.loadPointsStatus()
// Bluetooth manager
let options = ["CBCentralManagerOptionShowPowerAlertKey":"false"]
bluetoothManager = CBCentralManager(delegate: self, queue: dispatch_get_main_queue(), options: options)
self.centralManagerDidUpdateState(bluetoothManager)
}
override func viewDidAppear(animated: Bool) {
self.checkIfUserExists()
if (PFUser.currentUser() != nil) {
let userDefaults = NSUserDefaults.standardUserDefaults()
if !userDefaults.boolForKey("wtPresented") {
showWalkthrough()
userDefaults.setBool(true, forKey: "wtPresented")
userDefaults.synchronize()
} else {
let user: PFUser = PFUser.currentUser()
self.emailLabel.text = user.email
if PFFacebookUtils.isLinkedWithUser(user) {
self.nameLabel.text = user.objectForKey("first_name").stringByAppendingString(" ".stringByAppendingString(user.objectForKey("last_name") as String))
FBRequestConnection.startForMeWithCompletionHandler({ (connection: FBRequestConnection!, result: AnyObject!, error: NSError!) -> Void in
if (error == nil) {
let facebookId = result.objectForKey("id") as String
let pictureID = "https://graph.facebook.com/".stringByAppendingString(facebookId).stringByAppendingString("/picture?type=large")
self.avatarImage.contentMode = UIViewContentMode.ScaleAspectFit
self.avatarImage.sd_setImageWithURL(NSURL(string: pictureID), placeholderImage: UIImage(named: "kiwiLogo"))
self.avatarImage.clipsToBounds = true
self.avatarImage.layer.cornerRadius = self.avatarImage.bounds.size.width / 2
}
})
} else {
self.nameLabel.text = user.objectForKey("username").capitalizedString
}
}
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
//////////////////////////////////////////////////////
//MARK:- Walkthrough
//////////////////////////////////////////////////////
func showWalkthrough() {
let stb = UIStoryboard(name:"WT", bundle: nil)
let walkthrough = stb.instantiateViewControllerWithIdentifier("master") as BWWalkthroughViewController
let page1 = stb.instantiateViewControllerWithIdentifier("page1") as UIViewController
let page2 = stb.instantiateViewControllerWithIdentifier("page2") as UIViewController
let page3 = stb.instantiateViewControllerWithIdentifier("page3") as UIViewController
walkthrough.delegate = self
walkthrough.addViewController(page1)
walkthrough.addViewController(page2)
walkthrough.addViewController(page3)
self.presentViewController(walkthrough, animated: true, completion: nil)
}
func walkthroughCloseButtonPressed() {
self.dismissViewControllerAnimated(true, completion: nil)
}
//////////////////////////////////////////////////////
//MARK:- Personal Utils
//////////////////////////////////////////////////////
func setupViews() {
self.navigationController?.navigationBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barTintColor = UIColor.blackColor()
self.tabBarController?.tabBar.barTintColor = UIColor.blackColor()
self.tabBarController?.tabBar.tintColor = UIColor.whiteColor()
self.navigationController?.navigationBar.barStyle = UIBarStyle.Black
}
func checkIfUserExists() {
if (PFUser.currentUser() == nil) {
var loginViewController = PFLogInViewController()
loginViewController.logInView.logo = UIImageView(image: UIImage(named: "kiwiLogo"))
loginViewController.logInView.logo.contentMode = UIViewContentMode.ScaleAspectFit
loginViewController.facebookPermissions = []
loginViewController.fields = PFLogInFields.Default | PFLogInFields.Facebook | PFLogInFields.Twitter
loginViewController.delegate = self
var signupController = PFSignUpViewController()
signupController.fields = PFSignUpFields.Default
signupController.signUpView.logo = UIImageView(image: UIImage(named: "kiwiLogo"))
signupController.signUpView.logo.contentMode = UIViewContentMode.ScaleAspectFit
signupController.delegate = self
//Set the signup controller
loginViewController.signUpController = signupController
self.presentViewController(loginViewController, animated: true, completion: nil)
}
}
func addBeaconsObservers() {
NSNotificationCenter.defaultCenter().addObserver(self, selector: "foundPOI:", name: "BMFoundPOI", object: nil)
}
func loadPointsStatus() {
if let starsFound = NSUserDefaults.standardUserDefaults().objectForKey("starsFound") as? [String] {
for starName in starsFound {
self.starsFound.append(starName)
switch starName {
case "edoardo":
edoStar.highlighted = true
case "marco":
marcoStar.highlighted = true
case "ennio":
ennioStar.highlighted = true
case "serra":
serraStar.highlighted = true
case "convivium":
conviviumStar.highlighted = true
case "hfarm":
hfarmStar.highlighted = true
case "life":
lifeStar.highlighted = true
default:
println("Nope")
}
}
self.setCollectedString()
}
}
func foundPOI(notification: NSNotification!) {
let userInfo = notification.userInfo as NSDictionary!
let foundPOI = userInfo.objectForKey("poi") as String
if (find(starsFound, foundPOI) != nil) {
return
}
else {
starsFound.append(foundPOI)
let alert = SCLAlertView()
alert.backgroundType = .Blur
switch foundPOI {
case "edoardo":
edoStar.highlighted = true
alert.showSuccess(self, title: "\(foundPOI.capitalizedString)", subTitle: "From designer to the signer", closeButtonTitle: "Ok", duration: 0.0)
case "marco":
marcoStar.highlighted = true
alert.showSuccess(self, title: "\(foundPOI.capitalizedString)", subTitle: "The designed designer", closeButtonTitle: "Ok", duration: 0.0)
case "ennio":
ennioStar.highlighted = true
alert.showSuccess(self, title: "\(foundPOI.capitalizedString)", subTitle: "Marketing? No problem", closeButtonTitle: "Ok", duration: 0.0)
case "serra":
serraStar.highlighted = true
alert.showSuccess(self, title: "La \(foundPOI.capitalizedString)", subTitle: "Ti va un caffè?", closeButtonTitle: "Ok", duration: 0.0)
case "convivium":
conviviumStar.highlighted = true
alert.showSuccess(self, title: "Il \(foundPOI.capitalizedString)", subTitle: "Le presentazioni verranno svolte qui!", closeButtonTitle: "Ok", duration: 0.0)
case "hfarm":
hfarmStar.highlighted = true
alert.showSuccess(self, title: "\(foundPOI.capitalizedString)", subTitle: "Benvenuto in H-Farm", closeButtonTitle: "Ok", duration: 0.0)
case "life":
lifeStar.highlighted = true
alert.showSuccess(self, title: "\(foundPOI.capitalizedString)", subTitle: "Benvenuto in Life", closeButtonTitle: "Ok", duration: 0.0)
default:
println("That's not the right beacon")
}
//Write the "stelle collezionate" string
self.setCollectedString()
NSUserDefaults.standardUserDefaults().setObject(starsFound, forKey: "starsFound")
NSUserDefaults.standardUserDefaults().synchronize()
}
}
func setCollectedString() {
self.collectedStarsLabel.text = "Stelle collezionate: \(self.starsFound.count) di 7"
if (self.starsFound.count == 7) {
let audioSession = AVAudioSession.sharedInstance()
let path = NSBundle.mainBundle().pathForResource("winner", ofType: "mp3")
let error = NSErrorPointer()
self.audioPlayer = AVAudioPlayer(contentsOfURL: NSURL(fileURLWithPath: path!), error: error)
audioSession.setCategory(AVAudioSessionCategoryPlayback, error: nil)
if (error == nil) {
self.audioPlayer!.delegate = self
self.audioPlayer!.prepareToPlay()
self.audioPlayer!.play()
} else {
println("\(error.debugDescription)")
}
// SCLAlertView show alert
let winnerAlert = SCLAlertView()
winnerAlert.showAnimationType = .SlideInFromCenter
winnerAlert.addButton("Si", actionBlock: { () -> Void in
let shareString = "Ho visitato tutti i punti di interesse! #KiwiappKiwi"
let shareView = UIActivityViewController(activityItems: [shareString], applicationActivities: nil)
self.presentViewController(shareView, animated: true, completion: nil)
})
winnerAlert.showCustom(self, image: UIImage(named: "winner"), color: UIColor(red: 0.878431373, green: 0.529411765, blue: 0.019607843, alpha: 1), title: "Completato!", subTitle: "Congratulazioni, hai visitato tutti i punti di interesse! Vuoi condividerlo?", closeButtonTitle: "No", duration: 0.0)
}
}
//////////////////////////////////////////////////////
//MARK:- Button actions
//////////////////////////////////////////////////////
@IBAction func reloadData(sender: AnyObject) {
let resetAlert = SCLAlertView()
resetAlert.backgroundType = .Blur
resetAlert.addButton("Cancella", actionBlock: { () -> Void in
self.starsFound.removeAll(keepCapacity: false)
NSUserDefaults.standardUserDefaults().setObject(self.starsFound, forKey: "starsFound")
NSUserDefaults.standardUserDefaults().synchronize()
self.marcoStar.highlighted = false
self.serraStar.highlighted = false
self.edoStar.highlighted = false
self.ennioStar.highlighted = false
self.hfarmStar.highlighted = false
self.conviviumStar.highlighted = false
self.lifeStar.highlighted = false
self.setCollectedString()
})
resetAlert.showWarning(self, title: "Attenzione!", subTitle: "Le stelle collezionate verranno ripristinate a 0", closeButtonTitle: "Annulla", duration: 0.0)
}
@IBAction func signOut(sender: AnyObject) {
let alertView = SCLAlertView()
alertView.backgroundType = .Blur
alertView.addButton("Esci", actionBlock: { () -> Void in
PFUser.logOut()
self.nameLabel.text = "Welcome"
self.avatarImage.image = UIImage(named: "startScreenLogo")
self.checkIfUserExists()
})
alertView.showNotice(self, title: "Logout", subTitle: "Scollegarsi dall'applicazione?", closeButtonTitle: "Annulla", duration: 0.0)
}
}
//////////////////////////////////////////////////////
//MARK:- LOGIN DELEGATE METHODS
//////////////////////////////////////////////////////
extension FirstViewController {
func centralManagerDidUpdateState(central: CBCentralManager!) {
var state = ""
switch central.state {
case .PoweredOff:
state = "PoweredOff"
let alertNotification = UIAlertController(title: "Attenzione", message: "Per usufruire della migliore esperienza d'uso è necessario accendere il bluetooth.", preferredStyle: UIAlertControllerStyle.Alert)
let okAction = UIAlertAction(title: "Ok", style: UIAlertActionStyle.Cancel, handler: nil)
alertNotification.addAction(okAction)
self.presentViewController(alertNotification, animated: true, completion: nil)
case .PoweredOn:
state = "Powered On"
case .Resetting:
state = "Resetting"
case .Unauthorized:
state = "Unauthorized"
case .Unsupported:
state = "Unsupported"
case .Unknown:
state = "Unknown"
}
// println("The state of bluetooth is \(state)")
}
}
//////////////////////////////////////////////////////
//MARK:- LOGIN DELEGATE METHODS
//////////////////////////////////////////////////////
extension FirstViewController {
func logInViewController(logInController: PFLogInViewController!, didFailToLogInWithError error: NSError!) {
//Print errors
println("\(error.localizedDescription, error.localizedFailureReason)")
}
func logInViewController(logInController: PFLogInViewController!, didLogInUser user: PFUser!) {
println("The user successfully logged in")
if PFFacebookUtils.isLinkedWithUser(user) {
//Request data from facebook to fill the missing params
FBRequestConnection.startForMeWithCompletionHandler({ (connection: FBRequestConnection!, response: AnyObject!, error: NSError!) -> Void in
if (error == nil) {
var userData = response as NSDictionary
var firstName = userData["first_name"] as String?
var lastName = userData["last_name"] as String?
var email = userData["email"] as String?
println("User Data: \(userData.description)")
let parseUser = PFUser.currentUser()
parseUser.setValue(firstName, forKey: "first_name")
parseUser.setValue(lastName, forKey: "last_name")
parseUser.setValue(email, forKey: "email")
parseUser.saveInBackgroundWithBlock(nil)
}
else
{
println("\(error.localizedFailureReason)")
}
})
}
self.dismissViewControllerAnimated(true, completion: nil)
}
func logInViewControllerDidCancelLogIn(logInController: PFLogInViewController!) {
//Tell the user that the login or registration is required.
//AlertView
let alertView = SCLAlertView()
alertView.backgroundType = .Blur
alertView.showError(self, title: "Attenzione", subTitle: "È richiesta una registrazione per il corretto funzionamento di questa applicazione.", closeButtonTitle: "Ok", duration: 0.0)
}
}
//////////////////////////////////////////////////////
//MARK:- SIGNUP DELEGATE METHODS
//////////////////////////////////////////////////////
extension FirstViewController {
func signUpViewController(signUpController: PFSignUpViewController!, didSignUpUser user: PFUser!) {
self.dismissViewControllerAnimated(true, completion: nil)
}
func signUpViewController(signUpController: PFSignUpViewController!, shouldBeginSignUp info: [NSObject : AnyObject]!) -> Bool {
let password = info["password"] as NSString
let username = info["username"] as NSString
let email = info["email"] as NSString
if ((email.length == 0) | (username.length == 0) | (password.length == 0)) {
let alertView = SCLAlertView()
alertView.backgroundType = .Blur
alertView.showError(self, title: "Attenzione", subTitle: "È richiesto il completamento di ogni campo", closeButtonTitle: "Ok", duration: 0.0)
return false
}
return true
}
func signUpViewController(signUpController: PFSignUpViewController!, didFailToSignUpWithError error: NSError!) {
//Print errors
println("\(error.localizedDescription, error.localizedFailureReason)")
}
} | apache-2.0 | 2118fb2c98e1510f0cb169dfb37d9ad4 | 41.921659 | 307 | 0.58587 | 5.713804 | false | false | false | false |
sun409377708/swiftDemo | SinaSwiftPractice/SinaSwiftPractice/Classes/View/Compose/Controller/JQPictureController.swift | 1 | 5588 | //
// JQPictureController.swift
// SinaSwiftPractice
//
// Created by maoge on 16/11/22.
// Copyright © 2016年 maoge. All rights reserved.
//
import UIKit
import SVProgressHUD
private let maxImageCount = 3
let selectCellMargin: CGFloat = 4
let colCount = 3
let itemW = (ScreenWidth - (CGFloat(colCount) + 1) * selectCellMargin) / CGFloat(colCount)
private let reuseIdentifier = "Cell"
class JQPictureController: UICollectionViewController {
var images: [UIImage] = [UIImage]()
override func viewDidLoad() {
super.viewDidLoad()
// Register cell classes
self.collectionView!.register(JQPictureSelCell.self, forCellWithReuseIdentifier: reuseIdentifier)
}
override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
let imageCount = images.count
let count = (imageCount == maxImageCount) ? (imageCount + 0) : (imageCount + 1)
return count
}
override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! JQPictureSelCell
cell.backgroundColor = UIColor.randomColor()
if indexPath.item == images.count {
cell.image = nil
}else {
cell.image = self.images[indexPath.item]
}
cell.delegate = self
return cell
}
}
@objc protocol JQPictureSelCellDelegate: NSObjectProtocol {
@objc optional func userWillAddPic()
@objc optional func userWllRemovePic(cell: JQPictureSelCell)
}
class JQPictureSelCell : UICollectionViewCell {
//图片
var image: UIImage? {
didSet {
addBtn.setImage(image, for: .normal)
//设置删除按钮的隐藏与显示
removeBtn.isHidden = image == nil
//遇到透明视图时, 需要将addBtn背景图片设置nil
let backImage: UIImage? = (image == nil ? #imageLiteral(resourceName: "compose_pic_add") : nil)
addBtn.setBackgroundImage(backImage, for: .normal)
}
}
//声明delegate
weak var delegate: JQPictureSelCellDelegate?
override init(frame: CGRect) {
super.init(frame: frame)
self.setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
private func setupUI() {
contentView.addSubview(addBtn)
contentView.addSubview(removeBtn)
addBtn.snp.makeConstraints { (make) in
make.edges.equalTo(self.contentView)
}
removeBtn.snp.makeConstraints { (make) in
make.top.right.equalTo(self.contentView)
}
}
//MARK: - 按钮点击
@objc private func btnAddClick() {
if self.image != nil {
return
}
self.delegate?.userWillAddPic?()
}
@objc private func btnRemoveClick() {
self.delegate?.userWllRemovePic?(cell: self)
}
private lazy var addBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add"), for: .normal)
btn.setBackgroundImage(#imageLiteral(resourceName: "compose_pic_add_highlighted"), for: .highlighted)
//设置视图显示模式
btn.imageView?.contentMode = .scaleAspectFill
btn.addTarget(self, action: #selector(btnAddClick), for: .touchUpInside)
return btn
}()
private lazy var removeBtn: UIButton = {
let btn = UIButton()
btn.setBackgroundImage(#imageLiteral(resourceName: "compose_photo_close"), for: .normal)
btn.addTarget(self, action: #selector(btnRemoveClick), for: .touchUpInside)
return btn
}()
}
extension JQPictureController: JQPictureSelCellDelegate {
func userWillAddPic() {
print("添加")
/*
//iOS 10 之前的判断方法
if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.photoLibrary) {
SVProgressHUD.showInfo(withStatus: "请您到->设置->新浪微博->开启相册访问权限")
return
}
*/
//进入照片选择器
let imagePicker = UIImagePickerController()
// imagePicker.allowsEditing = true
imagePicker.delegate = self
present(imagePicker, animated: true, completion: nil)
}
func userWllRemovePic(cell: JQPictureSelCell) {
let indexPath = collectionView?.indexPath(for: cell)
self.images.remove(at: indexPath!.item)
//删除时, 如果是最后一张, 则直接影藏
self.view?.isHidden = images.count == 0
self.collectionView?.reloadData()
}
}
extension JQPictureController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
let image = info[UIImagePickerControllerOriginalImage] as! UIImage
//数组记录图片
self.images.append(image.jq_scaleToWidth(width: 600))
self.collectionView?.reloadData()
dismiss(animated: true, completion: nil)
}
}
| mit | 65873cd1b25a4c4331cbb923a737f0bf | 27.21466 | 130 | 0.62108 | 4.953125 | false | false | false | false |
flypaper0/ethereum-wallet | ethereum-wallet/Classes/BusinessLayer/Services/WalletManager/WalletManager.swift | 1 | 3006 | // Copyright © 2018 Conicoin LLC. All rights reserved.
// Created by Artur Guseinov
import Foundation
class WalletManager: WalletManagerProtocol {
let keychain: Keychain
let walletDataStoreService: WalletDataStoreServiceProtocol
let keystoreService: KeystoreServiceProtocol
let mnemonicService: MnemonicServiceProtocol
init(keyhcain: Keychain,
walletDataStoreService: WalletDataStoreServiceProtocol,
keystoreService: KeystoreServiceProtocol,
mnemonicService: MnemonicServiceProtocol) {
self.walletDataStoreService = walletDataStoreService
self.keystoreService = keystoreService
self.mnemonicService = mnemonicService
self.keychain = keyhcain
}
func createWallet(passphrase: String) throws {
let mnemonic = mnemonicService.create(strength: .normal, language: .english)
try importWallet(mnemonic: mnemonic, passphrase: passphrase)
}
func importWallet(jsonKey: Data, passphrase: String) throws {
let gethAccount = try keystoreService.restoreAccount(with: jsonKey, passphrase: passphrase)
let keyObject = try JSONDecoder().decode(Key.self, from: jsonKey)
let privateKey = try keyObject.decrypt(password: passphrase)
let address = gethAccount.getAddress().getHex()!
let account = Account(type: .privateKey, address: address, key: privateKey.hex())
keychain.accounts = [account]
keychain.passphrase = passphrase
commonWalletInitialization(address: address)
}
func importWallet(privateKey: Data, passphrase: String) throws {
let gethAccount = try keystoreService.restoreAccount(withECDSA: privateKey, passphrase: passphrase)
let address = gethAccount.getAddress().getHex()!
let account = Account(type: .privateKey, address: address, key: privateKey.hex())
keychain.accounts = [account]
keychain.passphrase = passphrase
commonWalletInitialization(address: address)
}
func importWallet(mnemonic: [String], passphrase: String) throws {
let seed = try mnemonicService.createSeed(mnemonic: mnemonic, withPassphrase: "")
let chain = Chain.mainnet
let masterPrivateKey = HDPrivateKey(seed: seed, network: chain)
let privateKey = try masterPrivateKey
.derived(at: 44, hardens: true)
.derived(at: chain.bip44CoinType, hardens: true)
.derived(at: 0, hardens: true)
.derived(at: 0)
.derived(at: 0).privateKey()
let gethAccount = try keystoreService.restoreAccount(withECDSA: privateKey.raw, passphrase: passphrase)
let address = gethAccount.getAddress().getHex()!
let account = Account(type: .mnemonic, address: address, key: mnemonic.joined(separator: " "))
keychain.accounts = [account]
keychain.passphrase = passphrase
commonWalletInitialization(address: address)
}
// MARK: - Privates
private func commonWalletInitialization(address: String) {
walletDataStoreService.createWallet(address: address)
Defaults.walletCreated = true
}
}
| gpl-3.0 | bb08ff16f35c052c8186bc2aee088c49 | 35.646341 | 107 | 0.732113 | 4.769841 | false | false | false | false |
RobinRH/family-history-booklet | FamilyTree.swift | 1 | 3247 | //
// FamilyTree.swift
// Copyright (c) 2017 Robin Reynolds. All rights reserved.
//
import Foundation
import UIKit
enum FamilyColor : Int, Codable {
case me, parents, grandParents, greatGrandParents
func getUIColor() -> UIColor {
switch (self) {
case .me : return UIColor(red: 45/255, green: 208/255, blue: 0/255, alpha: 1.0)
case .parents : return UIColor(red: 106/255, green: 148/255, blue: 212/255, alpha: 1.0)
case .grandParents : return UIColor(red: 255/255, green: 203/255, blue: 115/255, alpha: 1.0)
case .greatGrandParents : return UIColor(red: 250/255, green: 112/255, blue: 128/255, alpha: 1.0)
}
}
}
//class FamilyTreeNode {
// var child : Person? = nil
// var mother : Person? = nil
// var father : Person? = nil
//}
//
//class FamilyTreeConnected {
//
// init(data : String) {
//
// }
//
//}
class FamilyTree : Codable {
var me = Person()
var parents = Family(name: "Parents", friendly1: "My Parents", friendly2: "", color: .parents)
var grandParentsFather = Family(name: "GrandParentsFathersSide", friendly1: "My Grandparents", friendly2: "Father's Side", color: .grandParents)
var grandParentsMother = Family(name: "GrandParentsMothersSide", friendly1: "My Grandparents", friendly2: "Mother's Side", color: .grandParents)
var greatGrandParentsFatherFather = Family(name: "GreatGrandParentsFatherFather", friendly1: "My Great-Grandparents", friendly2: "Father's Father's Side", color: .greatGrandParents)
var greatGrandParentsFatherMother = Family(name: "GreatGrandParentsFatherMother", friendly1: "My Great-Grandparents", friendly2: "Father's Mothers's Side", color: .greatGrandParents)
var greatGrandParentsMotherFather = Family(name: "GreatGrandParentsMotherFather", friendly1: "My Great-Grandparents", friendly2: "Mother's Father's Side", color: .greatGrandParents)
var greatGrandParentsMotherMother = Family(name: "GreatGrandParentsMotherMother", friendly1: "My Great-Grandparents", friendly2: "Mother's Mother's Side", color: .greatGrandParents)
init() {
}
}
class Event : Codable {
var date = ""
var place = ""
}
class Marriage : Codable {
var wedding = Event()
var husband = Person()
var wife = Person()
init() {
}
}
//extension UIColor : Codable {
// public convenience init(from decoder: Decoder) throws {
// }
//
// public func encode(to encoder: Encoder) throws {
//
// }
//
//}
class Family : Codable {
var father = Person()
var mother = Person()
var marriage = Marriage()
var children = [Person]()
var familyName = ""
var friendlyName1 = ""
var friendlyName2 = ""
var colorComps : [CGFloat]? = CGColor(colorLiteralRed: 0.5, green: 0.5, blue: 0.5, alpha: 1.0).components
var generationColor : FamilyColor = FamilyColor.me
var color : UIColor {
return generationColor.getUIColor()
}
init(name: String, friendly1 : String, friendly2 : String, color : FamilyColor) {
familyName = name
friendlyName1 = friendly1
friendlyName2 = friendly2
generationColor = color
}
init() {
}
}
| apache-2.0 | 9307b64d350c5700e3e54cc534e80e85 | 27.991071 | 186 | 0.649215 | 3.775581 | false | false | false | false |
Allow2CEO/browser-ios | ClientTests/TabManagerTests.swift | 3 | 2988 | /* 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/. */
@testable import Client
import Shared
import Storage
import UIKit
import WebKit
import Deferred
import XCTest
public class TabManagerMockProfile: MockProfile {
override func storeTabs(tabs: [RemoteTab]) -> Deferred<Maybe<Int>> {
return self.remoteClientsAndTabs.insertOrUpdateTabs(tabs)
}
}
class TabManagerTests: XCTestCase {
override func setUp() {
super.setUp()
}
override func tearDown() {
super.tearDown()
}
func testTabManagerStoresChangesInDB() {
let profile = TabManagerMockProfile()
let manager = TabManager(defaultNewTabRequest: NSURLRequest(URL: NSURL(fileURLWithPath: "http://localhost")), prefs: profile.prefs, imageStore: nil)
let configuration = WKWebViewConfiguration()
configuration.processPool = WKProcessPool()
profile.remoteClientsAndTabs.wipeTabs()
// Make sure we start with no remote tabs.
var remoteTabs: [RemoteTab]?
waitForCondition {
remoteTabs = profile.remoteClientsAndTabs.getTabsForClientWithGUID(nil).value.successValue
return remoteTabs?.count == 0
}
XCTAssertEqual(remoteTabs?.count, 0)
// test that non-private tabs are saved to the db
// add some non-private tabs to the tab manager
for _ in 0..<3 {
let tab = Browser(configuration: configuration)
manager.configureTab(tab, request: NSURLRequest(URL: NSURL(string: "http://yahoo.com")!), flushToDisk: false, zombie: false)
}
manager.storeChanges()
// now test that the database contains 3 tabs
waitForCondition {
remoteTabs = profile.remoteClientsAndTabs.getTabsForClientWithGUID(nil).value.successValue
return remoteTabs?.count == 3
}
XCTAssertEqual(remoteTabs?.count, 3)
// test that private tabs are not saved to the DB
// private tabs are only available in iOS9 so don't execute this part of the test if we're testing against < iOS9
if #available(iOS 9, *) {
// create some private tabs
for _ in 0..<3 {
let tab = Browser(configuration: configuration, isPrivate: true)
manager.configureTab(tab, request: NSURLRequest(URL: NSURL(string: "http://yahoo.com")!), flushToDisk: false, zombie: false)
}
manager.storeChanges()
// We can't use waitForCondition here since we're testing a non-change.
wait(ProfileRemoteTabsSyncDelay * 2)
// now test that the database still contains only 3 tabs
remoteTabs = profile.remoteClientsAndTabs.getTabsForClientWithGUID(nil).value.successValue
XCTAssertEqual(remoteTabs?.count, 3)
}
}
}
| mpl-2.0 | ada80966e860b32f37470a01fc602617 | 35 | 156 | 0.655622 | 4.971714 | false | true | false | false |
BugMomon/weibo | NiceWB/NiceWB/Classes/Home(主页)/TitleViewController/PresentationViewController.swift | 1 | 998 | //
// PresentationView.swift
// NiceWB
//
// Created by HongWei on 2017/3/27.
// Copyright © 2017年 HongWei. All rights reserved.
//弹出视图
import UIKit
class PresentationViewController: UIPresentationController {
lazy var container : UIView = UIView()
var PresentationViewFrame : CGRect = .zero
override func containerViewWillLayoutSubviews() {
super.containerViewWillLayoutSubviews()
presentedView?.frame = PresentationViewFrame
containerView?.backgroundColor = UIColor(white: 0.5, alpha: 0.5)
setupContainerView()
}
func setupContainerView(){
containerView?.insertSubview(container, at: 0)
container.frame = containerView!.bounds
let tap = UITapGestureRecognizer(target: self, action:#selector(dismissTap))
container.addGestureRecognizer(tap)
}
func dismissTap(){
presentedViewController.dismiss(animated: true, completion: nil)
}
}
| apache-2.0 | dfd22e6e39807918478c0809b798aee2 | 24.973684 | 84 | 0.671733 | 5.11399 | false | false | false | false |
LoveAlwaysYoung/EnjoyUniversity | EnjoyUniversity/EnjoyUniversity/Classes/ViewModel/UserInfoListViewModel.swift | 1 | 7319 | //
// UserInfoListViewModel.swift
// EnjoyUniversity
//
// Created by lip on 17/4/10.
// Copyright © 2017年 lip. All rights reserved.
//
import Foundation
import YYModel
class UserInfoListViewModel{
/// 活动参与者
lazy var activityParticipatorList = [UserinfoViewModel]()
/// 完成签到的活动参与者
lazy var finishedRegisterParticipatorList = [UserinfoViewModel]()
/// 未完成签到的互动参与者
lazy var waitingRegisterParticipatorList = [UserinfoViewModel]()
/// 社团通讯录(权限表和用户表联合查询结果)
lazy var communityContactsList = [UserinfoViewModel]()
/// 社团成员列表
lazy var communityMemberList = [UserinfoViewModel]()
/// 搜索用户列表
lazy var searchList = [UserinfoViewModel]()
/// 申请社团成员列表
lazy var applycmMemberList = [UserinfoViewModel]()
/// 加载活动参与者信息
///
/// - Parameters:
/// - avid: 活动 ID
/// - completion: 完成回调
func loadActivityMemberInfoList(avid:Int,completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getActivityParticipators(avid: avid) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json,
let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
completion(true,false)
return
}
self.activityParticipatorList.removeAll()
for model in modelarray{
self.activityParticipatorList.append(UserinfoViewModel(model: model))
}
completion(true,true)
}
}
/// 加载未完成签到者信息
///
/// - Parameters:
/// - avid: 活动ID
/// - completion: 完成回调
func loadWaitingRegisterMemberInfoList(avid:Int,completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getActivityParticipators(avid: avid, choice: -1) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json,
let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
self.waitingRegisterParticipatorList.removeAll()
completion(true,false)
return
}
self.waitingRegisterParticipatorList.removeAll()
for model in modelarray{
self.waitingRegisterParticipatorList.append(UserinfoViewModel(model: model))
}
completion(true,true)
}
}
/// 加载社团通讯录
///
/// - Parameters:
/// - cmid: 社团 ID
/// - completion: 完成回调
func loadCommunityContactsInfoList(cmid:Int,completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getCommunityContactsByID(cmid: cmid) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json,let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
completion(true,false)
return
}
self.communityContactsList.removeAll()
for model in modelarray{
// 去除正在审核的人
if model.position < 0{
continue
}
self.communityContactsList.append(UserinfoViewModel(model: model))
}
self.communityContactsList.sort(by: { (x, y) -> Bool in
return x.model?.position ?? 0 > y.model?.position ?? 0
})
completion(true,true)
}
}
/// 加载社团成员列表
///
/// - Parameters:
/// - cmid: 社团 ID
/// - completion: 完成回调
func loadCommunityMemberList(cmid:Int,completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getCommunityMemberInfoList(cmid: cmid) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json ,let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
completion(true,false)
return
}
self.communityMemberList.removeAll()
for model in modelarray{
self.communityMemberList.append(UserinfoViewModel(model: model))
}
completion(true,true)
}
}
/// 搜索用户列表
///
/// - Parameters:
/// - keyword: 关键字
/// - page: 页
/// - rows: 每页行数
/// - completion: 完成回调
func loadSearchedUserList(keyword:String,isPullUp:Bool,completion:@escaping (Bool,Bool)->()){
var page = 1
let rows = EUREQUESTCOUNT
if isPullUp {
if searchList.count >= rows {
// swift 整数相处直接舍弃余数
page = searchList.count / rows + 1
}
}
EUNetworkManager.shared.searchUser(keyword: keyword, page: page, rows: rows) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json ,let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
completion(true,false)
return
}
var temp = [UserinfoViewModel]()
for model in modelarray{
temp.append(UserinfoViewModel(model: model))
}
if isPullUp{
self.searchList = self.searchList + temp
}else{
self.searchList = temp
}
completion(true,true)
}
}
/// 加载申请参加社团的成员列表
///
/// - Parameters:
/// - cmid: 社团 ID
/// - completion: 完成回到
func loadApplyCommunityUserList(cmid:Int,completion:@escaping (Bool,Bool)->()){
EUNetworkManager.shared.getCommunityContactsByID(cmid: cmid) { (isSuccess, json) in
if !isSuccess{
completion(false,false)
return
}
guard let json = json,let modelarray = NSArray.yy_modelArray(with: UserInfo.self, json: json) as? [UserInfo] else{
completion(true,false)
return
}
self.applycmMemberList.removeAll()
for model in modelarray{
// 去除正在审核的人
if model.position > 0{
continue
}
self.applycmMemberList.append(UserinfoViewModel(model: model))
}
completion(true,true)
}
}
}
| mit | fc9f4da43ba40959ff19672051d96e71 | 29.871111 | 127 | 0.521163 | 4.957887 | false | false | false | false |
wordpress-mobile/WordPress-iOS | WordPress/Classes/ViewRelated/Reader/Detail/WebView/ReaderCSS.swift | 1 | 2260 | import Foundation
/// A struct that returns the Reader CSS URL
/// If you need to fix an issue in the CSS, see pbArwn-GU-p2
///
struct ReaderCSS {
private let store: KeyValueDatabase
private let now: Int
private let isInternetReachable: () -> Bool
private let expirationDays: Int = 5
private var expirationDaysInSeconds: Int {
return expirationDays * 60 * 60 * 24
}
static let updatedKey = "ReaderCSSLastUpdated"
/// Returns a custom Reader CSS URL
/// This value can be changed under Settings > Debug
///
var customAddress: String? {
get {
return store.object(forKey: "reader-css-url") as? String
}
set {
store.set(newValue, forKey: "reader-css-url")
}
}
/// Returns the Reader CSS appending a timestamp
/// We force it to update based on the `expirationDays` property
///
var address: String {
// Always returns a fresh CSS if the flag is enabled
guard !FeatureFlag.readerCSS.enabled else {
return url(appendingTimestamp: now)
}
guard let lastUpdated = store.object(forKey: type(of: self).updatedKey) as? Int,
(now - lastUpdated < expirationDaysInSeconds
|| !isInternetReachable()) else {
saveCurrentDate()
return url(appendingTimestamp: now)
}
return url(appendingTimestamp: lastUpdated)
}
init(now: Int = Int(Date().timeIntervalSince1970),
store: KeyValueDatabase = UserPersistentStoreFactory.instance(),
isInternetReachable: @escaping () -> Bool = ReachabilityUtils.isInternetReachable) {
self.store = store
self.now = now
self.isInternetReachable = isInternetReachable
}
private func saveCurrentDate() {
store.set(now, forKey: type(of: self).updatedKey)
}
private func url(appendingTimestamp appending: Int) -> String {
guard let customURL = customAddress, !customURL.isEmpty else {
let timestamp = String(appending)
return "https://wordpress.com/calypso/reader-mobile.css?\(timestamp)"
}
let timestamp = String(appending)
return "\(customURL)?\(timestamp)"
}
}
| gpl-2.0 | be57c959025a6ce28aadd0577f020a1c | 29.958904 | 93 | 0.627876 | 4.728033 | false | false | false | false |
lemberg/connfa-ios | Connfa/Classes/EventTableView/EventsTableView.swift | 1 | 1510 | //
// EventsTableView.swift
// Connfa
//
// Created by Marian Fedyk on 9/18/18.
// Copyright © 2018 Lemberg Solution. All rights reserved.
//
import UIKit
class EventsTableView: UITableView {
static let programListHeaderidentifier = "ProgramListHeader"
static let programListCellIdentifier = "ProgramListCell"
private var suplementaryView: UIImageView {
let result = UIImageView(frame: CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 70))
result.image = #imageLiteral(resourceName: "ic-neutral-logo")
result.contentMode = .center
return result
}
override init(frame: CGRect, style: UITableView.Style){
super.init(frame: frame, style: style)
setup()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
setup()
}
private func setup() {
register(UINib(nibName: EventsTableView.programListHeaderidentifier, bundle: nil), forHeaderFooterViewReuseIdentifier: EventsTableView.programListHeaderidentifier)
register(UINib(nibName: EventsTableView.programListCellIdentifier, bundle: nil), forCellReuseIdentifier: EventsTableView.programListCellIdentifier)
estimatedRowHeight = 120
rowHeight = UITableView.automaticDimension
backgroundView = nil
backgroundColor = UIColor.clear
showsVerticalScrollIndicator = true
tableHeaderView = suplementaryView
tableFooterView = suplementaryView
if #available(iOS 11.0, *) {
contentInsetAdjustmentBehavior = .never
}
}
}
| apache-2.0 | 3cf59405afd9f9c07323c43bdd730a29 | 31.804348 | 167 | 0.740225 | 4.671827 | false | false | false | false |
kickstarter/ios-oss | Kickstarter-iOS/Features/ProjectPage/Views/Cells/ProjectRisksCell.swift | 1 | 2309 | import KsApi
import Library
import Prelude
import UIKit
final class ProjectRisksCell: UITableViewCell, ValueCell {
// MARK: - Properties
private let viewModel = ProjectRisksCellViewModel()
private lazy var descriptionLabel: UILabel = {
UILabel(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
private lazy var rootStackView = {
UIStackView(frame: .zero)
|> \.translatesAutoresizingMaskIntoConstraints .~ false
}()
// MARK: - Lifecycle
override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.bindStyles()
self.configureViews()
self.bindViewModel()
}
required init?(coder _: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Bindings
override func bindViewModel() {
super.bindViewModel()
self.descriptionLabel.rac.text = self.viewModel.outputs.descriptionLabelText
}
override func bindStyles() {
super.bindStyles()
_ = self
|> baseTableViewCellStyle()
|> \.separatorInset .~ .init(leftRight: Styles.projectPageLeftRightInset)
_ = self.contentView
|> \.layoutMargins .~
.init(topBottom: Styles.grid(2), leftRight: Styles.projectPageLeftRightInset)
_ = self.descriptionLabel
|> descriptionLabelStyle
_ = self.rootStackView
|> rootStackViewStyle
}
// MARK: - Configuration
func configureWith(value: String) {
self.viewModel.inputs.configureWith(value: value)
}
private func configureViews() {
_ = (self.rootStackView, self.contentView)
|> ksr_addSubviewToParent()
|> ksr_constrainViewToMarginsInParent()
_ = ([self.descriptionLabel], self.rootStackView)
|> ksr_addArrangedSubviewsToStackView()
}
}
// MARK: - Styles
private let descriptionLabelStyle: LabelStyle = { label in
label
|> \.adjustsFontForContentSizeCategory .~ true
|> \.font .~ UIFont.ksr_body()
|> \.numberOfLines .~ 0
|> \.textColor .~ .ksr_support_700
}
private let rootStackViewStyle: StackViewStyle = { stackView in
stackView
|> \.axis .~ .vertical
|> \.insetsLayoutMarginsFromSafeArea .~ false
|> \.isLayoutMarginsRelativeArrangement .~ true
|> \.spacing .~ Styles.grid(3)
}
| apache-2.0 | 58c55d0f154a2980670d9e16b3fa3fd5 | 23.827957 | 83 | 0.685578 | 4.954936 | false | true | false | false |
srosskopf/DMpruefungen | DMpruefer/SRSettingsVC.swift | 1 | 2470 | //
// SettingsViewController.swift
// DMpruefer
//
// Created by Sebastian Roßkopf on 27.02.16.
// Copyright © 2016 ross. All rights reserved.
//
import UIKit
class SRSettingsVC: UIViewController, UITextFieldDelegate {
@IBOutlet weak var nameTextField: UITextField!
@IBOutlet weak var saveButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
let swipeGestureRecognizer = UISwipeGestureRecognizer(target: self, action: #selector(SRSettingsVC.goToStart(_:)))
swipeGestureRecognizer.direction = UISwipeGestureRecognizerDirection.Up
self.view.addGestureRecognizer(swipeGestureRecognizer)
saveButton.layer.cornerRadius = saveButton.frame.size.height/2
nameTextField.delegate = self
nameTextField.text = SRCoreDataHelper.getNameOfStudent()
let attributes = [NSForegroundColorAttributeName:UIColor(red: 1, green: 1, blue: 1, alpha: 0.6)]
let placeholderString = NSMutableAttributedString(string: "Dein Name", attributes: attributes)
nameTextField.attributedPlaceholder = placeholderString
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func preferredStatusBarStyle() -> UIStatusBarStyle {
return UIStatusBarStyle.LightContent
}
@IBAction func saveSettings(sender: UIButton) {
if nameTextField.text?.characters.count > 0 {
if let name = nameTextField.text {
SRCoreDataHelper.updateStudentName(name)
nameTextField.resignFirstResponder()
}
}
}
func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
func goToStart(sender: UISwipeGestureRecognizer) {
performSegueWithIdentifier("settingsToStart", sender: sender)
}
}
| mit | ec4e7342a601c97cacc901a9bfaf3cac | 26.422222 | 122 | 0.639789 | 5.990291 | false | false | false | false |
zom/Zom-iOS | Zom/Zom/Classes/View Controllers/ZomPickStickerViewController.swift | 1 | 3028 | //
// ZomPickStickerViewController.swift
// Zom
//
// Created by N-Pex on 2015-11-13.
//
//
import UIKit
import ChatSecureCore
public protocol ZomPickStickerViewControllerDelegate {
func didPickSticker(_ sticker:String, inPack: String)
}
open class ZomPickStickerViewController: UICollectionViewController {
open var stickerPackFileName: String = ""
open var stickerPack: String = ""
private var stickers: [String] = []
private var stickerPaths: [String] = []
private var selectedSticker:String = ""
fileprivate var assetGridThumbnailSize:CGSize = CGSize()
open override func viewDidLoad() {
super.viewDidLoad()
let docsPath = Bundle.main.resourcePath! + "/Stickers/" + stickerPackFileName
let fileManager = FileManager.default
do {
let stickerFiles = try fileManager.contentsOfDirectory(atPath: docsPath)
for item in stickerFiles {
// Hide "old" stickers with an starting "_"
if !item.hasPrefix("_") {
stickers.append((item as NSString).deletingPathExtension)
stickerPaths.append(docsPath + "/" + item)
}
}
} catch {
print(error)
}
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// Determine the size of the thumbnails to request from the PHCachingImageManager
let scale:CGFloat = UIScreen.main.scale
let cellSize:CGSize = (self.collectionViewLayout as! UICollectionViewFlowLayout).itemSize;
assetGridThumbnailSize = CGSize(width: cellSize.width * scale, height: cellSize.height * scale);
}
// Mark - UICollectionViewDataSource
open override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return stickerPaths.count
}
open override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell:ZomPickStickerCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! ZomPickStickerCell
cell.imageView.image = UIImage(contentsOfFile: stickerPaths[indexPath.item])
return cell
}
open override func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
selectedSticker = stickers[indexPath.item]
self.performSegue(withIdentifier: "unwindPickStickerSegue", sender: self)
}
open override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if (segue.destination is ZomPickStickerViewControllerDelegate) {
let vc:ZomPickStickerViewControllerDelegate = segue.destination as! ZomPickStickerViewControllerDelegate
if (!selectedSticker.isEmpty) {
vc.didPickSticker(selectedSticker, inPack: stickerPack)
}
}
}
}
| mpl-2.0 | 7346739bb9b44f336b75755f8038c356 | 36.382716 | 140 | 0.67041 | 5.555963 | false | false | false | false |
lorentey/Attabench | BenchmarkCharts/NSImage Export.swift | 2 | 841 | // Copyright © 2017 Károly Lőrentey.
// This file is part of Attabench: https://github.com/attaswift/Attabench
// For licensing information, see the file LICENSE.md in the Git repository above.
import Cocoa
import Quartz
extension NSImage {
public func pngData(scale: Int = 4) -> Data {
let cgimage = self.cgImage(forProposedRect: nil, context: nil, hints: [.CTM: NSAffineTransform(transform: AffineTransform.init(scale: CGFloat(scale)))])!
let rep = NSBitmapImageRep(cgImage: cgimage)
rep.size = self.size
let data = rep.representation(using: .png, properties: [:])
return data!
}
public func pdfData() -> Data {
let document = PDFDocument()
let page = PDFPage(image: self)!
document.insert(page, at: 0)
return document.dataRepresentation()!
}
}
| mit | 73de140604b97fb17fbe9b11ca4dbcae | 35.434783 | 161 | 0.667064 | 4.341969 | false | false | false | false |
marinehero/LeetCode-Solutions-in-Swift | Solutions/Solutions/Hard/Hard_068_Text_Justification.swift | 4 | 2385 | /*
https://leetcode.com/problems/text-justification/
#68 Text Justification
Given an array of words and a length L, format the text such that each line has exactly L characters and is fully (left and right) justified.
You should pack your words in a greedy approach; that is, pack as many words as you can in each line. Pad extra spaces ' ' when necessary so that each line has exactly L characters.
Extra spaces between words should be distributed as evenly as possible. If the number of spaces on a line do not divide evenly between words, the empty slots on the left will be assigned more spaces than the slots on the right.
For the last line of text, it should be left justified and no extra space is inserted between words.
For example,
words: ["This", "is", "an", "example", "of", "text", "justification."]
L: 16.
Return the formatted lines as:
[
"This is an",
"example of text",
"justification. "
]
Note: Each word is guaranteed not to exceed L in length.
click to show corner cases.
Corner Cases:
A line other than the last line might contain only one word. What should you do in this case?
In this case, that line should be left-justified.
Inspired by @qddpx at https://leetcode.com/discuss/13610/share-my-concise-c-solution-less-than-20-lines
*/
import Foundation
struct Hard_068_Text_Justification {
static func fullJustify(words: [String], maxWidth: Int) -> [String] {
var res: [String] = []
for var i = 0, k: Int, l: Int; i < words.count; i += k {
for k = 0, l = 0; i + k < words.count && l + words[i+k].characters.count <= maxWidth - k; k++ {
l += words[i+k].characters.count
}
var tmp = words[i]
for var j = 0; j < k - 1; j++ {
if i + k >= words.count {
tmp += " "
} else {
let tmpLen = (maxWidth - l) / (k - 1) + Int((j < (maxWidth - l) % (k - 1)))
let tmpArr: [Character] = Array(count: tmpLen, repeatedValue: " ")
tmp += String(tmpArr)
}
tmp += words[i+j+1]
}
let charArrLen = maxWidth - tmp.characters.count
let charArr: [Character] = Array(count: charArrLen, repeatedValue: " ")
tmp += String(charArr)
res.append(tmp)
}
return res
}
} | mit | 4a0cc00b9503b8bbd42705718183e64e | 36.28125 | 227 | 0.607547 | 3.75 | false | false | false | false |
piscis/XCodeAdventuresSwift | TodoApp/TodoApp/MasterTableViewController.swift | 1 | 4241 | //
// MasterTableViewController.swift
// TodoApp
//
// Created by Alexander Pirsig on 18.07.14.
// Copyright (c) 2014 IworxIT. All rights reserved.
//
import UIKit
class MasterTableViewController: UITableViewController {
var toDoItems: NSMutableArray = NSMutableArray()
override func viewDidAppear(animated: Bool) {
var userDefaults:NSUserDefaults = NSUserDefaults.standardUserDefaults()
var itemListFromUserDefaults:NSMutableArray? = userDefaults.objectForKey("itemList") as? NSMutableArray
if(itemListFromUserDefaults) {
toDoItems = itemListFromUserDefaults!
}
self.tableView.reloadData()
}
override func viewDidLoad() {
super.viewDidLoad()
// Uncomment the following line to preserve selection between presentations
// self.clearsSelectionOnViewWillAppear = false
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem()
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// #pragma mark - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
// #warning Potentially incomplete method implementation.
// Return the number of sections.
return 1
}
override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete method implementation.
// Return the number of rows in the section.
return toDoItems.count
}
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
let cell = tableView!.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath) as UITableViewCell
var toDoItem:NSDictionary = toDoItems.objectAtIndex(indexPath!.row) as NSDictionary
cell.textLabel.text = toDoItem.objectForKey("itemTitle") as String
return cell
}
/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the specified item to be editable.
return true
}
*/
/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
if editingStyle == .Delete {
// Delete the row from the data source
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
} else if editingStyle == .Insert {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}
}
*/
/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {
}
*/
/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
// Return NO if you do not want the item to be re-orderable.
return true
}
*/
// #pragma mark - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue && segue!.identifier == "showDetail") {
var selectedIndexPath:NSIndexPath = self.tableView.indexPathForSelectedRow()
var detailViewController:DetailViewController = segue!.destinationViewController as DetailViewController
detailViewController.toDoData = toDoItems.objectAtIndex(selectedIndexPath.row) as NSDictionary
}
}
}
| unlicense | 6e8133f517214d2ba753aace64d62eaa | 35.247863 | 159 | 0.681679 | 5.857735 | false | false | false | false |
adamyanalunas/Font | Pod/Classes/Font.swift | 1 | 2800 | //
// Font.swift
// Pods
//
// Created by Adam Yanalunas on 10/2/15.
//
//
import Foundation
public enum FontStyle:String {
case none, italic
}
public enum FontWeight:String {
case ultralight, thin, light, regular, medium, semibold, bold, heavy, black
public init(type:String) {
self = FontWeight(rawValue: type)!
}
}
public struct Font: Equatable {
public typealias FontScaler = (_ sizeClass:UIContentSizeCategory) -> CGFloat
public let fontName:String
public let size:CGFloat
public let weight:FontWeight
public let style:FontStyle
public init(fontName:String, size:CGFloat, weight:FontWeight = .medium, style:FontStyle = .none) {
self.fontName = fontName
self.size = size
self.weight = weight
self.style = style
}
fileprivate func dynamicSize(_ sizeClass:UIContentSizeCategory) -> CGFloat {
let adjustedSize:CGFloat
switch sizeClass {
case UIContentSizeCategory.extraSmall:
adjustedSize = floor(size / 1.6) //10
case UIContentSizeCategory.small:
adjustedSize = floor(size / 1.4) //11
case UIContentSizeCategory.medium:
adjustedSize = floor(size / 1.2) //13
case UIContentSizeCategory.large:
adjustedSize = size //16
case UIContentSizeCategory.extraLarge:
adjustedSize = floor(size * 1.15) //18
case UIContentSizeCategory.extraExtraLarge:
adjustedSize = floor(size * 1.25) //20
case UIContentSizeCategory.extraExtraExtraLarge:
adjustedSize = floor(size * 1.4) //22
case UIContentSizeCategory.accessibilityMedium:
adjustedSize = floor(size * 1.5) //24
case UIContentSizeCategory.accessibilityLarge:
adjustedSize = floor(size * 1.65) //26
case UIContentSizeCategory.accessibilityExtraLarge:
adjustedSize = floor(size * 1.75) //28
case UIContentSizeCategory.accessibilityExtraExtraLarge:
adjustedSize = floor(size * 1.9) //30
case UIContentSizeCategory.accessibilityExtraExtraExtraLarge:
adjustedSize = floor(size * 2) //32
default:
adjustedSize = 16
}
return adjustedSize
}
public func generate(_ sizeClass:UIContentSizeCategory = UIApplication.shared.preferredContentSizeCategory, resizer:FontScaler? = nil) -> UIFont? {
let adjustedSize = resizer != nil ? resizer!(sizeClass) : dynamicSize(sizeClass)
return UIFont(name: fontName, size: adjustedSize)
}
}
public func ==(lhs:Font, rhs:Font) -> Bool {
return lhs.fontName == rhs.fontName
&& lhs.size == rhs.size
&& lhs.weight == rhs.weight
&& lhs.style == rhs.style
}
| mit | 40bf6c5ce6b9b064c6f4a06b560415ea | 32.73494 | 151 | 0.641071 | 4.852686 | false | false | false | false |
mike-levenick/mut | The MUT/APIAccess/APIAccess.swift | 1 | 1904 | //
// APIAccess.swift
// testProj
//
// Created by Andrew Pirkl on 11/24/19.
// Copyright © 2019 PIrklator. All rights reserved.
//
import Foundation
/**
Run operations against an API
*/
public class APIAccess {
/**
Add and run a datatask by a URLRequest with the SessionHandler singleton's URLSession
*/
func runCall(mySession: URLSession, myRequest : URLRequest,completion: @escaping (Data?,URLResponse?,Error?) -> Void)
{
mySession.dataTask(with: myRequest)
{ (data: Data?, response: URLResponse?, error: Error?) in
return completion(data,response,error)
}.resume()
}
/**
Handle result of a dataTask
*/
public func parseCall(data: Data?, response: URLResponse?, error: Error?) -> Void
{
if let error = error {
//print("got an error")
//print(error)
return
}
guard let response = response else {
//print("empty response")
return
}
guard let data = data else {
//print("empty data")
return
}
// check for response errors, and handle data
//print("We got some data up in here")
let responseData = String(data: data, encoding: String.Encoding.utf8)
//print((String(describing: responseData)))
}
public func testCall()
{
let creds = String("user:pass").toBase64()
var request = URLRequest(url: URL(string: "https://tryitout.jamfcloud.com/JSSResource/computers")!)
request.httpMethod = HTTPMethod.get.rawValue
request.addValue("Basic \(creds)", forHTTPHeaderField: "Authorization")
runCall(mySession: SessionHandler.SharedSessionHandler.mySession,myRequest: request)
{data,response,error in self.parseCall(data: data,response: response,error: error)}
}
}
| mit | c2a52baf1810be1669cc4eca87eb321a | 30.196721 | 121 | 0.604834 | 4.364679 | false | false | false | false |
saagarjha/iina | iina/LanguageTokenField.swift | 1 | 3049 | //
// LanguageTokenField.swift
// iina
//
// Created by Collider LI on 12/4/2020.
// Copyright © 2020 lhc. All rights reserved.
//
import Cocoa
fileprivate class Token: NSObject {
var content: String
var code: String
init(_ content: String) {
self.content = content
self.code = ISO639Helper.descriptionRegex.captures(in: content)[at: 1] ?? content
}
}
class LanguageTokenField: NSTokenField {
private var layoutManager: NSLayoutManager?
override func awakeFromNib() {
super.awakeFromNib()
self.delegate = self
}
override var stringValue: String {
set {
self.objectValue = newValue.count == 0 ?
[] : newValue.components(separatedBy: ",").map(Token.init)
}
get {
return (objectValue as? NSArray)?.map({ val in
if let token = val as? Token {
return token.code
} else if let str = val as? String {
return str
}
return ""
}).joined(separator: ",") ?? ""
}
}
func controlTextDidChange(_ obj: Notification) {
guard let layoutManager = layoutManager else { return }
let attachmentChar = Character(UnicodeScalar(NSTextAttachment.character)!)
let finished = layoutManager.attributedString().string.split(separator: attachmentChar).count == 0
if finished, let target = target, let action = action {
target.performSelector(onMainThread: action, with: self, waitUntilDone: false)
}
}
override func textShouldBeginEditing(_ textObject: NSText) -> Bool {
if let view = textObject as? NSTextView {
layoutManager = view.layoutManager
}
return true
}
}
extension LanguageTokenField: NSTokenFieldDelegate {
func tokenField(_ tokenField: NSTokenField, styleForRepresentedObject representedObject: Any) -> NSTokenField.TokenStyle {
return .rounded
}
func tokenField(_ tokenField: NSTokenField, displayStringForRepresentedObject representedObject: Any) -> String? {
if let token = representedObject as? Token {
return token.code
} else {
return representedObject as? String
}
}
func tokenField(_ tokenField: NSTokenField, hasMenuForRepresentedObject representedObject: Any) -> Bool {
return false
}
func tokenField(_ tokenField: NSTokenField, completionsForSubstring substring: String, indexOfToken tokenIndex: Int, indexOfSelectedItem selectedIndex: UnsafeMutablePointer<Int>?) -> [Any]? {
let lowSubString = substring.lowercased()
let matches = ISO639Helper.languages.filter { lang in
return lang.name.contains { $0.lowercased().hasPrefix(lowSubString) }
}
return matches.map { $0.description }
}
func tokenField(_ tokenField: NSTokenField, editingStringForRepresentedObject representedObject: Any) -> String? {
if let token = representedObject as? Token {
return token.content
} else {
return representedObject as? String
}
}
func tokenField(_ tokenField: NSTokenField, representedObjectForEditing editingString: String) -> Any? {
return Token(editingString)
}
}
| gpl-3.0 | 1910c1cc130db366369d0d56ae9dfb2f | 29.787879 | 193 | 0.693898 | 4.718266 | false | false | false | false |
cotkjaer/Silverback | Silverback/Random.swift | 1 | 2834 | //
// Random.swift
// SilverbackFramework
//
// Created by Christian Otkjær on 20/04/15.
// Copyright (c) 2015 Christian Otkjær. All rights reserved.
//
import Foundation
import UIKit
public extension Int
{
/**
Random integer in the open range [_lower_;_upper_[, ie. an integer between lower (_inclusive_) and upper (_exclusive_)
NB! _lower_ **must** be less than _upper_
- parameter lower: lower limit - inclusive
- parameter upper: upper limit - exclusive
- returns: Random integer in the open range [_lower_;_upper_[
*/
static func random(lower lower: Int = min, upper: Int = max) -> Int
{
return Int(Int64.random(Int64(lower), upper: Int64(upper)))
}
}
/**
Arc Random for Double and Float
*/
public func arc4random <T: IntegerLiteralConvertible> (type: T.Type) -> T
{
var r: T = 0
arc4random_buf(&r, sizeof(T))
return r
}
public extension UInt64
{
static func random(lower: UInt64 = min, upper: UInt64 = max) -> UInt64
{
var m: UInt64
let u = upper - lower
var r = arc4random(UInt64)
if u > UInt64(Int64.max)
{
m = 1 + ~u
}
else
{
m = ((max - (u * 2)) + 1) % u
}
while r < m
{
r = arc4random(UInt64)
}
return (r % u) + lower
}
}
public extension Int64
{
static func random(lower: Int64 = min, upper: Int64 = max) -> Int64
{
let (s, overflow) = Int64.subtractWithOverflow(upper, lower)
let u = overflow ? UInt64.max - UInt64(~s) : UInt64(s)
let r = UInt64.random(upper: u)
if r > UInt64(Int64.max)
{
return Int64(r - (UInt64(~lower) + 1))
}
else
{
return Int64(r) + lower
}
}
}
public extension UInt32
{
static func random(lower: UInt32 = min, upper: UInt32 = max) -> UInt32
{
return arc4random_uniform(upper - lower) + lower
}
}
public extension Int32
{
static func random(lower: Int32 = min, upper: Int32 = max) -> Int32
{
let r = arc4random_uniform(UInt32(Int64(upper) - Int64(lower)))
return Int32(Int64(r) + Int64(lower))
}
}
public extension UInt
{
static func random(lower: UInt = min, upper: UInt = max) -> UInt
{
return UInt(UInt64.random(UInt64(lower), upper: UInt64(upper)))
}
}
public extension Double
{
/**
Create a random num Double
- parameter lower: number Double
- parameter upper: number Double
:return: random number Double
*/
public static func random(lower lower: Double, upper: Double) -> Double
{
let r = Double(arc4random(UInt64)) / Double(UInt64.max)
return (r * (upper - lower)) + lower
}
}
| mit | 8df758cd42c3e3244fccda97a90baf2c | 21.299213 | 122 | 0.564266 | 3.589354 | false | false | false | false |
SusanDoggie/Doggie | Sources/DoggieGraphics/SVGContext/SVGContext.swift | 1 | 72918 | //
// SVGContext.swift
//
// The MIT License
// Copyright (c) 2015 - 2022 Susan Cheng. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
private struct SVGContextStyles {
static let defaultShadowColor = AnyColor(colorSpace: .default, white: 0.0, opacity: 1.0 / 3.0)
var opacity: Double = 1
var transform: SDTransform = SDTransform.identity
var shadowColor: AnyColor = SVGContextStyles.defaultShadowColor
var shadowOffset: Size = Size()
var shadowBlur: Double = 0
var compositingMode: ColorCompositingMode = .default
var blendMode: ColorBlendMode = .default
var renderingIntent: RenderingIntent = .default
var effect: SVGEffect = SVGEffect()
}
private struct GraphicState {
var clip: SVGContext.Clip?
var styles: SVGContextStyles
init(context: SVGContext) {
self.clip = context.state.clip
self.styles = context.styles
}
func apply(to context: SVGContext) {
context.state.clip = self.clip
context.styles = self.styles
}
}
private struct SVGContextState {
var clip: SVGContext.Clip?
var elements: [SDXMLElement] = []
var visibleBound: Rect?
var objectBound: Shape?
var defs: [SDXMLElement] = []
var imageTable: [SVGContext.ImageTableKey: String] = [:]
}
public class SVGContext: DrawableContext {
public let viewBox: Rect
public let resolution: Resolution
fileprivate var state: SVGContextState = SVGContextState()
fileprivate var styles: SVGContextStyles = SVGContextStyles()
private var graphicStateStack: [GraphicState] = []
private var next: SVGContext?
private weak var global: SVGContext?
public init(viewBox: Rect, resolution: Resolution = .default) {
self.viewBox = viewBox
self.resolution = resolution
}
}
extension SVGContext {
public convenience init(width: Double, height: Double, unit: Resolution.Unit = .point) {
let _width = unit.convert(length: width, to: .point)
let _height = unit.convert(length: height, to: .point)
self.init(viewBox: Rect(x: 0, y: 0, width: _width, height: _height), resolution: Resolution.default.convert(to: unit))
}
}
extension SVGContext {
private convenience init(copyStates context: SVGContext) {
self.init(viewBox: context.viewBox, resolution: context.resolution)
self.styles = context.styles
self.styles.opacity = 1
self.styles.shadowColor = SVGContextStyles.defaultShadowColor
self.styles.shadowOffset = Size()
self.styles.shadowBlur = 0
self.styles.compositingMode = .default
self.styles.blendMode = .default
self.styles.effect = SVGEffect()
}
}
extension SVGContext {
fileprivate enum Clip {
case clip(String, Shape, Shape.WindingRule)
case mask(String)
}
fileprivate enum ImageTableKey: Hashable {
case image(AnyImage)
case data(Data)
#if canImport(CoreGraphics)
case cgimage(CGImage)
#endif
init(_ image: AnyImage) {
self = .image(image)
}
init(_ data: Data) {
self = .data(data)
}
#if canImport(CoreGraphics)
init(_ image: CGImage) {
self = .cgimage(image)
}
#endif
static func ==(lhs: ImageTableKey, rhs: ImageTableKey) -> Bool {
switch (lhs, rhs) {
case let (.image(lhs), .image(rhs)): return lhs.isStorageEqual(rhs)
case let (.data(lhs), .data(rhs)): return lhs.isStorageEqual(rhs)
#if canImport(CoreGraphics)
case let (.cgimage(lhs), .cgimage(rhs)): return lhs === rhs
#endif
default: return false
}
}
#if canImport(CoreGraphics)
func hash(into hasher: inout Hasher) {
switch self {
case let .image(image):
hasher.combine(image)
hasher.combine(0)
case let .data(data):
hasher.combine(data)
hasher.combine(1)
case let .cgimage(image):
hasher.combine(ObjectIdentifier(image))
hasher.combine(2)
}
}
#endif
}
}
extension SVGContext {
private var current_layer: SVGContext {
return next?.current_layer ?? self
}
private func _clone(global: SVGContext?) -> SVGContext {
let clone = SVGContext(viewBox: viewBox, resolution: resolution)
clone.state = self.state
clone.styles = self.styles
clone.graphicStateStack = self.graphicStateStack
clone.next = self.next?._clone(global: global ?? clone)
clone.global = global
return clone
}
public func clone() -> SVGContext {
return self._clone(global: nil)
}
public var defs: [SDXMLElement] {
get {
return global?.defs ?? state.defs
}
set {
if let global = self.global {
global.state.defs = newValue
} else {
self.state.defs = newValue
}
}
}
public var all_names: Set<String> {
return Set(defs.compactMap { $0.isNode ? $0.attributes(for: "id", namespace: "") : nil })
}
public func new_name(_ type: String) -> String {
let all_names = self.all_names
var name = ""
var counter = 6
let chars = Array("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ")
repeat {
let _name = String((0..<counter).map { _ in chars.randomElement()! })
name = "\(type)_ID_\(_name)"
counter += 1
} while all_names.contains(name)
return name
}
private var imageTable: [ImageTableKey: String] {
get {
return global?.imageTable ?? state.imageTable
}
set {
if let global = self.global {
global.state.imageTable = newValue
} else {
self.state.imageTable = newValue
}
}
}
}
extension SVGContext {
public var isRasterContext: Bool {
return false
}
public var opacity: Double {
get {
return current_layer.styles.opacity
}
set {
current_layer.styles.opacity = newValue
}
}
public var transform: SDTransform {
get {
return current_layer.styles.transform
}
set {
current_layer.styles.transform = newValue
}
}
public var shadowColor: AnyColor {
get {
return current_layer.styles.shadowColor
}
set {
current_layer.styles.shadowColor = newValue
}
}
public var shadowOffset: Size {
get {
return current_layer.styles.shadowOffset
}
set {
current_layer.styles.shadowOffset = newValue
}
}
public var shadowBlur: Double {
get {
return current_layer.styles.shadowBlur
}
set {
current_layer.styles.shadowBlur = newValue
}
}
public var compositingMode: ColorCompositingMode {
get {
return current_layer.styles.compositingMode
}
set {
current_layer.styles.compositingMode = newValue
}
}
public var blendMode: ColorBlendMode {
get {
return current_layer.styles.blendMode
}
set {
current_layer.styles.blendMode = newValue
}
}
public var renderingIntent: RenderingIntent {
get {
return current_layer.styles.renderingIntent
}
set {
current_layer.styles.renderingIntent = newValue
}
}
public var effect: SVGEffect {
get {
return current_layer.styles.effect
}
set {
current_layer.styles.effect = newValue
}
}
}
private func getDataString(_ x: Double ...) -> String {
return getDataString(x)
}
private func getDataString(_ x: [Double]) -> String {
return x.map { "\(Decimal($0).rounded(scale: 9))" }.joined(separator: " ")
}
extension SDTransform {
fileprivate func attributeStr() -> String? {
let transformStr = getDataString(a, d, b, e, c, f)
if transformStr == "1 0 0 1 0 0" {
return nil
}
return "matrix(\(transformStr))"
}
}
extension SVGContext {
public var document: SDXMLDocument {
var body = SDXMLElement(name: "svg", attributes: [
"xmlns": "http://www.w3.org/2000/svg",
"xmlns:xlink": "http://www.w3.org/1999/xlink",
"xmlns:a": "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/",
"style": "isolation: isolate;"
])
body.setAttribute(for: "viewBox", value: getDataString(viewBox.minX, viewBox.minY, viewBox.width, viewBox.height))
let x = viewBox.minX / resolution.horizontal
let y = viewBox.minY / resolution.vertical
let width = viewBox.width / resolution.horizontal
let height = viewBox.height / resolution.vertical
switch resolution.unit {
case .point:
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))pt")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))pt")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))pt")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))pt")
case .pica:
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))pc")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))pc")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))pc")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))pc")
case .meter:
let x = resolution.unit.convert(length: x, to: .centimeter)
let y = resolution.unit.convert(length: y, to: .centimeter)
let width = resolution.unit.convert(length: width, to: .centimeter)
let height = resolution.unit.convert(length: height, to: .centimeter)
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))cm")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))cm")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))cm")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))cm")
case .centimeter:
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))cm")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))cm")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))cm")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))cm")
case .millimeter:
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))mm")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))mm")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))mm")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))mm")
case .inch:
body.setAttribute(for: "x", value: "\(Decimal(x).rounded(scale: 9))in")
body.setAttribute(for: "y", value: "\(Decimal(y).rounded(scale: 9))in")
body.setAttribute(for: "width", value: "\(Decimal(width).rounded(scale: 9))in")
body.setAttribute(for: "height", value: "\(Decimal(height).rounded(scale: 9))in")
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .long
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.timeZone = TimeZone(secondsFromGMT: 0)
body.append(SDXMLElement(comment: " Created by Doggie SVG Generator; \(dateFormatter.string(from: Date())) "))
if !defs.isEmpty {
body.append(SDXMLElement(name: "defs", elements: defs))
}
body.append(contentsOf: state.elements)
return [body]
}
}
extension SVGContext {
public func saveGraphicState() {
graphicStateStack.append(GraphicState(context: current_layer))
}
public func restoreGraphicState() {
graphicStateStack.popLast()?.apply(to: current_layer)
}
}
extension SVGContext {
private func apply_style(_ element: inout SDXMLElement, _ visibleBound: inout Rect, _ objectBound: Shape, _ clip_object: Bool, _ object_transform: SDTransform) {
var style: [String: String] = ["isolation": "isolate"]
let _objectBound = objectBound.boundary
if self.effect.output != nil && _objectBound.width != 0 && _objectBound.height != 0 {
let _transform = self.transform.inverse
var _visibleBound = visibleBound._applying(_transform)
if let filter = self._effect_element("FILTER", self.effect, &_visibleBound, (objectBound * _transform).boundary) {
visibleBound = _visibleBound._applying(self.transform)
element.setAttribute(for: "transform", value: (object_transform * _transform).attributeStr())
element = SDXMLElement(name: "g", elements: [element])
element.setAttribute(for: "filter", value: "url(#\(filter))")
element.setAttribute(for: "transform", value: self.transform.attributeStr())
}
}
if self.shadowColor.opacity > 0 && self.shadowBlur > 0 && _objectBound.width != 0 && _objectBound.height != 0 {
if !element.attributes(for: "transform").isEmpty {
element = SDXMLElement(name: "g", elements: [element])
}
let gaussian_blur_uuid = UUID()
let offset_uuid = UUID()
let flood_uuid = UUID()
let blend_uuid = UUID()
var effect: SVGEffect = [
gaussian_blur_uuid: SVGGaussianBlurEffect(source: .sourceAlpha, stdDeviation: 0.5 * self.shadowBlur),
offset_uuid: SVGOffsetEffect(source: .reference(gaussian_blur_uuid), offset: self.shadowOffset),
flood_uuid: SVGFloodEffect(color: self.shadowColor),
blend_uuid: SVGBlendEffect(source: .reference(flood_uuid), source2: .reference(offset_uuid), mode: .in),
]
effect.output = SVGMergeEffect(sources: [.reference(blend_uuid), .source])
if let filter = self._effect_element("SHADOW", effect, &visibleBound, _objectBound) {
element.setAttribute(for: "filter", value: "url(#\(filter))")
}
}
if self.opacity < 1 {
element.setAttribute(for: "opacity", value: "\(Decimal(self.opacity).rounded(scale: 9))")
}
switch self.blendMode {
case .normal: break
case .multiply:
style["mix-blend-mode"] = "multiply"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "multiply")
case .screen:
style["mix-blend-mode"] = "screen"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "screen")
case .overlay:
style["mix-blend-mode"] = "overlay"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "overlay")
case .darken:
style["mix-blend-mode"] = "darken"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "darken")
case .lighten:
style["mix-blend-mode"] = "lighten"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "lighten")
case .colorDodge:
style["mix-blend-mode"] = "color-dodge"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "colorDodge")
case .colorBurn:
style["mix-blend-mode"] = "color-burn"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "colorBurn")
case .softLight:
style["mix-blend-mode"] = "soft-light"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "softLight")
case .hardLight:
style["mix-blend-mode"] = "hard-light"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "hardLight")
case .difference:
style["mix-blend-mode"] = "difference"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "difference")
case .exclusion:
style["mix-blend-mode"] = "exclusion"
element.setAttribute(for: "adobe-blending-mode", namespace: "http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/", value: "exclusion")
default: break
}
if clip_object, let clip = self.current_layer.state.clip {
if !element.attributes(for: "transform").isEmpty {
element = SDXMLElement(name: "g", elements: [element])
}
switch clip {
case let .clip(id, _, _): element.setAttribute(for: "clip-path", value: "url(#\(id))")
case let .mask(id): element.setAttribute(for: "mask", value: "url(#\(id))")
}
}
if !style.isEmpty {
var style: [String] = style.map { "\($0): \($1)" }
if let _style = element.attributes(for: "style", namespace: "") {
style = _style.split(separator: ";").map { $0.trimmingCharacters(in: .whitespaces) } + style
}
element.setAttribute(for: "style", value: style.joined(separator: "; "))
}
}
private func append(_ newElement: SDXMLElement, _ visibleBound: Rect, _ objectBound: Shape, _ clip_object: Bool, _ object_transform: SDTransform) {
guard self.transform.invertible && !visibleBound.isEmpty else { return }
var newElement = newElement
var visibleBound = visibleBound
self.apply_style(&newElement, &visibleBound, objectBound, clip_object, object_transform)
self.current_layer.state.elements.append(newElement)
self.current_layer.state.visibleBound = self.current_layer.state.visibleBound.map { $0.union(visibleBound) } ?? visibleBound
self.current_layer.state.objectBound = self.current_layer.state.objectBound.map { $0.identity + objectBound.identity } ?? objectBound
}
private func append(_ newElement: SDXMLElement, _ objectBound: Shape, _ clip_object: Bool, _ object_transform: SDTransform) {
self.append(newElement, objectBound.boundary, objectBound, clip_object, object_transform)
}
}
extension SVGContext {
public func beginTransparencyLayer() {
if let next = self.next {
next.beginTransparencyLayer()
} else {
self.next = SVGContext(copyStates: self)
self.next?.global = global ?? self
}
}
public func endTransparencyLayer() {
if let next = self.next {
if next.next != nil {
next.endTransparencyLayer()
} else {
self.next = nil
guard !next.state.elements.isEmpty else { return }
guard let visibleBound = next.state.visibleBound else { return }
guard let objectBound = next.state.objectBound else { return }
self.append(SDXMLElement(name: "g", elements: next.state.elements), visibleBound, objectBound, true, .identity)
}
}
}
}
extension SVGContext {
private func create_color<C: ColorProtocol>(_ color: C) -> String {
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
let red = UInt8((color.red * 255).clamped(to: 0...255).rounded())
let green = UInt8((color.green * 255).clamped(to: 0...255).rounded())
let blue = UInt8((color.blue * 255).clamped(to: 0...255).rounded())
return "rgb(\(red),\(green),\(blue))"
}
public func draw<C: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: C) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
let shape = shape * self.transform
var element = SDXMLElement(name: "path", attributes: ["d": shape.identity.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
element.setAttribute(for: "fill", value: create_color(color))
if color.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(color.opacity).rounded(scale: 9))")
}
self.append(element, shape, true, .identity)
}
public func draw<C: ColorProtocol>(shape: Shape, stroke: Stroke<C>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
var element = SDXMLElement(name: "path", attributes: ["d": shape.identity.encode()])
element.setAttribute(for: "fill", value: "none")
element.setAttribute(for: "stroke", value: create_color(stroke.color))
if stroke.color.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(stroke.color.opacity).rounded(scale: 9))")
}
element.setAttribute(for: "stroke-width", value: "\(Decimal(stroke.width).rounded(scale: 9))")
switch stroke.cap {
case .butt: element.setAttribute(for: "stroke-linecap", value: "butt")
case .round: element.setAttribute(for: "stroke-linecap", value: "round")
case .square: element.setAttribute(for: "stroke-linecap", value: "square")
}
switch stroke.join {
case let .miter(limit):
element.setAttribute(for: "stroke-linejoin", value: "miter")
element.setAttribute(for: "stroke-miterlimit", value: "\(Decimal(limit).rounded(scale: 9))")
case .round: element.setAttribute(for: "stroke-linejoin", value: "round")
case .bevel: element.setAttribute(for: "stroke-linejoin", value: "bevel")
}
element.setAttribute(for: "transform", value: self.transform.attributeStr())
self.append(element, shape.strokePath(stroke), true, self.transform)
}
}
private protocol SVGImageProtocol {
var width: Int { get }
var height: Int { get }
var imageTableKey: SVGContext.ImageTableKey? { get }
func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String?
}
extension MediaType {
fileprivate var _mime_type: MIMEType? {
switch self {
case .bmp: return .bmp
case .gif: return .gif
case .heic: return .heic
case .heif: return .heif
case .jpeg: return .jpeg
case .jpeg2000: return .jpeg2000
case .png: return .png
case .tiff: return .tiff
case .webp: return .webp
default:
#if canImport(CoreServices)
return mimeTypes.first ?? _mimeTypes.first
#else
return mimeTypes.first
#endif
}
}
}
extension Image: SVGImageProtocol {
fileprivate var imageTableKey: SVGContext.ImageTableKey? {
return SVGContext.ImageTableKey(AnyImage(self))
}
fileprivate func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String? {
guard let mediaType = storageType._mime_type?.rawValue else { return nil }
guard let properties = properties as? [ImageRep.PropertyKey : Any] else { return nil }
guard let data = self.representation(using: storageType, properties: properties) else { return nil }
return "data:\(mediaType);base64," + data.base64EncodedString()
}
}
extension AnyImage: SVGImageProtocol {
fileprivate var imageTableKey: SVGContext.ImageTableKey? {
return SVGContext.ImageTableKey(self)
}
fileprivate func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String? {
guard let mediaType = storageType._mime_type?.rawValue else { return nil }
guard let properties = properties as? [ImageRep.PropertyKey : Any] else { return nil }
guard let data = self.representation(using: storageType, properties: properties) else { return nil }
return "data:\(mediaType);base64," + data.base64EncodedString()
}
}
extension ImageRep: SVGImageProtocol {
fileprivate var imageTableKey: SVGContext.ImageTableKey? {
return self.originalData.map { SVGContext.ImageTableKey($0) } ?? SVGContext.ImageTableKey(AnyImage(imageRep: self, fileBacked: true))
}
fileprivate func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String? {
if let data = self.originalData, let mediaType = self.mediaType?._mime_type?.rawValue {
return "data:\(mediaType);base64," + data.base64EncodedString()
} else {
let image = AnyImage(imageRep: self, fileBacked: true)
return image.encode(using: storageType, resolution: resolution, properties: properties)
}
}
}
extension SVGContext {
private func _draw(image: SVGImageProtocol, transform: SDTransform, using storageType: MediaType, resolution: Resolution, properties: Any) {
guard self.transform.invertible else { return }
guard let key = image.imageTableKey else { return }
let id: String
if let _id = imageTable[key] {
id = _id
} else {
id = new_name("IMAGE")
var _image = SDXMLElement(name: "image", attributes: [
"id": id,
"width": "\(image.width)",
"height": "\(image.height)",
])
guard let encoded = image.encode(using: storageType, resolution: resolution, properties: properties) else { return }
_image.setAttribute(for: "href", namespace: "http://www.w3.org/1999/xlink", value: encoded)
defs.append(_image)
imageTable[key] = id
}
var element = SDXMLElement(name: "use")
element.setAttribute(for: "href", namespace: "http://www.w3.org/1999/xlink", value: "#\(id)")
let transform = transform * self.transform
element.setAttribute(for: "transform", value: transform.attributeStr())
let _bound = Shape(rect: Rect(x: 0, y: 0, width: image.width, height: image.height)) * transform
self.append(element, _bound, true, transform)
}
public func draw<Image: ImageProtocol>(image: Image, transform: SDTransform, using storageType: MediaType, properties: [ImageRep.PropertyKey: Any]) {
let _image = image as? SVGImageProtocol ?? image.convert(to: .sRGB, intent: renderingIntent) as DoggieGraphics.Image<ARGB32ColorPixel>
self._draw(image: _image, transform: transform, using: storageType, resolution: image.resolution, properties: properties)
}
public func draw(image: ImageRep, transform: SDTransform, using storageType: MediaType, properties: [ImageRep.PropertyKey: Any]) {
self._draw(image: image, transform: transform, using: storageType, resolution: image.resolution, properties: properties)
}
}
extension SVGContext {
public func draw<Image: ImageProtocol>(image: Image, transform: SDTransform) {
self.draw(image: image, transform: transform, using: .png, properties: [:])
}
public func draw(image: ImageRep, transform: SDTransform) {
self.draw(image: image, transform: transform, using: .png, properties: [:])
}
}
#if canImport(CoreGraphics)
extension CGImage: SVGImageProtocol {
fileprivate var imageTableKey: SVGContext.ImageTableKey? {
return SVGContext.ImageTableKey(self)
}
fileprivate func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String? {
guard let mediaType = storageType._mime_type?.rawValue else { return nil }
guard let properties = properties as? [CGImageRep.PropertyKey : Any] else { return nil }
guard let data = self.representation(using: storageType, resolution: resolution, properties: properties) else { return nil }
return "data:\(mediaType);base64," + data.base64EncodedString()
}
}
extension CGImageRep: SVGImageProtocol {
fileprivate var imageTableKey: SVGContext.ImageTableKey? {
return self.cgImage.map { SVGContext.ImageTableKey($0) }
}
fileprivate func encode(using storageType: MediaType, resolution: Resolution, properties: Any) -> String? {
return self.cgImage?.encode(using: storageType, resolution: resolution, properties: properties)
}
}
extension SVGContext {
public func draw(image: CGImageRep, transform: SDTransform, using storageType: MediaType = .png, resolution: Resolution = .default, properties: [CGImageRep.PropertyKey: Any] = [:]) {
self._draw(image: image, transform: transform, using: storageType, resolution: resolution, properties: properties)
}
public func draw(image: CGImage, transform: SDTransform, using storageType: MediaType = .png, resolution: Resolution = .default, properties: [CGImageRep.PropertyKey: Any] = [:]) {
self._draw(image: image, transform: transform, using: storageType, resolution: resolution, properties: properties)
}
}
#endif
extension SVGContext {
public func resetClip() {
current_layer.state.clip = nil
}
public func clip(shape: Shape, winding: Shape.WindingRule) {
guard shape.contains(where: { !$0.isEmpty }) else {
current_layer.state.clip = nil
return
}
let id = new_name("CLIP")
let clipRule: String
switch winding {
case .nonZero: clipRule = "nonzero"
case .evenOdd: clipRule = "evenodd"
}
var shape = shape * self.transform
shape = shape.identity
let clipPath = SDXMLElement(name: "clipPath", attributes: ["id": id], elements: [SDXMLElement(name: "path", attributes: ["d": shape.encode(), "clip-rule": clipRule])])
defs.append(clipPath)
current_layer.state.clip = .clip(id, shape, winding)
}
public func clipToDrawing(body: (DrawableContext) throws -> Void) rethrows {
try self.clipToDrawing { (context: SVGContext) in try body(context) }
}
public func clipToDrawing(body: (SVGContext) throws -> Void) rethrows {
let mask_context = SVGContext(copyStates: current_layer)
mask_context.global = global ?? self
try body(mask_context)
let id = new_name("MASK")
let mask = SDXMLElement(name: "mask", attributes: ["id": id], elements: mask_context.state.elements)
defs.append(mask)
current_layer.state.clip = .mask(id)
}
}
extension SVGContext {
private func create_gradient<C>(_ gradient: Gradient<C>) -> String {
let id = new_name("GRADIENT")
switch gradient.type {
case .linear:
var element = SDXMLElement(name: "linearGradient", attributes: [
"id": id,
"gradientUnits": "objectBoundingBox",
"x1": "\(Decimal(gradient.start.x).rounded(scale: 9))",
"y1": "\(Decimal(gradient.start.y).rounded(scale: 9))",
"x2": "\(Decimal(gradient.end.x).rounded(scale: 9))",
"y2": "\(Decimal(gradient.end.y).rounded(scale: 9))",
])
switch gradient.startSpread {
case .reflect: element.setAttribute(for: "spreadMethod", value: "reflect")
case .repeat: element.setAttribute(for: "spreadMethod", value: "repeat")
default: break
}
element.setAttribute(for: "gradientTransform", value: gradient.transform.attributeStr())
for stop in gradient.stops {
var _stop = SDXMLElement(name: "stop")
_stop.setAttribute(for: "offset", value: "\(Decimal(stop.offset).rounded(scale: 9))")
_stop.setAttribute(for: "stop-color", value: create_color(stop.color))
if stop.color.opacity < 1 {
_stop.setAttribute(for: "stop-opacity", value: "\(Decimal(stop.color.opacity).rounded(scale: 9))")
}
element.append(_stop)
}
defs.append(element)
case .radial:
let magnitude = (gradient.start - gradient.end).magnitude
let phase = (gradient.start - gradient.end).phase
var element = SDXMLElement(name: "radialGradient", attributes: [
"id": id,
"gradientUnits": "objectBoundingBox",
"fx": "\(Decimal(0.5 + magnitude).rounded(scale: 9))",
"fy": "0.5",
"cx": "0.5",
"cy": "0.5",
])
switch gradient.startSpread {
case .reflect: element.setAttribute(for: "spreadMethod", value: "reflect")
case .repeat: element.setAttribute(for: "spreadMethod", value: "repeat")
default: break
}
let transform = SDTransform.translate(x: -0.5, y: -0.5) * SDTransform.rotate(phase) * SDTransform.translate(x: gradient.end.x, y: gradient.end.y) * gradient.transform
element.setAttribute(for: "gradientTransform", value: transform.attributeStr())
for stop in gradient.stops {
var _stop = SDXMLElement(name: "stop")
_stop.setAttribute(for: "offset", value: "\(Decimal(stop.offset).rounded(scale: 9))")
_stop.setAttribute(for: "stop-color", value: create_color(stop.color))
if stop.color.opacity < 1 {
_stop.setAttribute(for: "stop-opacity", value: "\(Decimal(stop.color.opacity).rounded(scale: 9))")
}
element.append(_stop)
}
defs.append(element)
}
return "url(#\(id))"
}
public func draw<C>(shape: Shape, winding: Shape.WindingRule, color gradient: Gradient<C>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard gradient.transform.invertible else { return }
var gradient = gradient
gradient.transform *= SDTransform.scale(x: shape.originalBoundary.width, y: shape.originalBoundary.height)
gradient.transform *= SDTransform.translate(x: shape.originalBoundary.minX, y: shape.originalBoundary.minY)
gradient.transform *= shape.transform * self.transform
var shape = shape * self.transform
shape = shape.identity
gradient.transform *= SDTransform.translate(x: shape.originalBoundary.minX, y: shape.originalBoundary.minY).inverse
gradient.transform *= SDTransform.scale(x: shape.originalBoundary.width, y: shape.originalBoundary.height).inverse
var element = SDXMLElement(name: "path", attributes: ["d": shape.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
element.setAttribute(for: "fill", value: create_gradient(gradient))
if gradient.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(gradient.opacity).rounded(scale: 9))")
}
self.append(element, shape, true, .identity)
}
public func draw<C>(shape: Shape, stroke: Stroke<Gradient<C>>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard stroke.color.transform.invertible else { return }
let shape_identity = shape.identity
let strokePath = shape.strokePath(stroke)
var element = SDXMLElement(name: "path", attributes: ["d": shape_identity.encode()])
var gradient = stroke.color
gradient.transform *= SDTransform.scale(x: strokePath.originalBoundary.width, y: strokePath.originalBoundary.height)
gradient.transform *= SDTransform.translate(x: strokePath.originalBoundary.minX, y: strokePath.originalBoundary.minY)
gradient.transform *= SDTransform.translate(x: shape_identity.originalBoundary.minX, y: shape_identity.originalBoundary.minY).inverse
gradient.transform *= SDTransform.scale(x: shape_identity.originalBoundary.width, y: shape_identity.originalBoundary.height).inverse
element.setAttribute(for: "fill", value: "none")
element.setAttribute(for: "stroke", value: create_gradient(gradient))
if stroke.color.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(stroke.color.opacity).rounded(scale: 9))")
}
element.setAttribute(for: "stroke-width", value: "\(Decimal(stroke.width).rounded(scale: 9))")
switch stroke.cap {
case .butt: element.setAttribute(for: "stroke-linecap", value: "butt")
case .round: element.setAttribute(for: "stroke-linecap", value: "round")
case .square: element.setAttribute(for: "stroke-linecap", value: "square")
}
switch stroke.join {
case let .miter(limit):
element.setAttribute(for: "stroke-linejoin", value: "miter")
element.setAttribute(for: "stroke-miterlimit", value: "\(Decimal(limit).rounded(scale: 9))")
case .round: element.setAttribute(for: "stroke-linejoin", value: "round")
case .bevel: element.setAttribute(for: "stroke-linejoin", value: "bevel")
}
element.setAttribute(for: "transform", value: self.transform.attributeStr())
self.append(element, strokePath, true, self.transform)
}
}
extension SVGContext {
public func drawLinearGradient<C>(stops: [GradientStop<C>], start: Point, end: Point, startSpread: GradientSpreadMode, endSpread: GradientSpreadMode) {
self.drawLinearGradient(stops: stops, start: start, end: end, spreadMethod: startSpread)
}
public func drawRadialGradient<C>(stops: [GradientStop<C>], start: Point, startRadius: Double, end: Point, endRadius: Double, startSpread: GradientSpreadMode, endSpread: GradientSpreadMode) {
self.drawRadialGradient(stops: stops, start: start, startRadius: startRadius, end: end, endRadius: endRadius, spreadMethod: startSpread)
}
private func create_gradient<C>(stops: [GradientStop<C>], start: Point, end: Point, spreadMethod: GradientSpreadMode, element: SDXMLElement) -> String {
let id = new_name("GRADIENT")
var element = element
element.setAttribute(for: "id", value: id)
element.setAttribute(for: "gradientUnits", value: "userSpaceOnUse")
switch spreadMethod {
case .reflect: element.setAttribute(for: "spreadMethod", value: "reflect")
case .repeat: element.setAttribute(for: "spreadMethod", value: "repeat")
default: break
}
for stop in stops.sorted() {
var _stop = SDXMLElement(name: "stop")
_stop.setAttribute(for: "offset", value: "\(Decimal(stop.offset).rounded(scale: 9))")
_stop.setAttribute(for: "stop-color", value: create_color(stop.color))
if stop.color.opacity < 1 {
_stop.setAttribute(for: "stop-opacity", value: "\(Decimal(stop.color.opacity).rounded(scale: 9))")
}
element.append(_stop)
}
defs.append(element)
return "url(#\(id))"
}
public func drawLinearGradient<C>(stops: [GradientStop<C>], start: Point, end: Point, spreadMethod: GradientSpreadMode) {
guard self.transform.invertible else { return }
let objectBound: Shape
let clip_object: Bool
var element: SDXMLElement
if case let .clip(_, shape, winding) = current_layer.state.clip {
element = SDXMLElement(name: "path", attributes: ["d": shape.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
objectBound = shape
clip_object = false
} else {
element = SDXMLElement(name: "rect", attributes: [
"x": "\(Decimal(viewBox.minX).rounded(scale: 9))",
"y": "\(Decimal(viewBox.minY).rounded(scale: 9))",
"width": "\(Decimal(viewBox.width).rounded(scale: 9))",
"height": "\(Decimal(viewBox.height).rounded(scale: 9))",
])
objectBound = Shape(rect: self.viewBox)
clip_object = true
}
var gradient = SDXMLElement(name: "linearGradient", attributes: [
"x1": "\(Decimal(start.x).rounded(scale: 9))",
"y1": "\(Decimal(start.y).rounded(scale: 9))",
"x2": "\(Decimal(end.x).rounded(scale: 9))",
"y2": "\(Decimal(end.y).rounded(scale: 9))",
])
gradient.setAttribute(for: "gradientTransform", value: self.transform.attributeStr())
element.setAttribute(for: "fill", value: create_gradient(stops: stops, start: start, end: end, spreadMethod: spreadMethod, element: gradient))
self.append(element, objectBound, clip_object, .identity)
}
public func drawRadialGradient<C>(stops: [GradientStop<C>], start: Point, startRadius: Double, end: Point, endRadius: Double, spreadMethod: GradientSpreadMode) {
guard self.transform.invertible else { return }
let objectBound: Shape
let clip_object: Bool
var element: SDXMLElement
if case let .clip(_, shape, winding) = current_layer.state.clip {
element = SDXMLElement(name: "path", attributes: ["d": shape.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
objectBound = shape
clip_object = false
} else {
element = SDXMLElement(name: "rect", attributes: [
"x": "\(Decimal(viewBox.minX).rounded(scale: 9))",
"y": "\(Decimal(viewBox.minY).rounded(scale: 9))",
"width": "\(Decimal(viewBox.width).rounded(scale: 9))",
"height": "\(Decimal(viewBox.height).rounded(scale: 9))",
])
objectBound = Shape(rect: self.viewBox)
clip_object = true
}
let magnitude = (start - end).magnitude
let phase = (start - end).phase
var gradient = SDXMLElement(name: "radialGradient", attributes: [
"fx": "\(Decimal(0.5 + magnitude).rounded(scale: 9))",
"fy": "0.5",
"cx": "0.5",
"cy": "0.5",
"fr": "\(Decimal(startRadius).rounded(scale: 9))",
"r": "\(Decimal(endRadius).rounded(scale: 9))",
])
let transform = SDTransform.translate(x: -0.5, y: -0.5) * SDTransform.rotate(phase) * SDTransform.translate(x: end.x, y: end.y) * self.transform
gradient.setAttribute(for: "gradientTransform", value: transform.attributeStr())
element.setAttribute(for: "fill", value: create_gradient(stops: stops, start: start, end: end, spreadMethod: spreadMethod, element: gradient))
self.append(element, objectBound, clip_object, .identity)
}
}
extension SVGContext {
public func drawMeshGradient<C>(_ mesh: MeshGradient<C>) {
}
}
extension SVGContext {
private func create_pattern(pattern: Pattern) -> String {
let pattern_context = SVGContext(viewBox: pattern.bound, resolution: resolution)
pattern_context.global = global ?? self
if pattern.xStep != pattern.bound.width || pattern.yStep != pattern.bound.height {
pattern_context.clip(rect: pattern.bound)
pattern_context.beginTransparencyLayer()
pattern.callback(pattern_context)
pattern_context.endTransparencyLayer()
} else {
pattern.callback(pattern_context)
}
let id = new_name("PATTERN")
var element = SDXMLElement(name: "pattern", attributes: [
"x": "\(Decimal(pattern.bound.minX).rounded(scale: 9))",
"y": "\(Decimal(pattern.bound.minY).rounded(scale: 9))",
"width": "\(Decimal(pattern.xStep).rounded(scale: 9))",
"height": "\(Decimal(pattern.yStep).rounded(scale: 9))",
"viewBox": getDataString(pattern.bound.minX, pattern.bound.minY, pattern.xStep, pattern.yStep),
], elements: pattern_context.state.elements)
let transform = pattern.transform * self.transform
element.setAttribute(for: "patternTransform", value: transform.attributeStr())
element.setAttribute(for: "id", value: id)
element.setAttribute(for: "patternUnits", value: "userSpaceOnUse")
defs.append(element)
return "url(#\(id))"
}
public func draw(shape: Shape, winding: Shape.WindingRule, color pattern: Pattern) {
guard self.transform.invertible else { return }
guard !pattern.bound.width.almostZero() && !pattern.bound.height.almostZero() && !pattern.xStep.almostZero() && !pattern.yStep.almostZero() else { return }
guard !pattern.bound.isEmpty && pattern.xStep.isFinite && pattern.yStep.isFinite else { return }
guard pattern.transform.invertible else { return }
let shape = shape * self.transform
var element = SDXMLElement(name: "path", attributes: ["d": shape.identity.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
element.setAttribute(for: "fill", value: create_pattern(pattern: pattern))
if pattern.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(pattern.opacity).rounded(scale: 9))")
}
self.append(element, shape, true, .identity)
}
public func draw(shape: Shape, stroke: Stroke<Pattern>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard !stroke.color.bound.width.almostZero() && !stroke.color.bound.height.almostZero() && !stroke.color.xStep.almostZero() && !stroke.color.yStep.almostZero() else { return }
guard !stroke.color.bound.isEmpty && stroke.color.xStep.isFinite && stroke.color.yStep.isFinite else { return }
guard stroke.color.transform.invertible else { return }
var element = SDXMLElement(name: "path", attributes: ["d": shape.identity.encode()])
var pattern = stroke.color
pattern.transform *= self.transform.inverse
element.setAttribute(for: "fill", value: "none")
element.setAttribute(for: "stroke", value: create_pattern(pattern: pattern))
if stroke.color.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(stroke.color.opacity).rounded(scale: 9))")
}
element.setAttribute(for: "stroke-width", value: "\(Decimal(stroke.width).rounded(scale: 9))")
switch stroke.cap {
case .butt: element.setAttribute(for: "stroke-linecap", value: "butt")
case .round: element.setAttribute(for: "stroke-linecap", value: "round")
case .square: element.setAttribute(for: "stroke-linecap", value: "square")
}
switch stroke.join {
case let .miter(limit):
element.setAttribute(for: "stroke-linejoin", value: "miter")
element.setAttribute(for: "stroke-miterlimit", value: "\(Decimal(limit).rounded(scale: 9))")
case .round: element.setAttribute(for: "stroke-linejoin", value: "round")
case .bevel: element.setAttribute(for: "stroke-linejoin", value: "bevel")
}
element.setAttribute(for: "transform", value: self.transform.attributeStr())
self.append(element, shape.strokePath(stroke), true, self.transform)
}
public func drawPattern(_ pattern: Pattern) {
guard self.transform.invertible else { return }
guard !pattern.bound.width.almostZero() && !pattern.bound.height.almostZero() && !pattern.xStep.almostZero() && !pattern.yStep.almostZero() else { return }
guard !pattern.bound.isEmpty && pattern.xStep.isFinite && pattern.yStep.isFinite else { return }
guard pattern.transform.invertible else { return }
let objectBound: Shape
let clip_object: Bool
var element: SDXMLElement
if case let .clip(_, shape, winding) = current_layer.state.clip {
element = SDXMLElement(name: "path", attributes: ["d": shape.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
objectBound = shape
clip_object = false
} else {
element = SDXMLElement(name: "rect", attributes: [
"x": "\(Decimal(viewBox.minX).rounded(scale: 9))",
"y": "\(Decimal(viewBox.minY).rounded(scale: 9))",
"width": "\(Decimal(viewBox.width).rounded(scale: 9))",
"height": "\(Decimal(viewBox.height).rounded(scale: 9))",
])
objectBound = Shape(rect: self.viewBox)
clip_object = true
}
element.setAttribute(for: "fill", value: create_pattern(pattern: pattern))
if pattern.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(pattern.opacity).rounded(scale: 9))")
}
self.append(element, objectBound, clip_object, .identity)
}
}
extension SVGContext {
private func _draw<C1, C2>(shape: Shape, winding: Shape.WindingRule, color: C1, stroke: Stroke<C2>) {
let shape_identity = shape.identity
let strokePath = shape.strokePath(stroke)
var element = SDXMLElement(name: "path", attributes: ["d": shape_identity.encode()])
switch winding {
case .nonZero: element.setAttribute(for: "fill-rule", value: "nonzero")
case .evenOdd: element.setAttribute(for: "fill-rule", value: "evenodd")
}
switch color {
case let color as Color<RGBColorModel>:
element.setAttribute(for: "fill", value: create_color(color))
if color.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(color.opacity).rounded(scale: 9))")
}
case var gradient as Gradient<Color<RGBColorModel>>:
gradient.transform *= SDTransform.scale(x: shape.originalBoundary.width, y: shape.originalBoundary.height)
gradient.transform *= SDTransform.translate(x: shape.originalBoundary.minX, y: shape.originalBoundary.minY)
gradient.transform *= shape.transform
gradient.transform *= SDTransform.translate(x: shape_identity.originalBoundary.minX, y: shape_identity.originalBoundary.minY).inverse
gradient.transform *= SDTransform.scale(x: shape_identity.originalBoundary.width, y: shape_identity.originalBoundary.height).inverse
element.setAttribute(for: "fill", value: create_gradient(gradient))
if gradient.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(gradient.opacity).rounded(scale: 9))")
}
case var pattern as Pattern:
pattern.transform *= self.transform.inverse
element.setAttribute(for: "fill", value: create_pattern(pattern: pattern))
if pattern.opacity < 1 {
element.setAttribute(for: "fill-opacity", value: "\(Decimal(pattern.opacity).rounded(scale: 9))")
}
default: break
}
switch stroke.color {
case let color as Color<RGBColorModel>:
element.setAttribute(for: "stroke", value: create_color(color))
if color.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(color.opacity).rounded(scale: 9))")
}
case var gradient as Gradient<Color<RGBColorModel>>:
gradient.transform *= SDTransform.scale(x: strokePath.originalBoundary.width, y: strokePath.originalBoundary.height)
gradient.transform *= SDTransform.translate(x: strokePath.originalBoundary.minX, y: strokePath.originalBoundary.minY)
gradient.transform *= SDTransform.translate(x: shape_identity.originalBoundary.minX, y: shape_identity.originalBoundary.minY).inverse
gradient.transform *= SDTransform.scale(x: shape_identity.originalBoundary.width, y: shape_identity.originalBoundary.height).inverse
element.setAttribute(for: "stroke", value: create_gradient(gradient))
if gradient.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(gradient.opacity).rounded(scale: 9))")
}
case var pattern as Pattern:
pattern.transform *= self.transform.inverse
element.setAttribute(for: "stroke", value: create_pattern(pattern: pattern))
if pattern.opacity < 1 {
element.setAttribute(for: "stroke-opacity", value: "\(Decimal(pattern.opacity).rounded(scale: 9))")
}
default: break
}
element.setAttribute(for: "stroke-width", value: "\(Decimal(stroke.width).rounded(scale: 9))")
switch stroke.cap {
case .butt: element.setAttribute(for: "stroke-linecap", value: "butt")
case .round: element.setAttribute(for: "stroke-linecap", value: "round")
case .square: element.setAttribute(for: "stroke-linecap", value: "square")
}
switch stroke.join {
case let .miter(limit):
element.setAttribute(for: "stroke-linejoin", value: "miter")
element.setAttribute(for: "stroke-miterlimit", value: "\(Decimal(limit).rounded(scale: 9))")
case .round: element.setAttribute(for: "stroke-linejoin", value: "round")
case .bevel: element.setAttribute(for: "stroke-linejoin", value: "bevel")
}
element.setAttribute(for: "transform", value: self.transform.attributeStr())
self.append(element, shape.strokePath(stroke), true, self.transform)
}
public func draw<C1: ColorProtocol, C2: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: C1, stroke: Stroke<C2>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C1: ColorProtocol, C2>(shape: Shape, winding: Shape.WindingRule, color: C1, stroke: Stroke<Gradient<C2>>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard stroke.color.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: C, stroke: Stroke<Pattern>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard !stroke.color.bound.width.almostZero() && !stroke.color.bound.height.almostZero() && !stroke.color.xStep.almostZero() && !stroke.color.yStep.almostZero() else { return }
guard !stroke.color.bound.isEmpty && stroke.color.xStep.isFinite && stroke.color.yStep.isFinite else { return }
guard stroke.color.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C1, C2: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: Gradient<C1>, stroke: Stroke<C2>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard color.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C1, C2>(shape: Shape, winding: Shape.WindingRule, color: Gradient<C1>, stroke: Stroke<Gradient<C2>>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard color.transform.invertible else { return }
guard stroke.color.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C>(shape: Shape, winding: Shape.WindingRule, color: Gradient<C>, stroke: Stroke<Pattern>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard color.transform.invertible else { return }
guard !stroke.color.bound.width.almostZero() && !stroke.color.bound.height.almostZero() && !stroke.color.xStep.almostZero() && !stroke.color.yStep.almostZero() else { return }
guard !stroke.color.bound.isEmpty && stroke.color.xStep.isFinite && stroke.color.yStep.isFinite else { return }
guard stroke.color.transform.invertible else { return }
let color = color.convert(to: ColorSpace.sRGB, intent: renderingIntent)
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C: ColorProtocol>(shape: Shape, winding: Shape.WindingRule, color: Pattern, stroke: Stroke<C>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard !color.bound.width.almostZero() && !color.bound.height.almostZero() && !color.xStep.almostZero() && !color.yStep.almostZero() else { return }
guard !color.bound.isEmpty && color.xStep.isFinite && color.yStep.isFinite else { return }
guard color.transform.invertible else { return }
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw<C>(shape: Shape, winding: Shape.WindingRule, color: Pattern, stroke: Stroke<Gradient<C>>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard !color.bound.width.almostZero() && !color.bound.height.almostZero() && !color.xStep.almostZero() && !color.yStep.almostZero() else { return }
guard !color.bound.isEmpty && color.xStep.isFinite && color.yStep.isFinite else { return }
guard color.transform.invertible else { return }
guard stroke.color.transform.invertible else { return }
let stroke = Stroke(width: stroke.width, cap: stroke.cap, join: stroke.join, color: stroke.color.convert(to: ColorSpace.sRGB, intent: renderingIntent))
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
public func draw(shape: Shape, winding: Shape.WindingRule, color: Pattern, stroke: Stroke<Pattern>) {
guard self.transform.invertible else { return }
guard shape.contains(where: { !$0.isEmpty }) && shape.transform.invertible else { return }
guard !color.bound.width.almostZero() && !color.bound.height.almostZero() && !color.xStep.almostZero() && !color.yStep.almostZero() else { return }
guard !color.bound.isEmpty && color.xStep.isFinite && color.yStep.isFinite else { return }
guard color.transform.invertible else { return }
guard !stroke.color.bound.width.almostZero() && !stroke.color.bound.height.almostZero() && !stroke.color.xStep.almostZero() && !stroke.color.yStep.almostZero() else { return }
guard !stroke.color.bound.isEmpty && stroke.color.xStep.isFinite && stroke.color.yStep.isFinite else { return }
guard stroke.color.transform.invertible else { return }
self._draw(shape: shape, winding: winding, color: color, stroke: stroke)
}
}
extension SVGEffectElement {
fileprivate func _visible_bound(_ sources: [SVGEffect.Source: Rect], _ objectBound: Rect) -> Rect? {
guard !region.isNull else { return self.visibleBound(sources) }
switch regionUnit {
case .userSpaceOnUse: return region
case .objectBoundingBox:
let x = region.minX * objectBound.width + objectBound.minX
let y = region.minY * objectBound.height + objectBound.minY
let width = region.width * objectBound.width
let height = region.height * objectBound.height
return Rect(x: x, y: y, width: width, height: height)
}
}
}
extension SVGEffect {
fileprivate func visibleBound(_ bound: Rect, _ objectBound: Rect) -> Rect {
var accumulated = bound
return self.apply(bound) { (_, primitive, list) -> Rect? in
let destination_region = primitive._visible_bound(list, objectBound)
accumulated = destination_region?.union(accumulated) ?? accumulated
return destination_region
}?.union(accumulated) ?? accumulated
}
}
extension SVGContext {
private func _effect_element(_ type: String, _ effect: SVGEffect, _ visibleBound: inout Rect, _ objectBound: Rect) -> String? {
let id = new_name(type)
var _filter = SDXMLElement(name: "filter", attributes: ["id": id])
visibleBound = effect.visibleBound(visibleBound, objectBound)
if objectBound.width != 0 && objectBound.height != 0 {
let x = 100 * (visibleBound.minX - objectBound.minX) / objectBound.width
let y = 100 * (visibleBound.minY - objectBound.minY) / objectBound.height
let width = 100 * visibleBound.width / objectBound.width
let height = 100 * visibleBound.height / objectBound.height
let _x = floor(x)
let _y = floor(y)
let _width = _x == x ? ceil(width) : ceil(width + 1)
let _height = _y == y ? ceil(height) : ceil(height + 1)
_filter.setAttribute(for: "filterUnits", value: "objectBoundingBox")
_filter.setAttribute(for: "primitiveUnits", value: "userSpaceOnUse")
_filter.setAttribute(for: "x", value: "\(Decimal(_x).rounded(scale: 9))" + "%")
_filter.setAttribute(for: "y", value: "\(Decimal(_y).rounded(scale: 9))" + "%")
_filter.setAttribute(for: "width", value: "\(Decimal(_width).rounded(scale: 9))" + "%")
_filter.setAttribute(for: "height", value: "\(Decimal(_height).rounded(scale: 9))" + "%")
}
effect.enumerate { uuid, primitive in
var element = primitive.xml_element
element.setAttribute(for: "result", value: uuid.uuidString)
if !primitive.region.isNull {
switch primitive.regionUnit {
case .userSpaceOnUse:
element.setAttribute(for: "x", value: "\(Decimal(primitive.region.minX).rounded(scale: 9))")
element.setAttribute(for: "y", value: "\(Decimal(primitive.region.minY).rounded(scale: 9))")
element.setAttribute(for: "width", value: "\(Decimal(primitive.region.width).rounded(scale: 9))")
element.setAttribute(for: "height", value: "\(Decimal(primitive.region.height).rounded(scale: 9))")
case .objectBoundingBox:
element.setAttribute(for: "x", value: "\(Decimal(primitive.region.minX * objectBound.width + objectBound.minX).rounded(scale: 9))")
element.setAttribute(for: "y", value: "\(Decimal(primitive.region.minY * objectBound.height + objectBound.minY).rounded(scale: 9))")
element.setAttribute(for: "width", value: "\(Decimal(primitive.region.width * objectBound.width).rounded(scale: 9))")
element.setAttribute(for: "height", value: "\(Decimal(primitive.region.height * objectBound.height).rounded(scale: 9))")
}
}
_filter.append(element)
}
if let primitive = effect.output {
var element = primitive.xml_element
if !primitive.region.isNull {
switch primitive.regionUnit {
case .userSpaceOnUse:
element.setAttribute(for: "x", value: "\(Decimal(primitive.region.minX).rounded(scale: 9))")
element.setAttribute(for: "y", value: "\(Decimal(primitive.region.minY).rounded(scale: 9))")
element.setAttribute(for: "width", value: "\(Decimal(primitive.region.width).rounded(scale: 9))")
element.setAttribute(for: "height", value: "\(Decimal(primitive.region.height).rounded(scale: 9))")
case .objectBoundingBox:
element.setAttribute(for: "x", value: "\(Decimal(primitive.region.minX * objectBound.width + objectBound.minX).rounded(scale: 9))")
element.setAttribute(for: "y", value: "\(Decimal(primitive.region.minY * objectBound.height + objectBound.minY).rounded(scale: 9))")
element.setAttribute(for: "width", value: "\(Decimal(primitive.region.width * objectBound.width).rounded(scale: 9))")
element.setAttribute(for: "height", value: "\(Decimal(primitive.region.height * objectBound.height).rounded(scale: 9))")
}
}
_filter.append(element)
}
defs.append(_filter)
return id
}
}
| mit | 5bef68ac001d2d9964eeaada595d23a8 | 40.858783 | 195 | 0.593379 | 4.56365 | false | false | false | false |
guille969/Licensy | Licensy/Sources/Licenses/Model/LicenseTypes/CreativeCommonsAttributionNoDerivs30Unported.swift | 1 | 1907 | //
// CreativeCommonsAttributionNoDerivs30Unported.swift
// Licensy
//
// Created by Guillermo Garcia Rebolo on 22/2/17.
// Copyright © 2017 RetoLabs. All rights reserved.
//
/// Creative Commons Attribution-NoDerivs 3.0 Unported
public class CreativeCommonsAttributionNoDerivs30Unported: License {
fileprivate var company: String = ""
fileprivate var copyright: String = ""
/// The initializer of the license
public init() {
}
/// The identifier of the license
public var identifier: String {
get {
return "CCAND"
}
}
/// The name of the license
public var name: String {
get {
return "Creative Commons Attribution-NoDerivs 3.0 Unported"
}
}
/// The license text
public var text: String {
get {
guard let value: String = LicenseParser.getContent("ccand_30") else {
return ""
}
return value
}
}
/// The minimal license text
public var minimalText: String {
get {
guard let value: String = LicenseParser.getContent("ccand_30_minimal") else {
return ""
}
return value
}
}
/// The license version
public var version: String {
get {
return "3.0"
}
}
/// The license URL
public var url: String {
get {
return "http://creativecommons.org/licenses/by-nd/3.0"
}
}
/// Configure the company and the copyright of the library for the license
///
/// - Parameters:
/// - company: the company of the library
/// - copyright: the copyright of the library
public func formatLicenseText(with company: String, copyright: String) {
self.company = company
self.copyright = copyright
}
}
| mit | d4f11c8b494507880eeadcce9ccaea3b | 24.078947 | 89 | 0.562959 | 4.570743 | false | false | false | false |
zwaldowski/Attendant | Attendant/AssociationPolicy.swift | 1 | 1222 | //
// AssociationPolicy.swift
// Attendant
//
// Created by Zachary Waldowski on 4/16/15.
// Copyright © 2015-2016 Big Nerd Ranch. All rights reserved.
//
import ObjectiveC.runtime
public enum AssociationPolicy {
case Unowned
case Strong(atomic: Bool)
case Copying(atomic: Bool)
var runtimeValue: objc_AssociationPolicy {
switch self {
case .Strong(false): return .OBJC_ASSOCIATION_RETAIN_NONATOMIC
case .Strong(true): return .OBJC_ASSOCIATION_RETAIN
case .Copying(false): return .OBJC_ASSOCIATION_COPY_NONATOMIC
case .Copying(true): return .OBJC_ASSOCIATION_COPY
default: return .OBJC_ASSOCIATION_ASSIGN
}
}
}
extension AssociationPolicy: Hashable {
public var hashValue: Int {
return runtimeValue.hashValue
}
}
public func ==(lhs: AssociationPolicy, rhs: AssociationPolicy) -> Bool {
switch (lhs, rhs) {
case (.Unowned, .Unowned):
return true
case (.Strong(let latomic), .Strong(let ratomic)):
return latomic == ratomic
case (.Copying(let latomic), .Copying(let ratomic)):
return latomic == ratomic
default:
return false
}
}
| mit | 8f73e6bc7669b96e559330afbb2af72a | 24.4375 | 72 | 0.63964 | 4.269231 | false | false | false | false |
kiwisip/BadgeControl | BadgeControl/BadgeView.swift | 1 | 5179 | //
// BadgeView.swift
// BadgeControl
//
// Created by Robin Krenecky on 19.08.17.
// Copyright © 2017 Robin Krenecky. All rights reserved.
//
import UIKit
open class BadgeView: UIView {
// MARK: Internal properties
internal var height: CGFloat { didSet { updateUI() } }
internal var centerPoint: CGPoint { didSet { updateUI() } }
internal var text: String { didSet { updateUI() } }
internal var badgeBackgroundColor: UIColor { didSet { updateUI() } }
internal var badgeTextColor: UIColor { didSet { updateUI() } }
internal var badgeTextFont: UIFont { didSet { updateUI() } }
internal var borderWidth: CGFloat { didSet { updateUI() } }
internal var borderColor: UIColor { didSet { updateUI() } }
// MARK: Initializers
public init(height: CGFloat,
center: CGPoint,
text: String,
badgeBackgroundColor: UIColor,
badgeTextColor: UIColor,
badgeTextFont: UIFont,
borderWidth: CGFloat,
borderColor: UIColor) {
self.height = height
self.centerPoint = center
self.text = text
self.badgeBackgroundColor = badgeBackgroundColor
self.badgeTextColor = badgeTextColor
self.badgeTextFont = badgeTextFont
self.borderWidth = borderWidth
self.borderColor = borderColor
super.init(frame: CGRect(x: 0,
y: 0,
width: BadgeView.calculateWidth(height: height, borderWidth: borderWidth, text: text),
height: height))
backgroundColor = .clear
}
@available(*, unavailable, message: "Storyboard initiation is not supported.")
public required init?(coder aDecoder: NSCoder) { fatalError("Not supported") }
open override func draw(_ rect: CGRect) {
frame = CGRect(x: 0, y: 0, width: BadgeView.calculateWidth(height: height, borderWidth: borderWidth, text: text), height: height)
let height = frame.height - borderWidth
let ovalWidth = height
let rightHemisphereX = frame.width - borderWidth / 2 - height
drawOval(height, ovalWidth, rightHemisphereX)
drawText()
center = centerPoint
}
// MARK: Private methods
private static func calculateWidth(height: CGFloat, borderWidth: CGFloat, text: String) -> CGFloat {
let height = height - borderWidth * 2
let ratio = CGFloat(text.count > 0 ? text.count : 1)
return CGFloat(height + (ratio - 1) * height / 2.4) + borderWidth * 2
}
private func drawOval(_ height: CGFloat, _ ovalWidth: CGFloat, _ rightHemisphereX: CGFloat) {
var ovalPath = UIBezierPath()
addRightHemisphereArc(to: &ovalPath, rightHemisphereX, ovalWidth, height)
ovalPath.addLine(to: CGPoint(x: ovalWidth / 2, y: height + borderWidth / 2))
addLeftHemisphereArc(to: &ovalPath, frame, ovalWidth, height)
ovalPath.close()
badgeBackgroundColor.setFill()
ovalPath.fill()
borderColor.setStroke()
ovalPath.lineWidth = borderWidth
ovalPath.stroke()
}
private func addRightHemisphereArc(to path: inout UIBezierPath, _ rightHemisphereX: CGFloat, _ ovalWidth: CGFloat, _ height: CGFloat) {
let rightHemisphereRect = CGRect(x: rightHemisphereX, y: borderWidth / 2, width: ovalWidth, height: height)
path.addArc(withCenter: CGPoint(x: rightHemisphereRect.midX, y: rightHemisphereRect.midY),
radius: rightHemisphereRect.width / 2,
startAngle: -90 * CGFloat.pi / 180,
endAngle: -270 * CGFloat.pi / 180,
clockwise: true)
}
private func addLeftHemisphereArc(to path: inout UIBezierPath, _ frame: CGRect, _ ovalWidth: CGFloat, _ height: CGFloat) {
let leftHemisphereRect = CGRect(x: frame.minX + borderWidth / 2, y: frame.minY + borderWidth / 2, width: ovalWidth, height: height)
path.addArc(withCenter: CGPoint(x: leftHemisphereRect.midX, y: leftHemisphereRect.midY),
radius: leftHemisphereRect.width / 2,
startAngle: -270 * CGFloat.pi / 180,
endAngle: -90 * CGFloat.pi / 180,
clockwise: true)
}
private func drawText() {
let textRect = frame
let textTextContent = text
let textStyle = NSMutableParagraphStyle()
textStyle.alignment = .center
let textFontAttributes = [
.font: badgeTextFont,
.foregroundColor: badgeTextColor,
.paragraphStyle: textStyle,
] as [NSAttributedString.Key: Any]
let textTextHeight: CGFloat = textTextContent.boundingRect(with: CGSize(width: textRect.width, height: CGFloat.infinity),
options: .usesLineFragmentOrigin,
attributes: textFontAttributes,
context: nil).height
textTextContent.draw(in: CGRect(x: textRect.minX, y: textRect.minY + (textRect.height - textTextHeight) / 2,
width: textRect.width,
height: textTextHeight),
withAttributes: textFontAttributes)
}
private func updateUI() {
setNeedsDisplay()
}
}
| mit | ac54e5aae731057ee973cc36113f903f | 37.073529 | 137 | 0.634608 | 4.861972 | false | false | false | false |
to4iki/conference-app-2017-ios | conference-app-2017/presentation/view/timetable/DateTitleCell.swift | 1 | 1034 | import UIKit
import SpreadsheetView
import OctavKit
final class DateTitleCell: Cell {
fileprivate let label = UILabel()
static let IntervalMinutes: Int = 300
override init(frame: CGRect) {
super.init(frame: frame)
commonInit()
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
commonInit()
}
private func commonInit() {
backgroundColor = UIColor.Builderscon.lightGray
label.textColor = .black
label.frame = bounds
label.autoresizingMask = [.flexibleWidth, .flexibleHeight]
label.font = UIFont.systemFont(ofSize: 12)
label.textAlignment = .center
gridlines.top = .solid(width: 1, color: .black)
gridlines.bottom = gridlines.top
gridlines.right = .solid(width: 1, color: .black)
gridlines.left = gridlines.right
addSubview(label)
}
}
extension DateTitleCell {
func setup(date: Date) {
label.text = date.string(format: .custom("HH:mm"))
}
}
| apache-2.0 | 02b574d0da17761eedc89b45be354bf2 | 25.512821 | 66 | 0.637331 | 4.308333 | false | false | false | false |
Johennes/firefox-ios | ThirdParty/FilledPageControl.swift | 1 | 4742 | // FilledPageControl
//
// Copyright (c) 2016 Kyle Zaragoza <[email protected]>
// MIT License
import UIKit
@IBDesignable public class FilledPageControl: UIView {
// MARK: - PageControl
@IBInspectable public var pageCount: Int = 0 {
didSet {
updateNumberOfPages(pageCount)
}
}
@IBInspectable public var progress: CGFloat = 0 {
didSet {
updateActivePageIndicatorMasks(progress)
}
}
public var currentPage: Int {
return Int(round(progress))
}
// MARK: - Appearance
override public var tintColor: UIColor! {
didSet {
inactiveLayers.forEach() { $0.backgroundColor = tintColor.CGColor }
}
}
@IBInspectable public var inactiveRingWidth: CGFloat = 1 {
didSet {
updateActivePageIndicatorMasks(progress)
}
}
@IBInspectable public var indicatorPadding: CGFloat = 10 {
didSet {
layoutPageIndicators(inactiveLayers)
}
}
@IBInspectable public var indicatorRadius: CGFloat = 5 {
didSet {
layoutPageIndicators(inactiveLayers)
}
}
private var indicatorDiameter: CGFloat {
return indicatorRadius * 2
}
private var inactiveLayers = [CALayer]()
// MARK: - State Update
private func updateNumberOfPages(count: Int) {
// no need to update
guard count != inactiveLayers.count else { return }
// reset current layout
inactiveLayers.forEach() { $0.removeFromSuperlayer() }
inactiveLayers = [CALayer]()
// add layers for new page count
inactiveLayers = 0.stride(to:count, by:1).map() { _ in
let layer = CALayer()
layer.backgroundColor = self.tintColor.CGColor
self.layer.addSublayer(layer)
return layer
}
layoutPageIndicators(inactiveLayers)
updateActivePageIndicatorMasks(progress)
self.invalidateIntrinsicContentSize()
}
// MARK: - Layout
private func updateActivePageIndicatorMasks(progress: CGFloat) {
// ignore if progress is outside of page indicators' bounds
guard progress >= 0 && progress <= CGFloat(pageCount - 1) else { return }
// mask rect w/ default stroke width
let insetRect = CGRectInset(
CGRect(x: 0, y: 0, width: indicatorDiameter, height: indicatorDiameter),
inactiveRingWidth, inactiveRingWidth)
let leftPageFloat = trunc(progress)
let leftPageInt = Int(progress)
// inset right moving page indicator
let spaceToMove = insetRect.width / 2
let percentPastLeftIndicator = progress - leftPageFloat
let additionalSpaceToInsetRight = spaceToMove * percentPastLeftIndicator
let closestRightInsetRect = CGRectInset(insetRect, additionalSpaceToInsetRight, additionalSpaceToInsetRight)
// inset left moving page indicator
let additionalSpaceToInsetLeft = (1 - percentPastLeftIndicator) * spaceToMove
let closestLeftInsetRect = CGRectInset(insetRect, additionalSpaceToInsetLeft, additionalSpaceToInsetLeft)
// adjust masks
for (idx, layer) in inactiveLayers.enumerate() {
let maskLayer = CAShapeLayer()
maskLayer.fillRule = kCAFillRuleEvenOdd
let boundsPath = UIBezierPath(rect: layer.bounds)
let circlePath: UIBezierPath
if leftPageInt == idx {
circlePath = UIBezierPath(ovalInRect: closestLeftInsetRect)
} else if leftPageInt + 1 == idx {
circlePath = UIBezierPath(ovalInRect: closestRightInsetRect)
} else {
circlePath = UIBezierPath(ovalInRect: insetRect)
}
boundsPath.appendPath(circlePath)
maskLayer.path = boundsPath.CGPath
layer.mask = maskLayer
}
}
private func layoutPageIndicators(layers: [CALayer]) {
let layerDiameter = indicatorRadius * 2
var layerFrame = CGRect(x: 0, y: 0, width: layerDiameter, height: layerDiameter)
layers.forEach() { layer in
layer.cornerRadius = self.indicatorRadius
layer.frame = layerFrame
layerFrame.origin.x += layerDiameter + indicatorPadding
}
}
override public func intrinsicContentSize() -> CGSize {
return sizeThatFits(CGSize.zero)
}
override public func sizeThatFits(size: CGSize) -> CGSize {
let layerDiameter = indicatorRadius * 2
return CGSize(width: CGFloat(inactiveLayers.count) * layerDiameter + CGFloat(inactiveLayers.count - 1) * indicatorPadding,
height: layerDiameter)
}
} | mpl-2.0 | de4e232d231b58e04488d269fd86e331 | 33.122302 | 130 | 0.635386 | 5.32809 | false | false | false | false |
linkedin/ConsistencyManager-iOS | ConsistencyManagerTests/HelperClasses/ProjectionTestModel.swift | 2 | 4225 | // © 2016 LinkedIn Corp. 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.
import Foundation
import ConsistencyManager
/**
This model is intended for unit testing the consistency manager. It simply declares some child objects and some data.
It is similar to TestModel but declares an extra field.
Therefore, it also implements mergeModel which will merge TestModel into this model.
*/
final class ProjectionTestModel: ConsistencyManagerModel, Equatable {
let id: String?
let data: Int?
let otherData: Int?
let children: [ProjectionTestModel]
let requiredModel: TestRequiredModel
init(id: String?, data: Int?, otherData: Int?, children: [ProjectionTestModel], requiredModel: TestRequiredModel) {
self.id = id
self.data = data
self.otherData = otherData
self.children = children
self.requiredModel = requiredModel
}
var modelIdentifier: String? {
return id
}
func map(_ transform: (ConsistencyManagerModel) -> ConsistencyManagerModel?) -> ConsistencyManagerModel? {
var newChildren: [ProjectionTestModel] = []
for model in children {
if let newModel = transform(model) as? ProjectionTestModel {
newChildren.append(newModel)
}
}
if let newRequiredModel = transform(requiredModel) as? TestRequiredModel {
return ProjectionTestModel(id: id, data: data, otherData: otherData, children: newChildren, requiredModel: newRequiredModel)
} else {
return nil
}
}
func forEach(_ function: (ConsistencyManagerModel) -> Void) {
for model in children {
function(model)
}
function(requiredModel)
}
func mergeModel(_ model: ConsistencyManagerModel) -> ConsistencyManagerModel {
if let model = model as? ProjectionTestModel {
return model
} else if let model = model as? TestModel {
return testModelFromProjection(model)
} else {
assertionFailure("Tried to merge two models which cannot be merged: \(type(of: self)) and \(type(of: model))")
// The best we can do is return self (no merging done)
return self
}
}
fileprivate func testModelFromProjection(_ model: TestModel) -> ProjectionTestModel {
let newChildren = model.children.map { currentChild in
return testModelFromProjection(currentChild)
}
// For otherData, we're going to use our current value. For everything else, we're going to use the other model's values.
return ProjectionTestModel(id: model.id, data: model.data, otherData: otherData, children: newChildren, requiredModel: model.requiredModel)
}
}
// MARK - Equatable
func ==(lhs: ProjectionTestModel, rhs: ProjectionTestModel) -> Bool {
return lhs.id == rhs.id
&& lhs.data == rhs.data
&& lhs.otherData == rhs.otherData
&& lhs.children == rhs.children
&& lhs.requiredModel == rhs.requiredModel
}
// MARK - CustomStringConvertible
extension ProjectionTestModel: CustomStringConvertible {
var description: String {
return "\(String(describing: id)):\(String(describing: data)):\(String(describing: otherData))-\(requiredModel)-\(children)"
}
}
// MARK - Helpers
extension ProjectionTestModel {
func recursiveChildWithId(_ id: String) -> ProjectionTestModel? {
if let currentId = self.id {
if currentId == id {
return self
}
}
for child in children {
let foundModel = child.recursiveChildWithId(id)
if let foundModel = foundModel {
return foundModel
}
}
// We didn't find anything
return nil
}
}
| apache-2.0 | 29313419b6b507646bb336677852c689 | 34.79661 | 147 | 0.655303 | 4.928821 | false | true | false | false |
cecgsn/BWSwipeRevealCell | BWSwipeRevealCellExample/MasterViewController.swift | 1 | 7529 | //
// MasterViewController.swift
// BWSwipeTableCellExample
//
// Created by Kyle Newsome on 2015-11-12.
// Copyright © 2015 Kyle Newsome. All rights reserved.
//
import UIKit
import CoreData
import BWSwipeRevealCell
class MasterViewController: UITableViewController, NSFetchedResultsControllerDelegate, BWSwipeRevealCellDelegate {
var managedObjectContext: NSManagedObjectContext? = nil
override func viewDidLoad() {
super.viewDidLoad()
let addButton = UIBarButtonItem(barButtonSystemItem: .Add, target: self, action: #selector(MasterViewController.insertNewObject(_:)))
self.navigationItem.rightBarButtonItem = addButton
}
func insertNewObject(sender: AnyObject) {
let context = self.fetchedResultsController.managedObjectContext
let entity = self.fetchedResultsController.fetchRequest.entity!
//Create one of each type
for i in 0..<3 {
let newManagedObject = NSEntityDescription.insertNewObjectForEntityForName(entity.name!, inManagedObjectContext: context)
newManagedObject.setValue(i, forKey: "type")
}
do {
try context.save()
} catch {
abort()
}
}
func removeObjectAtIndexPath(indexPath:NSIndexPath) {
let context = self.fetchedResultsController.managedObjectContext
//Deleting objects regardless of done/delete for the purpose of this example
context.deleteObject(self.fetchedResultsController.objectAtIndexPath(indexPath) as! NSManagedObject)
do {
try context.save()
} catch {
abort()
}
}
// MARK: - Table View
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
return 72
}
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return self.fetchedResultsController.sections?.count ?? 0
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
let sectionInfo = self.fetchedResultsController.sections![section]
return sectionInfo.numberOfObjects
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
self.configureCell(cell, atIndexPath: indexPath)
return cell
}
func configureCell(cell: UITableViewCell, atIndexPath indexPath: NSIndexPath) {
let object = self.fetchedResultsController.objectAtIndexPath(indexPath)
let swipeCell:BWSwipeRevealCell = cell as! BWSwipeRevealCell
swipeCell.bgViewLeftImage = UIImage(named:"Done")!.imageWithRenderingMode(.AlwaysTemplate)
swipeCell.bgViewLeftColor = UIColor.greenColor()
swipeCell.bgViewRightImage = UIImage(named:"Delete")!.imageWithRenderingMode(.AlwaysTemplate)
swipeCell.bgViewRightColor = UIColor.redColor()
let type = BWSwipeCellType(rawValue: object.valueForKey("type") as! Int)
swipeCell.type = type
switch type {
case .SwipeThrough:
swipeCell.textLabel!.text = "Swipe Through"
break
case .SpringRelease:
swipeCell.textLabel!.text = "Spring Release"
break
case .SlidingDoor:
swipeCell.textLabel!.text = "Sliding Door"
break
}
swipeCell.delegate = self
}
// MARK: - Fetched results controller
var fetchedResultsController: NSFetchedResultsController {
if _fetchedResultsController != nil {
return _fetchedResultsController!
}
let fetchRequest = NSFetchRequest()
let entity = NSEntityDescription.entityForName("Event", inManagedObjectContext: self.managedObjectContext!)
fetchRequest.entity = entity
fetchRequest.fetchBatchSize = 20
let sortDescriptor = NSSortDescriptor(key: "type", ascending: false)
fetchRequest.sortDescriptors = [sortDescriptor]
let aFetchedResultsController = NSFetchedResultsController(fetchRequest: fetchRequest, managedObjectContext: self.managedObjectContext!, sectionNameKeyPath: nil, cacheName: "Master")
aFetchedResultsController.delegate = self
_fetchedResultsController = aFetchedResultsController
do {
try _fetchedResultsController!.performFetch()
} catch {
abort()
}
return _fetchedResultsController!
}
var _fetchedResultsController: NSFetchedResultsController? = nil
func controllerWillChangeContent(controller: NSFetchedResultsController) {
self.tableView.beginUpdates()
}
func controller(controller: NSFetchedResultsController, didChangeSection sectionInfo: NSFetchedResultsSectionInfo, atIndex sectionIndex: Int, forChangeType type: NSFetchedResultsChangeType) {
switch type {
case .Insert:
self.tableView.insertSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
case .Delete:
self.tableView.deleteSections(NSIndexSet(index: sectionIndex), withRowAnimation: .Fade)
default:
return
}
}
func controller(controller: NSFetchedResultsController, didChangeObject anObject: AnyObject, atIndexPath indexPath: NSIndexPath?, forChangeType type: NSFetchedResultsChangeType, newIndexPath: NSIndexPath?) {
switch type {
case .Insert:
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
case .Delete:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
case .Update:
self.configureCell(tableView.cellForRowAtIndexPath(indexPath!)!, atIndexPath: indexPath!)
case .Move:
tableView.deleteRowsAtIndexPaths([indexPath!], withRowAnimation: .Fade)
tableView.insertRowsAtIndexPaths([newIndexPath!], withRowAnimation: .Fade)
}
}
func controllerDidChangeContent(controller: NSFetchedResultsController) {
self.tableView.endUpdates()
}
// MARK: - Reveal Cell Delegate
func swipeCellWillRelease(cell: BWSwipeCell) {
print("Swipe Cell Will Release")
if cell.state != .Normal && cell.type != .SlidingDoor {
let indexPath: NSIndexPath = tableView.indexPathForCell(cell)!
self.removeObjectAtIndexPath(indexPath)
}
}
func swipeCellActivatedAction(cell: BWSwipeCell, isActionLeft: Bool) {
print("Swipe Cell Activated Action")
let indexPath: NSIndexPath = tableView.indexPathForCell(cell)!
self.removeObjectAtIndexPath(indexPath)
}
func swipeCellDidChangeState(cell: BWSwipeCell) {
print("Swipe Cell Did Change State")
if cell.state != .Normal {
print("-> Cell Passed Threshold")
} else {
print("-> Cell Returned to Normal")
}
}
func swipeCellDidCompleteRelease(cell: BWSwipeCell) {
print("Swipe Cell Did Complete Release")
}
func swipeCellDidSwipe(cell: BWSwipeCell) {
print("Swipe Cell Did Swipe")
}
func swipeCellDidStartSwiping(cell: BWSwipeCell) {
print("Swipe Cell Did Start Swiping")
}
}
| mit | f5d48f6738896b1e01f148dd26562893 | 37.020202 | 211 | 0.67043 | 6.0224 | false | false | false | false |
ifLab/WeCenterMobile-iOS | WeCenterMobile/View/Answer/AnswerCell.swift | 3 | 2180 | //
// AnswerCell.swift
// WeCenterMobile
//
// Created by Darren Liu on 15/3/29.
// Copyright (c) 2015年 Beijing Information Science and Technology University. All rights reserved.
//
import UIKit
class AnswerCell: UITableViewCell {
var answer: Answer?
@IBOutlet weak var userNameLabel: UILabel!
@IBOutlet weak var answerBodyLabel: MSRMultilineLabel!
@IBOutlet weak var userAvatarView: MSRRoundedImageView!
@IBOutlet weak var agreementCountLabel: UILabel!
@IBOutlet weak var userButton: UIButton!
@IBOutlet weak var answerButton: UIButton!
@IBOutlet weak var separator: UIView!
@IBOutlet weak var containerView: UIView!
@IBOutlet weak var userContainerView: UIView!
@IBOutlet weak var answerContainerView: UIView!
override func awakeFromNib() {
super.awakeFromNib()
msr_scrollView?.delaysContentTouches = false
let theme = SettingsManager.defaultManager.currentTheme
for v in [containerView, agreementCountLabel] {
v.msr_borderColor = theme.borderColorA
}
for v in [userButton, answerButton] {
v.msr_setBackgroundImageWithColor(theme.highlightColor, forState: .Highlighted)
}
for v in [agreementCountLabel, answerBodyLabel] {
v.textColor = theme.subtitleTextColor
}
for v in [userContainerView, answerContainerView] {
v.backgroundColor = theme.backgroundColorB
}
agreementCountLabel.backgroundColor = theme.backgroundColorA
separator.backgroundColor = theme.borderColorA
userNameLabel.textColor = theme.titleTextColor
}
func update(answer answer: Answer, updateImage: Bool) {
self.answer = answer
userNameLabel.text = answer.user?.name ?? "匿名用户"
answerBodyLabel.text = answer.body?.wc_plainString
agreementCountLabel.text = "\(answer.agreementCount ?? 0)"
userButton.msr_userInfo = answer.user
answerButton.msr_userInfo = answer
if updateImage {
userAvatarView.wc_updateWithUser(answer.user)
}
setNeedsLayout()
layoutIfNeeded()
}
}
| gpl-2.0 | d6862e005c8ca1a2c356e576ba6fd0c5 | 34.57377 | 99 | 0.679724 | 5.081967 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-x | Source/JsonWebToken/AccessProviders/CallbackJwtProvider.swift | 2 | 4301 | //
// Copyright (C) 2015-2021 Virgil Security Inc.
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are
// met:
//
// (1) Redistributions of source code must retain the above copyright
// notice, this list of conditions and the following disclaimer.
//
// (2) Redistributions in binary form must reproduce the above copyright
// notice, this list of conditions and the following disclaimer in
// the documentation and/or other materials provided with the
// distribution.
//
// (3) Neither the name of the copyright holder nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''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 AUTHOR 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.
//
// Lead Maintainer: Virgil Security Inc. <[email protected]>
//
import Foundation
// swiftlint:disable trailing_closure
/// Implementation of AccessTokenProvider which provides AccessToken using callback
@objc(VSSCallbackJwtProvider) open class CallbackJwtProvider: NSObject, AccessTokenProvider {
/// Callback, which takes a TokenContext and completion handler
/// Completion handler should be called with either JWT, or Error
@objc public let getJwtCallback: (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void
/// Initializer
///
/// - Parameter getJwtCallback: Callback, which takes a TokenContext and completion handler
/// Completion handler should be called with either JWT, or Error
@objc public init(getJwtCallback: @escaping (TokenContext, @escaping (Jwt?, Error?) -> Void) -> Void) {
self.getJwtCallback = getJwtCallback
super.init()
}
/// Typealias for callback used below
public typealias JwtStringCallback = (String?, Error?) -> Void
/// Typealias for callback used below
public typealias RenewJwtCallback = (TokenContext, @escaping JwtStringCallback) -> Void
/// Initializer
///
/// - Parameter getTokenCallback: Callback, which takes a TokenContext and completion handler
/// Completion handler should be called with either JWT string, or Error
@objc public convenience init(getTokenCallback: @escaping RenewJwtCallback) {
self.init(getJwtCallback: { ctx, completion in
getTokenCallback(ctx) { string, error in
do {
guard let string = string, error == nil else {
completion(nil, error)
return
}
completion(try Jwt(stringRepresentation: string), nil)
}
catch {
completion(nil, error)
}
}
})
}
/// Typealias for callback used below
public typealias AccessTokenCallback = (AccessToken?, Error?) -> Void
/// Provides access token using callback
///
/// - Parameters:
/// - tokenContext: `TokenContext` provides context explaining why token is needed
/// - completion: completion closure
@objc public func getToken(with tokenContext: TokenContext, completion: @escaping AccessTokenCallback) {
self.getJwtCallback(tokenContext) { token, err in
guard let token = token, err == nil else {
completion(nil, err)
return
}
completion(token, nil)
}
}
}
// swiftlint:enable trailing_closure
| bsd-3-clause | be56cfdde297c41b7eb232729f64a56b | 40.355769 | 108 | 0.666357 | 5.108076 | false | false | false | false |
ashfurrow/RxSwift | RxTests/RxCocoaTests/ControlPropertyTests.swift | 2 | 1264 | //
// ControlPropertyTests.swift
// RxTests
//
// Created by Krunoslav Zaher on 12/6/15.
//
//
import Foundation
import XCTest
import RxCocoa
import RxSwift
class ControlPropertyTests : RxTest {
func testObservingIsAlwaysHappeningOnMainThread() {
let hotObservable = MainThreadPrimitiveHotObservable<Int>()
var observedOnMainThread = false
let expectSubscribeOffMainThread = expectationWithDescription("Did subscribe off main thread")
let controlProperty = ControlProperty(values: deferred { () -> Observable<Int> in
XCTAssertTrue(NSThread.isMainThread())
observedOnMainThread = true
return hotObservable.asObservable()
}, valueSink: AnyObserver { n in
})
doOnBackgroundThread {
let d = controlProperty.asObservable().subscribe { n in
}
let d2 = controlProperty.subscribe { n in
}
doOnMainThread {
d.dispose()
d2.dispose()
expectSubscribeOffMainThread.fulfill()
}
}
waitForExpectationsWithTimeout(1.0) { error in
XCTAssertNil(error)
}
XCTAssertTrue(observedOnMainThread)
}
} | mit | be0735c255a724afb4d2d716c012315b | 24.3 | 102 | 0.614715 | 5.59292 | false | true | false | false |
rcgilbert/Kava | Kava/Kava/Source/PageObjects/Infrastructure/Elements/CollectionView.swift | 1 | 5023 | //
// CollectionView.swift
// Kava
//
// Created by John Hammerlund on 3/9/16.
// Copyright © 2016 MINDBODY, Inc. All rights reserved.
//
import Foundation
import XCTest
public enum ScrollDirection {
case horizontal
case vertical
}
/**
A collection view, which could be a table view. The provided generic argument
allows us to infer the proceeding block, defaulted to scope of the application
*/
open class CollectionView<TResultBlock : Block> : Element {
public typealias TResultBlockBuilder = (() -> TResultBlock)?
fileprivate let scrollDirection: ScrollDirection
open var visibleCells: [Swipeable<TResultBlock>] {
get {
return self.backingElement.cells.allElementsBoundByIndex.map {
return Swipeable(parentBlock: self.parentBlock, backingElement: $0)
}
}
}
public init(scrollDirection: ScrollDirection, parentBlock: Block, backingElement: XCUIElement) {
self.scrollDirection = scrollDirection
super.init(parentBlock: parentBlock, backingElement: backingElement)
}
public required convenience init(parentBlock: Block, backingElement: XCUIElement) {
self.init(scrollDirection: .vertical, parentBlock: parentBlock, backingElement: backingElement)
}
//MARK: Scrolling
fileprivate func scrollWithFunc<TCustomResultBlock : Block>(_ scrollFunction: (() -> Void), predicate: NSPredicate, timeout: TimeInterval, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock {
let endTimestamp = Date.timeIntervalSinceReferenceDate + timeout
while(!predicate.evaluate(with: nil) && Date.timeIntervalSinceReferenceDate < endTimestamp) {
scrollFunction()
}
return self.parentBlock.scopeTo(TCustomResultBlock.self, builder: builder)
}
open func scrollForwardUntil(_ predicate: NSPredicate, timeout: TimeInterval = 5, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock {
return self.scrollForwardUntil(predicate, timeout: timeout, result: TResultBlock.self, constructingBlock: builder)
}
open func scrollForwardUntil<TCustomResultBlock : Block>(_ predicate: NSPredicate, timeout: TimeInterval = 5, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock {
let scrollForwardFunction = self.scrollDirection == .vertical ? self.backingElement.swipeUp : self.backingElement.swipeRight
return self.scrollWithFunc(scrollForwardFunction, predicate: predicate, timeout: timeout, result: result, constructingBlock: builder)
}
open func scrollForwardUntil(_ block: @escaping (() -> Bool), timeout: TimeInterval = 5, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock {
return self.scrollForwardUntil(block, timeout: timeout, result: TResultBlock.self, constructingBlock: builder)
}
open func scrollForwardUntil<TCustomResultBlock : Block>(_ block: @escaping (() -> Bool), timeout: TimeInterval = 5, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock {
let predicate = NSPredicate { _ in
return block()
}
return self.scrollForwardUntil(predicate, timeout: timeout, result: result, constructingBlock: builder)
}
open func scrollBackwardsUntil(_ predicate: NSPredicate, timeout: TimeInterval = 5, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock {
return self.scrollBackwardsUntil(predicate, timeout: timeout, result: TResultBlock.self, constructingBlock: builder)
}
open func scrollBackwardsUntil<TCustomResultBlock : Block>(_ predicate: NSPredicate, timeout: TimeInterval = 5, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock {
let scrollForwardFunction = self.scrollDirection == .vertical ? self.backingElement.swipeDown : self.backingElement.swipeLeft
return self.scrollWithFunc(scrollForwardFunction, predicate: predicate, timeout: timeout, result: result, constructingBlock: builder)
}
open func scrollBackwardsUntil(_ block: @escaping (() -> Bool), timeout: TimeInterval = 5, constructingBlock builder: TResultBlockBuilder = nil) -> TResultBlock {
return self.scrollBackwardsUntil(block, timeout: timeout, result: TResultBlock.self, constructingBlock: builder)
}
open func scrollBackwardsUntil<TCustomResultBlock : Block>(_ block: @escaping (() -> Bool), timeout: TimeInterval = 5, result: TCustomResultBlock.Type, constructingBlock builder: (() -> TCustomResultBlock)? = nil) -> TCustomResultBlock {
let predicate = NSPredicate { _ in
return block()
}
return self.scrollBackwardsUntil(predicate, timeout: timeout, result: result, constructingBlock: builder)
}
}
| apache-2.0 | 2cfbf762a0c6e2cdf0f77da41d4d37bf | 52.425532 | 261 | 0.720231 | 5.446855 | false | false | false | false |
mauriciosantos/Buckets-Swift | Source/Multimap.swift | 3 | 7383 | //
// Multimap.swift
// Buckets
//
// Created by Mauricio Santos on 4/1/15.
// Copyright (c) 2015 Mauricio Santos. All rights reserved.
//
import Foundation
/// A Multimap is a special kind of dictionary in which each key may be
/// associated with multiple values. This implementation allows duplicate key-value pairs.
///
/// Comforms to `Sequence`, `ExpressibleByDictionaryLiteral`,
/// `Equatable` and `CustomStringConvertible`
public struct Multimap<Key: Hashable, Value: Equatable> {
// MARK: Creating a Multimap
/// Constructs an empty multimap.
public init() {}
/// Constructs a multimap from a dictionary.
public init(_ elements: Dictionary<Key, Value>) {
for (key ,value) in elements {
insertValue(value, forKey: key)
}
}
// MARK: Querying a Multimap
/// Number of key-value pairs stored in the multimap.
public fileprivate(set) var count = 0
/// Number of distinct keys stored in the multimap.
public var keyCount: Int {
return dictionary.count
}
/// Returns `true` if and only if `count == 0`.
public var isEmpty: Bool {
return count == 0
}
/// A sequence containing the multimap's unique keys.
public var keys: AnySequence<Key> {
return AnySequence(dictionary.keys)
}
/// A sequence containing the multimap's values.
public var values: AnySequence<Value> {
let selfIterator = makeIterator()
let valueIterator = AnyIterator { selfIterator.next()?.1 }
return AnySequence(valueIterator)
}
/// Returns an array containing the values associated with the specified key.
/// An empty array is returned if the key does not exist in the multimap.
public subscript(key: Key) -> [Value] {
if let values = dictionary[key] {
return values
}
return []
}
/// Returns `true` if the multimap contains at least one key-value pair with the given key.
public mutating func containsKey(_ key: Key) -> Bool {
return dictionary[key] != nil
}
/// Returns `true` if the multimap contains at least one key-value pair with the given key and value.
public func containsValue(_ value: Value, forKey key: Key) -> Bool {
if let values = dictionary[key] {
return values.contains(value)
}
return false
}
// MARK: Accessing and Changing Multimap Elements
/// Inserts a key-value pair into the multimap.
public mutating func insertValue(_ value: Value, forKey key: Key) {
insertValues([value], forKey: key)
}
/// Inserts multiple key-value pairs into the multimap.
///
/// - parameter values: A sequence of values to associate with the given key
public mutating func insertValues<S:Sequence>(_ values: S, forKey key: Key) where S.Iterator.Element == Value {
var result = dictionary[key] ?? []
let originalSize = result.count
result += values
count += result.count - originalSize
if !result.isEmpty {
dictionary[key] = result
}
}
/// Replaces all the values associated with a given key.
/// If the key does not exist in the multimap, the values are inserted.
///
/// - parameter values: A sequence of values to associate with the given key
public mutating func replaceValues<S:Sequence>(_ values: S, forKey key: Key) where S.Iterator.Element == Value {
removeValuesForKey(key)
insertValues(values, forKey: key)
}
/// Removes a single key-value pair with the given key and value from the multimap, if it exists.
///
/// - returns: The removed value, or nil if no matching pair is found.
@discardableResult
public mutating func removeValue(_ value: Value, forKey key: Key) -> Value? {
if var values = dictionary[key] {
if let removeIndex = values.index(of: value) {
let removedValue = values.remove(at: removeIndex)
count -= 1
dictionary[key] = values
return removedValue
}
if values.isEmpty {
dictionary.removeValue(forKey: key)
}
}
return nil
}
/// Removes all values associated with the given key.
public mutating func removeValuesForKey(_ key: Key) {
if let values = dictionary.removeValue(forKey: key) {
count -= values.count
}
}
/// Removes all the elements from the multimap, and by default
/// clears the underlying storage buffer.
public mutating func removeAll(keepingCapacity keep: Bool = true) {
dictionary.removeAll(keepingCapacity: keep)
count = 0
}
// MARK: Private Properties and Helper Methods
/// Internal dictionary holding the elements.
fileprivate var dictionary = [Key: [Value]]()
}
extension Multimap: Sequence {
// MARK: SequenceType Protocol Conformance
/// Provides for-in loop functionality.
///
/// - returns: A generator over the elements.
public func makeIterator() -> AnyIterator<(Key,Value)> {
var keyValueGenerator = dictionary.makeIterator()
var index = 0
var pairs = keyValueGenerator.next()
return AnyIterator {
if let tuple = pairs {
let value = tuple.1[index]
index += 1
if index >= tuple.1.count {
index = 0
pairs = keyValueGenerator.next()
}
return (tuple.0, value)
}
return nil
}
}
}
extension Multimap: ExpressibleByDictionaryLiteral {
// MARK: DictionaryLiteralConvertible Protocol Conformance
/// Constructs a multiset using a dictionary literal.
/// Unlike a set, multiple copies of an element are inserted.
public init(dictionaryLiteral elements: (Key, Value)...) {
self.init()
for (key, value) in elements {
insertValue(value, forKey: key)
}
}
}
extension Multimap: CustomStringConvertible {
// MARK: CustomStringConvertible Protocol Conformance
/// A string containing a suitable textual
/// representation of the multimap.
public var description: String {
return "[" + map{"\($0.0): \($0.1)"}.joined(separator: ", ") + "]"
}
}
extension Multimap: Equatable {
// MARK: Multimap Equatable Conformance
/// Returns `true` if and only if the multimaps contain the same key-value pairs.
public static func ==<Key, Value>(lhs: Multimap<Key, Value>, rhs: Multimap<Key, Value>) -> Bool {
if lhs.count != rhs.count || lhs.keyCount != rhs.keyCount {
return false
}
for (key, _) in lhs {
let leftValues = lhs[key]
var rightValues = rhs[key]
if leftValues.count != rightValues.count {
return false
}
for element in leftValues {
if let index = rightValues.index(of: element) {
rightValues.remove(at: index)
}
}
if !rightValues.isEmpty {
return false
}
}
return true
}
}
| mit | 6b5947f85d34fbf5d2af66cc495f35d5 | 31.524229 | 116 | 0.597183 | 4.828646 | false | false | false | false |
na4lapy/na4lapy-ios | Na4Łapy/Model/AnimalURLBuilder.swift | 1 | 2367 | //
// AnimalURLBuilder.swift
// Na4Łapy
//
// Created by mac on 15/09/2016.
// Copyright © 2016 Stowarzyszenie Na4Łapy. All rights reserved.
//
import Foundation
class AnimalURLBuilder: URLBuildable {
static func buildURLFrom(baseUrl: String, page: Int, pageSize: Int, params: UserPreferences?) -> String {
var url = baseUrl + "?page=\(page)&size=\(pageSize)"
guard let preferencesParams = params?.dictionaryRepresentation() else {
//NO PARAMS PROVIDED
return url
}
var spieciesParams = [String]()
var genderParams = [String]()
var sizeParams = [String]()
var activitiesParams = [String]()
for (paramKey, paramValue) in preferencesParams {
switch paramKey {
case Species.dog.rawValue, Species.cat.rawValue, Species.other.rawValue:
if paramValue != 0 {
spieciesParams.append(paramKey)
}
case Gender.female.rawValue, Gender.male.rawValue:
if paramValue != 0 {
genderParams.append(paramKey)
}
case Size.small.rawValue, Size.medium.rawValue, Size.large.rawValue:
if paramValue != 0 {
sizeParams.append(paramKey)
}
case Activity.low.rawValue, Activity.high.rawValue:
if paramValue != 0 {
activitiesParams.append(paramKey)
}
case ageBoundaries.ageMax.rawValue, ageBoundaries.ageMin.rawValue:
url += "&\(paramKey)=\(paramValue)"
default:
break
}
}
if (!spieciesParams.isEmpty) {
let joinedParams = spieciesParams.joined(separator: ",")
url += "&spiecies=\(joinedParams)"
}
if (!genderParams.isEmpty) {
let joinedParams = genderParams.joined(separator: ",")
url += "&genders=\(joinedParams)"
}
if (!sizeParams.isEmpty) {
let joinedParams = sizeParams.joined(separator: ",")
url += "&sizes=\(joinedParams)"
}
if (!activitiesParams.isEmpty) {
let joinedParams = sizeParams.joined(separator: ",")
url += "&activities=\(joinedParams)"
}
return url
}
}
| apache-2.0 | 3c463309ed2258f027453f811e173191 | 30.945946 | 109 | 0.547377 | 4.785425 | false | false | false | false |
sessionm/ios-smp-example | Offers/My Offers/ClaimUserOfferViewController.swift | 1 | 2670 | //
// ClaimUserOfferViewController.swift
// Offers
//
// Copyright © 2018 SessionM. All rights reserved.
//
import SessionMOffersKit
import UIKit
class ClaimUserOfferViewController: UIViewController {
var item: SMUserOfferItem? = nil;
@IBOutlet weak var barCodeText: UILabel!
@IBOutlet weak var barCodeImage: UIImageView!
@IBOutlet weak var barCodeImageHeight: NSLayoutConstraint!
@IBOutlet weak var image: UIImageView!
@IBOutlet weak var imageHeight: NSLayoutConstraint!
@IBOutlet weak var header: UILabel!
@IBOutlet weak var details: UILabel!
@IBOutlet weak var expires: UILabel!
@IBOutlet weak var countDown: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
fetchClaim()
}
func fetchClaim() {
SMOffersManager.instance().claimUserOffer(havingID: item!.userOfferID) { (result: SMUserOfferClaimedResponse?, error: SMError?) in
if let error = error {
self.present(UIAlertController(title: "Nothing Fetched", message: error.message, preferredStyle: .alert), animated: true, completion: {})
} else if let claim = result?.claimedOffer {
self.renderClaim(claim: claim)
}
}
}
func renderClaim(claim: SMClaimedOfferItem?) {
if let claim = claim {
barCodeText.text = claim.code;
header.text = claim.name;
details.text = claim.details;
let df = DateFormatter()
df.dateFormat = "dd.MM.yyyy"
if let expirationDate = claim.expirationDate {
expires.text = "Expires: \(df.string(from: expirationDate))";
} else {
expires.text = "Expires: N/A"
}
Common.loadImage(parent: nil, uri: claim.codeImageURI, imgView: self.barCodeImage, imageHeight: self.barCodeImageHeight, maxHeight: 70)
if let uri = item?.media[0].uri {
Common.loadImage(parent: nil, uri: uri, imgView: self.image, imageHeight: self.imageHeight, maxHeight: 150)
}
// Tick down 60 seconds
Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(onTick(timer:)), userInfo: nil, repeats: true).fire()
}
}
var ticks = 60;
@objc func onTick(timer: Timer) {
if (ticks > 0) {
countDown.text = ("in \(ticks) seconds");
ticks -= 1;
} else {
timer.invalidate()
dismiss(animated: true, completion: nil)
}
}
@IBAction func doDismiss(_ sender: UIButton) {
dismiss(animated: true, completion: nil)
}
}
| mit | dae1ac9c8b95069fda3a1c64558143ab | 30.4 | 153 | 0.611465 | 4.433555 | false | false | false | false |
anilkumarbp/swift-sdk-new | src/Subscription/crypt/PKCS7.swift | 8 | 1392 | //
// PKCS7.swift
// CryptoSwift
//
// Created by Marcin Krzyzanowski on 28/02/15.
// Copyright (c) 2015 Marcin Krzyzanowski. All rights reserved.
//
// PKCS is a group of public-key cryptography standards devised
// and published by RSA Security Inc, starting in the early 1990s.
//
import Foundation
public struct PKCS7: Padding {
public init() {
}
public func add(bytes: [UInt8] , blockSize:Int) -> [UInt8] {
var padding = UInt8(blockSize - (bytes.count % blockSize))
var withPadding = bytes
if (padding == 0) {
// If the original data is a multiple of N bytes, then an extra block of bytes with value N is added.
for i in 0..<blockSize {
withPadding.extend([UInt8(blockSize)])
}
} else {
// The value of each added byte is the number of bytes that are added
for i in 0..<padding {
withPadding.extend([UInt8(padding)])
}
}
return withPadding
}
public func remove(bytes: [UInt8], blockSize:Int? = nil) -> [UInt8] {
let lastByte = bytes.last!
var padding = Int(lastByte) // last byte
if padding >= 1 { //TODO: need test for that, what about empty padding
return Array(bytes[0..<(bytes.count - padding)])
}
return bytes
}
} | mit | 1a185650616f3979d0a727e92eb9728a | 29.282609 | 113 | 0.573994 | 4.231003 | false | false | false | false |
chen392356785/DouyuLive | DouyuLive/DouyuLive/Classes/Main/View/PageContentView.swift | 1 | 5794 | //
// PageContentView.swift
// DouyuLive
//
// Created by chenxiaolei on 2016/9/29.
// Copyright © 2016年 chenxiaolei. All rights reserved.
//
import UIKit
protocol PageContentViewDelegate : class {
func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int)
}
private let ContentCellID = "ContentCellID"
class PageContentView: UIView, UICollectionViewDataSource, UICollectionViewDelegate {
//MARK:- 定义属性
private var childVCs : [UIViewController]
private weak var parentViewController : UIViewController?
private var startOffsetX : CGFloat = 0
weak var delegate: PageContentViewDelegate?
private var isForbidScrollDelegate : Bool = false
// MARK:- 懒加载属性
private lazy var collectionView : UICollectionView = {[weak self] in
// 1.创建layout
let layout = UICollectionViewFlowLayout()
layout.itemSize = (self?.bounds.size)!
layout.minimumLineSpacing = 0
layout.minimumInteritemSpacing = 0
layout.scrollDirection = .horizontal
// 2.创建UICollectionView
let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout)
collectionView.showsHorizontalScrollIndicator = false
collectionView.isPagingEnabled = true
collectionView.bounces = false
collectionView.dataSource = self
collectionView.delegate = self
collectionView.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentCellID)
return collectionView
}()
//MARK:- 自定义构造函数
init(frame: CGRect, childVCs: [UIViewController], parentViewController: UIViewController?) {
self.childVCs = childVCs
self.parentViewController = parentViewController
super.init(frame: frame)
//设置UI界面
setupUI()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
//MARK:- 设置UI界面
private func setupUI() {
// 1.将所有的字控制器添加父控制器中
for childVC in childVCs {
parentViewController?.addChildViewController(childVC)
}
// 2. 添加UICollectionView,用于在Cell中存放控制器的View
addSubview(collectionView)
collectionView.frame = bounds
}
// MARK:- 遵守UICollectionViewDataSource
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVCs.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
// 1.创建Cell
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentCellID, for: indexPath)
// 2.给Cell设置内容
for view in cell.contentView.subviews {
view.removeFromSuperview()
}
let childVC = childVCs[indexPath.item]
childVC.view.frame = cell.contentView.bounds
cell.contentView.addSubview(childVC.view)
return cell
}
// MARK:- 遵守UICollectionViewDelegate
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
isForbidScrollDelegate = false
startOffsetX = scrollView.contentOffset.x
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
// 0.判断是否是点击事件
if isForbidScrollDelegate {
return
}
// 1.获取需要的数据
var progress : CGFloat = 0
var sourceIndex : Int = 0
var targetIndex: Int = 0
// 2.判断是左滑动还是右滑动
let currentOffsetX = scrollView.contentOffset.x
let scrollViewW = scrollView.bounds.width
if currentOffsetX > startOffsetX { // 左滑动
// 1.计算progress
progress = currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW)
// 2.计算sourceIndex
sourceIndex = Int(currentOffsetX / scrollViewW)
// 3.计算targetIndex
targetIndex = sourceIndex + 1
if targetIndex >= childVCs.count {
targetIndex = childVCs.count - 1
}
// 4.如果完全划过去
if currentOffsetX - startOffsetX == scrollViewW {
progress = 1
targetIndex = sourceIndex
}
} else { //右滑动
// 1.计算progress
progress = 1 - (currentOffsetX / scrollViewW - floor(currentOffsetX / scrollViewW))
// 2.计算targetIndex
targetIndex = Int(currentOffsetX / scrollViewW)
// 3.计算sourceIndex
sourceIndex = targetIndex + 1
if targetIndex >= childVCs.count {
sourceIndex = childVCs.count - 1
}
}
// 3.将progress/sourceIndex/tagetIndex传递给titleView
delegate?.pageContentView(contentView: self, progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex)
}
//MARK:- 对外界暴露的方法
func setCurrentIndex(currentIndex: Int){
// 1.记录需要进行执行代理方法
isForbidScrollDelegate = true
// 2.滚动到正确的位置
let offsetX = CGFloat(currentIndex) * collectionView.frame.width
collectionView.setContentOffset(CGPoint(x: offsetX, y: 0), animated: false)
}
}
| mit | 39cbfdcd0b9e7b22284196d35dcc60e6 | 30.011299 | 124 | 0.612498 | 5.953362 | false | false | false | false |
vector-im/riot-ios | Riot/Modules/Settings/Discovery/SettingsDiscoveryViewModel.swift | 1 | 6974 | /*
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
@objc final class SettingsDiscoveryViewModel: NSObject, SettingsDiscoveryViewModelType {
// MARK: - Properties
// MARK: Private
private let session: MXSession
private var identityService: MXIdentityService?
private var serviceTerms: MXServiceTerms?
private var viewState: SettingsDiscoveryViewState?
private var threePIDs: [MX3PID] = []
// MARK: Public
weak var viewDelegate: SettingsDiscoveryViewModelViewDelegate?
@objc weak var coordinatorDelegate: SettingsDiscoveryViewModelCoordinatorDelegate?
// MARK: - Setup
@objc init(session: MXSession, thirdPartyIdentifiers: [MXThirdPartyIdentifier]) {
self.session = session
let identityService = session.identityService
if let identityService = identityService {
self.serviceTerms = MXServiceTerms(baseUrl: identityService.identityServer, serviceType: MXServiceTypeIdentityService, matrixSession: session, accessToken: nil)
}
self.identityService = identityService
self.threePIDs = SettingsDiscoveryViewModel.threePids(from: thirdPartyIdentifiers)
super.init()
}
// MARK: - Public
func process(viewAction: SettingsDiscoveryViewAction) {
switch viewAction {
case .load:
self.checkTerms()
case .acceptTerms:
self.acceptTerms()
case .select(threePid: let threePid):
self.coordinatorDelegate?.settingsDiscoveryViewModel(self, didSelectThreePidWith: threePid.medium.identifier, and: threePid.address)
case .tapUserSettingsLink:
self.coordinatorDelegate?.settingsDiscoveryViewModelDidTapUserSettingsLink(self)
}
}
@objc func update(thirdPartyIdentifiers: [MXThirdPartyIdentifier]) {
self.threePIDs = SettingsDiscoveryViewModel.threePids(from: thirdPartyIdentifiers)
// Update view state only if three3pids was previously
guard let viewState = self.viewState,
case let .loaded(displayMode: displayMode) = viewState else {
return
}
let canDisplayThreePids: Bool
switch displayMode {
case .threePidsAdded, .noThreePidsAdded:
canDisplayThreePids = true
default:
canDisplayThreePids = false
}
if canDisplayThreePids {
self.updateViewStateFromCurrentThreePids()
}
}
// MARK: - Private
private func checkTerms() {
guard let identityService = self.identityService, let serviceTerms = self.serviceTerms else {
self.update(viewState: .loaded(displayMode: .noIdentityServer))
return
}
guard self.canCheckTerms() else {
return
}
self.update(viewState: .loading)
serviceTerms.areAllTermsAgreed({ (agreedTermsProgress) in
if agreedTermsProgress.isFinished || agreedTermsProgress.totalUnitCount == 0 {
// Display three pids if presents
self.updateViewStateFromCurrentThreePids()
} else {
let identityServer = identityService.identityServer
let identityServerHost = URL(string: identityServer)?.host ?? identityServer
self.update(viewState: .loaded(displayMode: .termsNotSigned(host: identityServerHost)))
}
}, failure: { (error) in
self.update(viewState: .error(error))
})
}
private func acceptTerms() {
guard let identityService = self.identityService else {
self.update(viewState: .loaded(displayMode: .noIdentityServer))
return
}
// Launch an identity server request to trigger terms modal apparition
identityService.account { (response) in
switch response {
case .success:
// Display three pids if presents
self.updateViewStateFromCurrentThreePids()
case .failure(let error):
if MXError(nsError: error)?.errcode == kMXErrCodeStringTermsNotSigned {
// Identity terms modal should appear
} else {
self.update(viewState: .error(error))
}
}
}
}
private func canCheckTerms() -> Bool {
guard let viewState = self.viewState else {
return true
}
let canCheckTerms: Bool
if case .loading = viewState {
canCheckTerms = false
} else {
canCheckTerms = true
}
return canCheckTerms
}
private func updateViewStateFromCurrentThreePids() {
self.updateViewState(with: self.threePIDs)
}
private func updateViewState(with threePids: [MX3PID]) {
let viewState: SettingsDiscoveryViewState
if threePids.isEmpty {
viewState = .loaded(displayMode: .noThreePidsAdded)
} else {
let emails = threePids.compactMap { (threePid) -> MX3PID? in
if case .email = threePid.medium {
return threePid
} else {
return nil
}
}
let phoneNumbers = threePids.compactMap { (threePid) -> MX3PID? in
if case .msisdn = threePid.medium {
return threePid
} else {
return nil
}
}
viewState = .loaded(displayMode: .threePidsAdded(emails: emails, phoneNumbers: phoneNumbers))
}
self.update(viewState: viewState)
}
private func update(viewState: SettingsDiscoveryViewState) {
self.viewState = viewState
self.viewDelegate?.settingsDiscoveryViewModel(self, didUpdateViewState: viewState)
}
private class func threePids(from thirdPartyIdentifiers: [MXThirdPartyIdentifier]) -> [MX3PID] {
return thirdPartyIdentifiers.map({ (thirdPartyIdentifier) -> MX3PID in
return MX3PID(medium: MX3PID.Medium(identifier: thirdPartyIdentifier.medium), address: thirdPartyIdentifier.address)
})
}
}
| apache-2.0 | 3bccb713df55e778f5c13bc89b07844b | 33.87 | 172 | 0.614138 | 5.521774 | false | false | false | false |
JaSpa/swift | test/SILGen/global_resilience.swift | 4 | 3546 | // RUN: rm -rf %t && mkdir %t
// RUN: %target-swift-frontend -emit-module -enable-resilience -emit-module-path=%t/resilient_global.swiftmodule -module-name=resilient_global %S/../Inputs/resilient_global.swift
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -I %t -emit-silgen -enable-resilience -parse-as-library %s | %FileCheck %s
// RUN: %target-swift-frontend -Xllvm -new-mangling-for-tests -I %t -emit-sil -O -enable-resilience -parse-as-library %s | %FileCheck --check-prefix=CHECK-OPT %s
import resilient_global
public struct MyEmptyStruct {}
// CHECK-LABEL: sil_global @_T017global_resilience13myEmptyGlobalAA02MyD6StructVv : $MyEmptyStruct
public var myEmptyGlobal = MyEmptyStruct()
// CHECK-LABEL: sil_global @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv : $MyEmptyStruct
@_fixed_layout public var myFixedLayoutGlobal = MyEmptyStruct()
// Mutable addressor for resilient global (should not be public?)
// CHECK-LABEL: sil [global_init] @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau : $@convention(thin) () -> Builtin.RawPointer
// CHECK: global_addr @_T017global_resilience13myEmptyGlobalAA02MyD6StructVv
// CHECK: return
// Synthesized getter and setter for our resilient global variable
// CHECK-LABEL: sil @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfg
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
// CHECK-LABEL: sil @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfs
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
// Mutable addressor for fixed-layout global
// CHECK-LABEL: sil [global_init] @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVfau
// CHECK: global_addr @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK: return
// CHECK-OPT-LABEL: sil private @globalinit_{{.*}}_func0
// CHECK-OPT: alloc_global @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: return
// CHECK-OPT-LABEL: sil [global_init] @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVfau
// CHECK-OPT: global_addr @_T017global_resilience19myFixedLayoutGlobalAA13MyEmptyStructVv
// CHECK-OPT: function_ref @globalinit_{{.*}}_func0
// CHECK-OPT: return
// Accessing resilient global from our resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @_T017global_resilience16getMyEmptyGlobalAA0dE6StructVyF
// CHECK: function_ref @_T017global_resilience13myEmptyGlobalAA02MyD6StructVfau
// CHECK: return
public func getMyEmptyGlobal() -> MyEmptyStruct {
return myEmptyGlobal
}
// Accessing resilient global from a different resilience domain --
// access it with accessors
// CHECK-LABEL: sil @_T017global_resilience14getEmptyGlobal010resilient_A00D15ResilientStructVyF
// CHECK: function_ref @_T016resilient_global11emptyGlobalAA20EmptyResilientStructVfg
// CHECK: return
public func getEmptyGlobal() -> EmptyResilientStruct {
return emptyGlobal
}
// Accessing fixed-layout global from a different resilience domain --
// call the addressor directly
// CHECK-LABEL: sil @_T017global_resilience20getFixedLayoutGlobal010resilient_A020EmptyResilientStructVyF
// CHECK: function_ref @_T016resilient_global17fixedLayoutGlobalAA20EmptyResilientStructVfau
// CHECK: return
public func getFixedLayoutGlobal() -> EmptyResilientStruct {
return fixedLayoutGlobal
}
| apache-2.0 | 69170ae7e1c1890ef07bb7fa817d3a66 | 45.051948 | 178 | 0.770446 | 4.166863 | false | false | false | false |
maxim-pervushin/TimeLogger | HyperTimeLogger/HyperTimeLogger/Src/View & Model Controllers/Settings/SettingsViewController.swift | 2 | 6729 | //
// Created by Maxim Pervushin on 30/05/16.
// Copyright (c) 2016 Maxim Pervushin. All rights reserved.
//
import UIKit
import MessageUI
class SettingsViewController: UITableViewController, MFMailComposeViewControllerDelegate {
// MARK: SettingsViewController @IB
@IBOutlet weak var remindersEnabledSwitch: UISwitch?
@IBOutlet weak var remindersIntervalPicker: UIDatePicker?
@IBOutlet weak var localNotificationsIntervalCell: UITableViewCell?
@IBAction func doneButtonAction(sender: AnyObject) {
dismissViewControllerAnimated(true, completion: nil)
}
@IBAction func remindersEnabledSwitchValueChanged(sender: AnyObject) {
if let sender = sender as? UISwitch {
HTLApp.remindersManager().enabled = sender.on
tableView.beginUpdates()
tableView.endUpdates()
}
}
@IBAction func remindersIntervalPickerValueChanged(sender: AnyObject) {
if let sender = sender as? UIDatePicker {
let components = NSCalendar.currentCalendar().components([.Hour, .Minute], fromDate: sender.date)
let interval = Double(components.hour * 60 * 60 + components.minute * 60)
HTLApp.remindersManager().interval = interval
}
}
@IBAction func exportToCSVButtonAction(sender: AnyObject) {
let csv = dataSource.exportDataToCSV()
if csv.characters.count == 0 {
let title = NSLocalizedString("Export to CSV", comment: "")
let message = NSLocalizedString("There is no data to export.", comment: "")
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
presentViewController(alert, animated: true, completion: nil)
} else {
let title = NSLocalizedString("Export to CSV", comment: "")
let message = NSLocalizedString("", comment: "")
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
if MFMailComposeViewController.canSendMail() {
alert.addAction(UIAlertAction(title: NSLocalizedString("Send Mail", comment: ""), style: .Default, handler: {
_ in
self.sendMailCSV(csv)
}))
}
alert.addAction(UIAlertAction(title: NSLocalizedString("Copy to Pasteboard", comment: ""), style: .Default, handler: {
_ in
self.copyCSV(csv)
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
}
@IBAction func resetContentButtonAction(sender: AnyObject) {
let title = NSLocalizedString("Reset content", comment: "")
let message = NSLocalizedString("Are you sure want to reset all data?", comment: "")
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Reset", comment: ""), style: .Destructive, handler: {
_ in
self.dataSource.resetContent()
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
@IBAction func resetDefaultsButtonAction(sender: AnyObject) {
let title = NSLocalizedString("Reset defaults", comment: "")
let message = NSLocalizedString("Are you sure want to reset all defaults?", comment: "")
let alert = UIAlertController(title: title, message: message, preferredStyle: .Alert)
alert.addAction(UIAlertAction(title: NSLocalizedString("Reset", comment: ""), style: .Destructive, handler: {
_ in
self.dataSource.resetDefaults()
}))
alert.addAction(UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel, handler: nil))
presentViewController(alert, animated: true, completion: nil)
}
// MARK: UITableViewController
override func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
if let remindersEnabledSwitch = remindersEnabledSwitch where indexPath.section == 0 && indexPath.row == 2 {
return remindersEnabledSwitch.on ? 216 : 0
}
return indexPath.row == 0 ? 22 : 44
}
// MARK: UIViewController
override func viewDidLoad() {
super.viewDidLoad()
if HTLApp.versionIdentifier() != "" {
let gestureRecognizer = UITapGestureRecognizer(target: self, action: #selector(SettingsViewController.generateTestDataGesture(_:)))
gestureRecognizer.numberOfTapsRequired = 7
gestureRecognizer.numberOfTouchesRequired = 2
tableView.addGestureRecognizer(gestureRecognizer)
}
}
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
updateUI()
}
// MARK: private
private let dataSource = HTLSettingsDataSource()
private func updateUI() {
remindersEnabledSwitch?.on = HTLApp.remindersManager().enabled
let components = NSDateComponents()
components.second = Int(HTLApp.remindersManager().interval)
if let date = NSCalendar.currentCalendar().dateFromComponents(components) {
remindersIntervalPicker?.date = date
}
}
@objc private func generateTestDataGesture(sender: AnyObject) {
dataSource.generateTestData()
}
private func sendMailCSV(csv: String) {
guard let data = csv.dataUsingEncoding(NSUTF8StringEncoding) else {
return
}
let mailComposeViewController = MFMailComposeViewController()
mailComposeViewController.mailComposeDelegate = self
mailComposeViewController.setSubject(NSLocalizedString("Data export from Time Logger", comment: ""))
mailComposeViewController.setMessageBody(NSLocalizedString("Look at files attached", comment: ""), isHTML: false)
mailComposeViewController.addAttachmentData(data, mimeType: "text/csv", fileName: "export.csv")
presentViewController(mailComposeViewController, animated: true, completion: nil)
}
private func copyCSV(csv: String) {
UIPasteboard.generalPasteboard().string = csv
}
// MARK: MFMailComposeViewControllerDelegate
func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}
| mit | 349c2218c4daf75f94b7b00d7710a716 | 41.859873 | 143 | 0.669639 | 5.515574 | false | false | false | false |
lukemetz/Paranormal | Paranormal/ParanormalTests/Editor/EditorViewTests.swift | 3 | 1164 | import Cocoa
import Quick
import Nimble
import Paranormal
class EditorViewTests: QuickSpec {
override func spec() {
describe("EditorView") {
var editorViewController : EditorViewController?
var document : Document?
var editorView : EditorView!
beforeEach {
editorViewController = EditorViewController(nibName: "Editor", bundle: nil)
editorView = editorViewController?.view as? EditorView
}
describe("Point Transforms") {
it ("imageToApplication and applicationToImage are inverses") {
let translate = CGAffineTransformTranslate(CGAffineTransformIdentity, 10, 10)
let transform = CGAffineTransformScale(translate, 2, 2)
editorView.transform = transform
let image = CGPoint(x: 20, y: 32)
let application = editorView.imageToApplication(image)
let image_test = editorView.applicationToImage(application)
expect(image_test).to(equal(image))
}
}
}
}
}
| mit | 16d7718c349630edc3377e530913081c | 34.272727 | 97 | 0.581615 | 5.938776 | false | true | false | false |
insidegui/AppleEvents | Dependencies/swift-protobuf/Sources/SwiftProtobufPluginLibrary/FieldNumbers.swift | 3 | 1296 | // Sources/SwiftProtobufPluginLibrary/FieldNumbers.swift - Proto Field numbers
//
// Copyright (c) 2014 - 2017 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/master/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Field numbers needed by SwiftProtobufPluginLibrary since they currently aren't generated.
///
// -----------------------------------------------------------------------------
import Foundation
extension Google_Protobuf_FileDescriptorProto {
struct FieldNumbers {
static let messageType: Int = 4
static let enumType: Int = 5
static let service: Int = 6
static let `extension`: Int = 7
}
}
extension Google_Protobuf_DescriptorProto {
struct FieldNumbers {
static let field: Int = 2
static let nestedType: Int = 3
static let enumType: Int = 4
static let `extension`: Int = 6
static let oneofDecl: Int = 8
}
}
extension Google_Protobuf_EnumDescriptorProto {
struct FieldNumbers {
static let value: Int = 2
}
}
extension Google_Protobuf_ServiceDescriptorProto {
struct FieldNumbers {
static let method: Int = 2
}
}
| bsd-2-clause | 27917b079d75a901ff2b62d1b08975c7 | 27.173913 | 93 | 0.631173 | 4.747253 | false | false | false | false |
phill84/mpx | mpx/PlayerViewController.swift | 1 | 2677 | //
// PlayerViewController.swift
// mpx
//
// Created by Jiening Wen on 04/09/15.
// Copyright (c) 2015 phill84.
//
// This file is part of mpx.
//
// mpx 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 2 of the License, or
// (at your option) any later version.
//
// mpx 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 mpx. If not, see <http://www.gnu.org/licenses/>.
//
import Cocoa
import XCGLogger
class PlayerViewController: NSViewController {
let logger = XCGLogger.defaultInstance()
let idleInterval = NSTimeInterval(2) // 2 seconds
var titleBarView: NSView?
var controlUIView: ControlUIView?
var idleTimer: NSTimer?
weak var mpv: MpvController?
var cursorOverView = false
override func viewWillAppear() {
titleBarView = view.window!.standardWindowButton(NSWindowButton.CloseButton)?.superview
controlUIView = view.subviews[1] as? ControlUIView
resetIdleTimer()
mpv = (view.window?.windowController as! PlayerWindowController).mpv
}
override func mouseEntered(event: NSEvent) {
cursorOverView = true
showControlUI()
}
override func mouseExited(event: NSEvent) {
cursorOverView = false
if !AppDelegate.getInstance().fullscreen {
hideControlUI()
}
NSCursor.unhide()
}
override func mouseMoved(event: NSEvent) {
showControlUI()
}
func resetIdleTimer() {
self.idleTimer?.invalidate()
self.idleTimer = NSTimer(timeInterval: self.idleInterval, target: self, selector: Selector("hideControlUI"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(self.idleTimer!, forMode: NSDefaultRunLoopMode)
}
func showControlUI() {
if !AppDelegate.getInstance().active {
return
}
resetIdleTimer()
titleBarView!.animator().alphaValue = 1
controlUIView!.animator().alphaValue = 1
// unhide cursor always since it doesn't do any harm if already unhidden
NSCursor.unhide()
}
func hideControlUI() {
if !AppDelegate.getInstance().active {
return
}
// invalidate idleTimer since controlUI will be hidden already
idleTimer?.invalidate()
if !AppDelegate.getInstance().fullscreen {
titleBarView!.animator().alphaValue = 0
}
controlUIView!.animator().alphaValue = 0
// hide cursor if over player view
if cursorOverView {
NSCursor.hide()
}
}
}
| gpl-2.0 | 80a49879a5203112b2adec8a945c8069 | 26.040404 | 140 | 0.72656 | 3.868497 | false | false | false | false |
stripe/stripe-ios | Tests/Tests/STPPaymentMethodCardTest.swift | 1 | 5459 | //
// STPPaymentMethodCardTest.swift
// StripeiOS Tests
//
// Created by Yuki Tokuhiro on 3/6/19.
// Copyright © 2019 Stripe, Inc. All rights reserved.
//
import StripeCoreTestUtils
@testable@_spi(STP) import Stripe
@testable@_spi(STP) import StripeCore
@testable@_spi(STP) import StripePaymentSheet
@testable@_spi(STP) import StripePayments
@testable@_spi(STP) import StripePaymentsUI
private let kCardPaymentIntentClientSecret =
"pi_1H5J4RFY0qyl6XeWFTpgue7g_secret_1SS59M0x65qWMaX2wEB03iwVE"
class STPPaymentMethodCardTest: XCTestCase {
private(set) var cardJSON: [AnyHashable: Any]?
func _retrieveCardJSON(_ completion: @escaping ([AnyHashable: Any]?) -> Void) {
if let cardJSON = cardJSON {
completion(cardJSON)
} else {
let client = STPAPIClient(publishableKey: STPTestingDefaultPublishableKey)
client.retrievePaymentIntent(
withClientSecret: kCardPaymentIntentClientSecret,
expand: ["payment_method"]
) { [self] paymentIntent, _ in
cardJSON = paymentIntent?.paymentMethod?.card?.allResponseFields
completion(cardJSON ?? [:])
}
}
}
func testCorrectParsing() {
let retrieveJSON = XCTestExpectation(description: "Retrieve JSON")
_retrieveCardJSON({ json in
let card = STPPaymentMethodCard.decodedObject(fromAPIResponse: json)
XCTAssertNotNil(card, "Failed to decode JSON")
retrieveJSON.fulfill()
XCTAssertEqual(card?.brand, .visa)
XCTAssertEqual(card?.country, "US")
XCTAssertNotNil(card?.checks)
XCTAssertEqual(card?.expMonth, 7)
XCTAssertEqual(card?.expYear, 2021)
XCTAssertEqual(card?.funding, "credit")
XCTAssertEqual(card?.last4, "4242")
XCTAssertNotNil(card?.threeDSecureUsage)
XCTAssertEqual(card?.threeDSecureUsage?.supported, true)
XCTAssertNotNil(card?.networks)
XCTAssertEqual(card?.networks?.available, ["visa"])
XCTAssertNil(card?.networks?.preferred)
})
wait(for: [retrieveJSON], timeout: STPTestingNetworkRequestTimeout)
}
func testDecodedObjectFromAPIResponseRequiredFields() {
let requiredFields: [String]? = []
for field in requiredFields ?? [] {
var response =
STPTestUtils.jsonNamed(STPTestJSONPaymentMethodCard)?["card"] as? [AnyHashable: Any]
response?.removeValue(forKey: field)
XCTAssertNil(STPPaymentMethodCard.decodedObject(fromAPIResponse: response))
}
let json = STPTestUtils.jsonNamed(STPTestJSONPaymentMethodCard)?["card"]
let decoded = STPPaymentMethodCard.decodedObject(
fromAPIResponse: json as? [AnyHashable: Any]
)
XCTAssertNotNil(decoded)
}
func testDecodedObjectFromAPIResponseMapping() {
let response =
STPTestUtils.jsonNamed(STPTestJSONPaymentMethodCard)?["card"] as? [AnyHashable: Any]
let card = STPPaymentMethodCard.decodedObject(fromAPIResponse: response)
XCTAssertEqual(card?.brand, .visa)
XCTAssertEqual(card?.country, "US")
XCTAssertNotNil(card?.checks)
XCTAssertEqual(card?.expMonth, 8)
XCTAssertEqual(card?.expYear, 2020)
XCTAssertEqual(card?.funding, "credit")
XCTAssertEqual(card?.last4, "4242")
XCTAssertEqual(card?.fingerprint, "6gVyxfIhqc8Z0g0X")
XCTAssertNotNil(card?.threeDSecureUsage)
XCTAssertEqual(card?.threeDSecureUsage?.supported, true)
XCTAssertNotNil(card?.wallet)
}
func testBrandFromString() {
XCTAssertEqual(STPPaymentMethodCard.brand(from: "visa"), .visa)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "VISA"), .visa)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "amex"), .amex)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "AMEX"), .amex)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "american_express"), .amex)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "AMERICAN_EXPRESS"), .amex)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "mastercard"), .mastercard)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "MASTERCARD"), .mastercard)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "discover"), .discover)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "DISCOVER"), .discover)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "jcb"), .JCB)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "JCB"), .JCB)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "diners"), .dinersClub)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "DINERS"), .dinersClub)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "diners_club"), .dinersClub)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "DINERS_CLUB"), .dinersClub)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "unionpay"), .unionPay)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "UNIONPAY"), .unionPay)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "unknown"), .unknown)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "UNKNOWN"), .unknown)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "garbage"), .unknown)
XCTAssertEqual(STPPaymentMethodCard.brand(from: "GARBAGE"), .unknown)
}
}
| mit | 84a86e58697a44998dcdec1f3459674a | 42.664 | 100 | 0.680835 | 4.877569 | false | true | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Controllers/ReadHistoryViewController.swift | 1 | 2306 | //
// ReadHistoryViewController.swift
// zhuishushenqi
//
// Created by yung on 2017/6/17.
// Copyright © 2017年 QS. All rights reserved.
//
import UIKit
class ReadHistoryViewController: BaseViewController,UITableViewDataSource,UITableViewDelegate {
lazy var tableView:UITableView = {
let tableView = UITableView(frame: CGRect(x: 0, y: 64, width: ScreenWidth, height: ScreenHeight - 64), style: .grouped)
tableView.dataSource = self
tableView.delegate = self
tableView.sectionHeaderHeight = CGFloat.leastNormalMagnitude
tableView.sectionFooterHeight = CGFloat.leastNormalMagnitude
tableView.rowHeight = 93
tableView.qs_registerCellNib(ReadHistoryCell.self)
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
initSubview()
}
func initSubview(){
self.title = "浏览记录"
view.addSubview(self.tableView)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ZSBookManager.shared.historyIds.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell:ReadHistoryCell? = tableView.qs_dequeueReusableCell(ReadHistoryCell.self)
cell?.backgroundColor = UIColor.white
cell?.selectionStyle = .none
let models = ZSBookManager.shared.historyBooks.allValues() as! [BookDetail]
cell?.configureCell(model: models[indexPath.row])
return cell!
}
func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
return tableView.sectionHeaderHeight
}
func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
return tableView.sectionHeaderHeight
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let models = ZSBookManager.shared.historyBooks.allValues() as! [BookDetail]
let model = models[indexPath.row]
self.navigationController?.pushViewController(QSBookDetailRouter.createModule(id: model._id ), animated: true)
}
}
| mit | 6124ab4fbb1d26a453cf88c54cf6bed5 | 34.859375 | 127 | 0.68976 | 5.111359 | false | false | false | false |
NoryCao/zhuishushenqi | zhuishushenqi/Root/Models/ZSShelfMessage.swift | 1 | 2073 | //
// ZSShelfMessage.swift
// zhuishushenqi
//
// Created by caony on 2018/6/8.
// Copyright © 2018年 QS. All rights reserved.
//
import UIKit
import HandyJSON
enum ZSShelfMessageType {
case post
case link
case booklist
}
//@objc(ZSShelfMessage)
class ZSShelfMessage: NSObject,HandyJSON {
@objc dynamic var postLink:String = ""
@objc var highlight:Bool = false {
didSet{
if highlight {
textColor = UIColor.red
}
}
}
required override init() {
}
internal var textColor:UIColor = UIColor.gray
func postMessage() ->(String,String, ZSShelfMessageType,UIColor){
var id:String = ""
var title:String = ""
// 过滤方式变更
// 目前已知的有三种 post或者link或booklist
// post一般跳转到评论页,post后跟的默认为24位的字符串
// link一般打开链接,link一般以link后的第一个空格作为区分
// booklist一般打开书单
var type:ZSShelfMessageType = .post
let qsLink:NSString = self.postLink as NSString
var typePost = qsLink.range(of: "post:") //[[post:5baf14726f660bbe4fe5dc36 🇨🇳喜迎国庆【惊喜】追书又双叒叕送福利!]]
if typePost.location == NSNotFound {
typePost = qsLink.range(of: "link:")
type = .link
}
if typePost.location == NSNotFound {
typePost = qsLink.range(of: "booklist:")
type = .booklist
}
// 去除首尾的中括号,再以空格区分文字与post
let noLeadLink = self.postLink.qs_subStr(from: 2)
let noTailLink = noLeadLink.substingInRange(0..<(noLeadLink.count - 2)) ?? noLeadLink
let spaceRange = (noTailLink as NSString).range(of: " ")
id = noTailLink.substingInRange(typePost.length..<spaceRange.location) ?? noLeadLink
title = noTailLink.qs_subStr(from: spaceRange.location + 1)
return (id, title, type, textColor)
}
}
| mit | 5e93631867be001b53c5757ca5e445c4 | 27.769231 | 105 | 0.600535 | 3.617021 | false | false | false | false |
ello/ello-ios | Sources/Controllers/ManageCategories/ManageCategoriesViewController.swift | 1 | 6634 | ////
/// ManageCategoriesViewController.swift
//
class ManageCategoriesViewController: StreamableViewController {
private var _mockScreen: ManageCategoriesScreenProtocol?
var screen: ManageCategoriesScreenProtocol {
set(screen) { _mockScreen = screen }
get { return fetchScreen(_mockScreen) }
}
var generator: ManageCategoriesGenerator!
var selectedIds: Set<String>?
init(currentUser: User) {
super.init(nibName: nil, bundle: nil)
self.generator = ManageCategoriesGenerator(
currentUser: currentUser,
destination: self
)
self.currentUser = currentUser
}
required init?(coder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func didSetCurrentUser() {
super.didSetCurrentUser()
generator.currentUser = currentUser
}
override func loadView() {
let screen = ManageCategoriesScreen()
screen.navigationBar.title = InterfaceString.Discover.Subscriptions
screen.delegate = self
view = screen
viewContainer = screen.streamContainer
}
override func viewDidLoad() {
super.viewDidLoad()
streamViewController.streamKind = .manageCategories
streamViewController.reloadClosure = { [weak self] in self?.generator?.load(reload: true) }
streamViewController.showLoadingSpinner()
generator.load(reload: false)
}
private func updateInsets() {
updateInsets(navBar: screen.navigationBar)
}
override func showNavBars(animated: Bool) {
super.showNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: true,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
updateInsets()
}
override func hideNavBars(animated: Bool) {
super.hideNavBars(animated: animated)
positionNavBar(
screen.navigationBar,
visible: false,
withConstraint: screen.navigationBarTopConstraint,
animated: animated
)
updateInsets()
}
override func goingBackNow(proceed: @escaping Block) {
guard hasPendingChanges() else {
proceed()
return
}
saveAndExit { proceed() }
}
override func backButtonTapped() {
guard hasPendingChanges() else {
super.backButtonTapped()
return
}
Tracker.shared.categoriesEdited()
saveAndExit { super.backButtonTapped() }
}
override func closeButtonTapped() {
if hasPendingChanges() {
let alertController = AlertViewController(
message: InterfaceString.Settings.AbortChanges
)
let okCancelAction = AlertAction(style: .okCancel) { _ in
super.backButtonTapped()
}
alertController.addAction(okCancelAction)
self.present(alertController, animated: true, completion: nil)
}
else {
super.backButtonTapped()
}
}
private func hasPendingChanges() -> Bool {
guard
let currentUser = currentUser,
let selectedIds = selectedIds
else { return false }
return selectedIds != currentUser.followedCategoryIds
}
private func saveAndExit(onSuccess: @escaping Block) {
guard let selectedIds = selectedIds else { return }
view.isUserInteractionEnabled = false
ElloHUD.showLoadingHudInView(view)
ProfileService().update(categoryIds: selectedIds, onboarding: false)
.done { _ in
if let currentUser = self.currentUser {
currentUser.followedCategoryIds = selectedIds
self.appViewController?.currentUser = currentUser
}
onSuccess()
}
.catch { _ in
self.view.isUserInteractionEnabled = true
}
.finally {
ElloHUD.hideLoadingHudInView(self.view)
}
}
}
extension ManageCategoriesViewController: SubscribedCategoryResponder {
func categorySubscribeTapped(cell: UICollectionViewCell) {
let collectionView = streamViewController.collectionView
guard let indexPath = collectionView.indexPath(for: cell) else { return }
let dataSource = streamViewController.dataSource!
if cell.isSelected {
collectionView.deselectItem(at: indexPath, animated: true)
}
else {
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: [])
}
if let paths = collectionView.indexPathsForSelectedItems {
let selection = paths.compactMap { dataSource.jsonable(at: $0) as? Category }
selectedIds = Set(selection.map { $0.id })
}
}
}
extension ManageCategoriesViewController: StreamDestination {
var isPagingEnabled: Bool {
get { return streamViewController.isPagingEnabled }
set { streamViewController.isPagingEnabled = newValue }
}
func replacePlaceholder(
type: StreamCellType.PlaceholderType,
items: [StreamCellItem],
completion: @escaping Block
) {
streamViewController.replacePlaceholder(type: type, items: items) {
if type == .streamItems, let currentUser = self.currentUser {
for (row, item) in items.enumerated() {
guard
let category = item.jsonable as? Category,
currentUser.subscribedTo(categoryId: category.id)
else { continue }
self.streamViewController.collectionView.selectItem(
at: IndexPath(row: row, section: 0),
animated: false,
scrollPosition: []
)
}
}
completion()
}
if type == .streamItems {
streamViewController.doneLoading()
}
}
func setPlaceholders(items: [StreamCellItem]) {
streamViewController.clearForInitialLoad(newItems: items)
}
func setPrimary(jsonable: Model) {
}
func primaryModelNotFound() {
self.streamViewController.doneLoading()
}
func setPagingConfig(responseConfig: ResponseConfig) {
streamViewController.responseConfig = responseConfig
}
}
extension ManageCategoriesViewController: ManageCategoriesScreenDelegate {
}
| mit | 15e9e2d6c8722da870a3b0935328dbb7 | 29.292237 | 99 | 0.610491 | 5.684662 | false | false | false | false |
cdtschange/SwiftMKit | SwiftMKit/Data/Push/PushManager.swift | 1 | 6995 | //
// PushManager.swift
// Merak
//
// Created by Mao on 7/8/16.
// Copyright © 2016. All rights reserved.
//
import Foundation
import UIKit
import CocoaLumberjack
import UserNotifications
public enum PushFrom : Int {
case remote
case local
}
public protocol PushManagerProtocol {
func pmp_registerRemoteNotification(application:UIApplication, launchOptions: [UIApplicationLaunchOptionsKey: Any]?)
func pmp_didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data)
func pmp_didReceiveNotification(from : PushFrom, userInfo: [AnyHashable: Any])
func pmp_didFailToRegisterForRemoteNotifications(withError error: Error)
}
extension PushManagerProtocol {
public func pmp_didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data) {}
public func pmp_didReceiveNotification(from : PushFrom, userInfo: [AnyHashable: Any]){}
public func pmp_didFailToRegisterForRemoteNotifications(withError error: Error) {}
}
public class PushManager: NSObject , UNUserNotificationCenterDelegate{
private override init() {
}
public static let shared = PushManager()
private var tempPushUserInfo: [AnyHashable: Any]? {
didSet {
DDLogInfo("PushUserInfo temp store: \(String(describing: tempPushUserInfo))")
}
}
private var tempPushFrom: PushFrom?
public var managers: [PushManagerProtocol] = []
public var canReceiveData: Bool = false {
didSet {
if canReceiveData == true && tempPushUserInfo != nil && tempPushFrom != nil {
didReceiveNotification(from: tempPushFrom!, userInfo: tempPushUserInfo!)
}
}
}
public func storeTempData(userInfo: [AnyHashable: Any], from: PushFrom) {
tempPushUserInfo = userInfo
tempPushFrom = from
}
public func addManagers(_ managers: [PushManagerProtocol]) {
_ = managers.map { self.managers.append($0) }
}
public func register(){
if #available(iOS 10.0, *) {
let notifiCenter = UNUserNotificationCenter.current()
// let appDelegate = (UIApplication.shared.delegate) as! AppDelegate
// notifiCenter.delegate = appDelegate
}
}
public func finishLaunch(application:UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?){
PushManager.shared.register()
if managers.count > 0{
_ = managers.map { $0.pmp_registerRemoteNotification(application: application,launchOptions:launchOptions) }
}
//开机收到通知
if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [AnyHashable: Any] {
self.didReceiveNotification(from: .remote, userInfo: userInfo)
}else if let localNoti = launchOptions?[UIApplicationLaunchOptionsKey.localNotification] as? UILocalNotification {
self.didReceiveNotification(from: .local, userInfo: localNoti.userInfo ?? [:])
}
}
public func didRegisterForRemoteNotifications(withDeviceToken deviceToken: Data){
_ = managers.map { $0.pmp_didRegisterForRemoteNotifications(withDeviceToken: deviceToken) }
}
public func didReceiveNotification(from: PushFrom, userInfo: [AnyHashable: Any]){
storeTempData(userInfo: userInfo, from: from)
if canReceiveData {
tempPushUserInfo = nil
tempPushFrom = nil
_ = managers.map { $0.pmp_didReceiveNotification(from: from, userInfo: userInfo) }
}
}
public func didFailToRegisterForRemoteNotifications(withError error: Error){
_ = managers.map { $0.pmp_didFailToRegisterForRemoteNotifications(withError: error) }
}
}
//extension AppDelegate : UNUserNotificationCenterDelegate{
//
// //MARK: 推送回调方法
// func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// DDLogInfo("推送注册成功 DeviceToken: \(deviceToken)")
// PushManager.shared.didRegisterForRemoteNotifications(withDeviceToken: deviceToken)
// }
// func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// DDLogError("推送注册失败")
// PushManager.shared.didFailToRegisterForRemoteNotifications(withError: error)
// }
//
// func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
// if application.applicationState == .active || application.applicationState == .inactive {
// PushManager.shared.didReceiveNotification(from: .remote, userInfo: userInfo as [NSObject : AnyObject])
// }
//
// completionHandler(.noData)
// }
// func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
// if UIApplication.shared.applicationState == .active{ //本地推送,用户活动状态 不做处理
// return
// }
// if let userInfo = notification.userInfo {
// PushManager.shared.didReceiveNotification(from: .local, userInfo: userInfo as [NSObject : AnyObject])
// }
// }
// //MARK: iOS10新加入的回调方法
// // 应用在前台收到通知
// @available(iOS 10.0, *)
// func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
// let userInfo = notification.request.content.userInfo
// if notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true { //远程推送
// PushManager.shared.didReceiveNotification(from: .remote, userInfo: userInfo as [NSObject : AnyObject])
// }else{ //本地推送
// if UIApplication.shared.applicationState != .active{ //本地推送,用户活动状态 不做处理
// PushManager.shared.didReceiveNotification(from: .local, userInfo: userInfo as [NSObject : AnyObject])
// }
// }
// completionHandler(.sound)
// }
//
// // 点击通知进入应用
// @available(iOS 10.0, *)
// func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
// let userInfo = response.notification.request.content.userInfo
// if (response.notification.request.trigger?.isKind(of: UNPushNotificationTrigger.self) == true){
// PushManager.shared.didReceiveNotification(from: .remote, userInfo: userInfo)
// }else {
// PushManager.shared.didReceiveNotification(from: .local, userInfo: userInfo)
// }
// completionHandler()
// }
//}
| mit | 2621e4c8bad3967c1dbc93bb3156890e | 43 | 209 | 0.68739 | 5.10479 | false | false | false | false |
brentdax/swift | test/SILGen/protocol_resilience.swift | 2 | 17310 |
// RUN: %empty-directory(%t)
// RUN: %target-swift-frontend -module-name protocol_resilience -emit-module -enable-sil-ownership -enable-resilience -emit-module-path=%t/resilient_protocol.swiftmodule -module-name=resilient_protocol %S/../Inputs/resilient_protocol.swift
// RUN: %target-swift-emit-silgen -module-name protocol_resilience -I %t -enable-sil-ownership -enable-resilience %s | %FileCheck %s
import resilient_protocol
prefix operator ~~~
infix operator <*>
infix operator <**>
infix operator <===>
public protocol P {}
// Protocol is public -- needs resilient witness table
public protocol ResilientMethods {
associatedtype AssocType : P
func defaultWitness()
func anotherDefaultWitness(_ x: Int) -> Self
func defaultWitnessWithAssociatedType(_ a: AssocType)
func defaultWitnessMoreAbstractThanRequirement(_ a: AssocType, b: Int)
func defaultWitnessMoreAbstractThanGenericRequirement<T>(_ a: AssocType, t: T)
func noDefaultWitness()
func defaultWitnessIsNotPublic()
static func staticDefaultWitness(_ x: Int) -> Self
}
extension ResilientMethods {
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP14defaultWitnessyyF
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE14defaultWitnessyyF
public func defaultWitness() {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE21anotherDefaultWitnessyxSiF
public func anotherDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
public func defaultWitnessWithAssociatedType(_ a: AssocType) {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE41defaultWitnessMoreAbstractThanRequirement_1byqd___qd_0_tr0_lF
public func defaultWitnessMoreAbstractThanRequirement<A, T>(_ a: A, b: T) {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE48defaultWitnessMoreAbstractThanGenericRequirement_1tyqd___qd_0_tr0_lF
public func defaultWitnessMoreAbstractThanGenericRequirement<A, T>(_ a: A, t: T) {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientMethodsPAAE20staticDefaultWitnessyxSiFZ
public static func staticDefaultWitness(_ x: Int) -> Self {}
// CHECK-LABEL: sil private @$s19protocol_resilience16ResilientMethodsPAAE25defaultWitnessIsNotPublic{{.*}}F
private func defaultWitnessIsNotPublic() {}
}
public protocol ResilientConstructors {
init(noDefault: ())
init(default: ())
init?(defaultIsOptional: ())
init?(defaultNotOptional: ())
init(optionalityMismatch: ())
}
extension ResilientConstructors {
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC
// CHECK-LABEL: sil @$s19protocol_resilience21ResilientConstructorsPAAE7defaultxyt_tcfC
public init(default: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC
// CHECK-LABEL: sil @$s19protocol_resilience21ResilientConstructorsPAAE17defaultIsOptionalxSgyt_tcfC
public init?(defaultIsOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @$s19protocol_resilience21ResilientConstructorsPAAE20defaultIsNotOptionalxyt_tcfC
public init(defaultIsNotOptional: ()) {
self.init(noDefault: ())
}
// CHECK-LABEL: sil @$s19protocol_resilience21ResilientConstructorsPAAE19optionalityMismatchxSgyt_tcfC
public init?(optionalityMismatch: ()) {
self.init(noDefault: ())
}
}
public protocol ResilientStorage {
associatedtype T : ResilientConstructors
var propertyWithDefault: Int { get }
var propertyWithNoDefault: Int { get }
var mutablePropertyWithDefault: Int { get set }
var mutablePropertyNoDefault: Int { get set }
var mutableGenericPropertyWithDefault: T { get set }
subscript(x: T) -> T { get set }
var mutatingGetterWithNonMutatingDefault: Int { mutating get set }
}
extension ResilientStorage {
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP19propertyWithDefaultSivg
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE19propertyWithDefaultSivg
public var propertyWithDefault: Int {
get { return 0 }
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivg
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE26mutablePropertyWithDefaultSivs
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivM
public var mutablePropertyWithDefault: Int {
get { return 0 }
set { }
}
public private(set) var mutablePropertyNoDefault: Int {
get { return 0 }
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvg
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE33mutableGenericPropertyWithDefault1TQzvs
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvM
public var mutableGenericPropertyWithDefault: T {
get {
return T(default: ())
}
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStoragePy1TQzAEcig
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAEy1TQzAEcig
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStoragePy1TQzAEcis
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAEy1TQzAEcis
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStoragePy1TQzAEciM
public subscript(x: T) -> T {
get {
return x
}
set { }
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-LABEL: sil @$s19protocol_resilience16ResilientStoragePAAE36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivM
public var mutatingGetterWithNonMutatingDefault: Int {
get {
return 0
}
set { }
}
}
public protocol ResilientOperators {
associatedtype AssocType : P
static prefix func ~~~(s: Self)
static func <*><T>(s: Self, t: T)
static func <**><T>(t: T, s: Self) -> AssocType
static func <===><T : ResilientOperators>(t: T, s: Self) -> T.AssocType
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience18ResilientOperatorsP3tttopyyxFZ
// CHECK-LABEL: sil @$s19protocol_resilience3tttopyyxlF
public prefix func ~~~<S>(s: S) {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ
// CHECK-LABEL: sil @$s19protocol_resilience3lmgoiyyq__xtr0_lF
public func <*><T, S>(s: S, t: T) {}
// Swap the generic parameters to make sure we don't mix up our DeclContexts
// when mapping interface types in and out
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ
// CHECK-LABEL: sil @$s19protocol_resilience4lmmgoiy9AssocTypeQzq__xtAA18ResilientOperatorsRzr0_lF
public func <**><S : ResilientOperators, T>(t: T, s: S) -> S.AssocType {}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ
// CHECK-LABEL: sil @$s19protocol_resilience5leeegoiy9AssocTypeQzx_q_tAA18ResilientOperatorsRzAaER_r0_lF
public func <===><T : ResilientOperators, S : ResilientOperators>(t: T, s: S) -> T.AssocType {}
public protocol ReabstractSelfBase {
// No requirements
}
public protocol ReabstractSelfRefined : class, ReabstractSelfBase {
// A requirement with 'Self' abstracted as a class instance
var callback: (Self) -> Self { get set }
}
func id<T>(_ t: T) -> T {}
extension ReabstractSelfBase {
// A witness for the above requirement, but with 'Self' maximally abstracted
public var callback: (Self) -> Self {
get { return id }
nonmutating set { }
}
}
// CHECK-LABEL: sil private [transparent] [thunk] @$s19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg : $@convention(witness_method: ReabstractSelfRefined) <τ_0_0 where τ_0_0 : ReabstractSelfRefined> (@guaranteed τ_0_0) -> @owned @callee_guaranteed (@guaranteed τ_0_0) -> @owned τ_0_0
// CHECK: [[SELF_BOX:%.*]] = alloc_stack $τ_0_0
// CHECK-NEXT: [[SELF_COPY:%.*]] = copy_value %0 : $τ_0_0
// CHECK-NEXT: store [[SELF_COPY]] to [init] [[SELF_BOX]] : $*τ_0_0
// CHECK: [[WITNESS:%.*]] = function_ref @$s19protocol_resilience18ReabstractSelfBasePAAE8callbackyxxcvg
// CHECK-NEXT: [[RESULT:%.*]] = apply [[WITNESS]]<τ_0_0>([[SELF_BOX]])
// CHECK: [[THUNK_FN:%.*]] = function_ref @$sxxIegnr_xxIeggo_19protocol_resilience21ReabstractSelfRefinedRzlTR
// CHECK-NEXT: [[THUNK:%.*]] = partial_apply [callee_guaranteed] [[THUNK_FN]]<τ_0_0>([[RESULT]])
// CHECK-NEXT: destroy_addr [[SELF_BOX]]
// CHECK-NEXT: dealloc_stack [[SELF_BOX]]
// CHECK-NEXT: return [[THUNK]]
final class X : ReabstractSelfRefined {}
func inoutFunc(_ x: inout Int) {}
// CHECK-LABEL: sil hidden @$s19protocol_resilience22inoutResilientProtocolyy010resilient_A005OtherdE0_pzF
func inoutResilientProtocol(_ x: inout OtherResilientProtocol) {
// CHECK: function_ref @$s18resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivM
inoutFunc(&x.propertyInExtension)
}
struct OtherConformingType : OtherResilientProtocol {}
// CHECK-LABEL: sil hidden @$s19protocol_resilience22inoutResilientProtocolyyAA19OtherConformingTypeVzF
func inoutResilientProtocol(_ x: inout OtherConformingType) {
// CHECK: function_ref @$s18resilient_protocol22OtherResilientProtocolPAAE19propertyInExtensionSivM
inoutFunc(&x.propertyInExtension)
// CHECK: function_ref @$s18resilient_protocol22OtherResilientProtocolPAAE25staticPropertyInExtensionSivM
inoutFunc(&OtherConformingType.staticPropertyInExtension)
}
// Protocol is public -- needs resilient witness table
public struct ConformsToP: P { }
public protocol ResilientAssocTypes {
associatedtype AssocType: P = ConformsToP
}
// CHECK-LABEL: sil_default_witness_table P {
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientMethods {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.defaultWitness!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP14defaultWitnessyyF
// CHECK-NEXT: method #ResilientMethods.anotherDefaultWitness!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP21anotherDefaultWitnessyxSiF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessWithAssociatedType!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP32defaultWitnessWithAssociatedTypeyy05AssocI0QzF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanRequirement!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP41defaultWitnessMoreAbstractThanRequirement_1by9AssocTypeQz_SitF
// CHECK-NEXT: method #ResilientMethods.defaultWitnessMoreAbstractThanGenericRequirement!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP48defaultWitnessMoreAbstractThanGenericRequirement_1ty9AssocTypeQz_qd__tlF
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientMethods.staticDefaultWitness!1: {{.*}} : @$s19protocol_resilience16ResilientMethodsP20staticDefaultWitnessyxSiFZ
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientConstructors {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @$s19protocol_resilience21ResilientConstructorsP7defaultxyt_tcfC
// CHECK-NEXT: method #ResilientConstructors.init!allocator.1: {{.*}} : @$s19protocol_resilience21ResilientConstructorsP17defaultIsOptionalxSgyt_tcfC
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientStorage {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.propertyWithDefault!getter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP19propertyWithDefaultSivg
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!getter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivg
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!setter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivs
// CHECK-NEXT: method #ResilientStorage.mutablePropertyWithDefault!modify.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP26mutablePropertyWithDefaultSivM
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!getter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvg
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!setter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvs
// CHECK-NEXT: method #ResilientStorage.mutableGenericPropertyWithDefault!modify.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP33mutableGenericPropertyWithDefault1TQzvM
// CHECK-NEXT: method #ResilientStorage.subscript!getter.1: {{.*}} : @$s19protocol_resilience16ResilientStoragePy1TQzAEcig
// CHECK-NEXT: method #ResilientStorage.subscript!setter.1: {{.*}} : @$s19protocol_resilience16ResilientStoragePy1TQzAEcis
// CHECK-NEXT: method #ResilientStorage.subscript!modify.1: {{.*}} : @$s19protocol_resilience16ResilientStoragePy1TQzAEciM
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!getter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivg
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!setter.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivs
// CHECK-NEXT: method #ResilientStorage.mutatingGetterWithNonMutatingDefault!modify.1: {{.*}} : @$s19protocol_resilience16ResilientStorageP36mutatingGetterWithNonMutatingDefaultSivM
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientOperators {
// CHECK-NEXT: no_default
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ResilientOperators."~~~"!1: {{.*}} : @$s19protocol_resilience18ResilientOperatorsP3tttopyyxFZ
// CHECK-NEXT: method #ResilientOperators."<*>"!1: {{.*}} : @$s19protocol_resilience18ResilientOperatorsP3lmgoiyyx_qd__tlFZ
// CHECK-NEXT: method #ResilientOperators."<**>"!1: {{.*}} : @$s19protocol_resilience18ResilientOperatorsP4lmmgoiy9AssocTypeQzqd___xtlFZ
// CHECK-NEXT: method #ResilientOperators."<===>"!1: {{.*}} : @$s19protocol_resilience18ResilientOperatorsP5leeegoiy9AssocTypeQyd__qd___xtAaBRd__lFZ
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ReabstractSelfRefined {
// CHECK-NEXT: no_default
// CHECK-NEXT: method #ReabstractSelfRefined.callback!getter.1: {{.*}} : @$s19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvg
// CHECK-NEXT: method #ReabstractSelfRefined.callback!setter.1: {{.*}} : @$s19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvs
// CHECK-NEXT: method #ReabstractSelfRefined.callback!modify.1: {{.*}} : @$s19protocol_resilience21ReabstractSelfRefinedP8callbackyxxcvM
// CHECK-NEXT: }
// CHECK-LABEL: sil_default_witness_table ResilientAssocTypes {
// CHECK-NEXT: associated_type_protocol (AssocType: P): ConformsToP: P module protocol_resilience
// CHECK-NEXT: associated_type AssocType: ConformsToP
// CHECK-NEXT: }
| apache-2.0 | 95abca801aff4040a76161cf268a6991 | 52.067485 | 296 | 0.783121 | 4.396442 | false | false | false | false |
JohnDuxbury/xcode | Is it prime/Is it prime/ViewController.swift | 1 | 1695 | //
// ViewController.swift
// Is it prime
//
// Created by JD on 25/05/2015.
// Copyright (c) 2015 JDuxbury.me. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var number: UITextField!
@IBOutlet weak var resultLabel: UILabel!
@IBAction func buttonPressed(sender: AnyObject) {
var numberInt = number.text.toInt()
if numberInt != nil
{
var unwrappedNumber = numberInt!
var isPrime = true
if unwrappedNumber == 1
{
isPrime = false
}
if unwrappedNumber != 2 && unwrappedNumber != 1
{
for var i = 2; i < unwrappedNumber; i++
{
if unwrappedNumber % i == 0
{
isPrime = false
}
}
}
if isPrime == true
{
resultLabel.text = "\(unwrappedNumber) is prime!"
}else
{
resultLabel.text = "\(unwrappedNumber) is not prime!"
}
}else
{
resultLabel.text = "Please enter a number in the box"
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
| apache-2.0 | af6d30f59f65e3f41186936deb2b45b6 | 21.302632 | 80 | 0.459587 | 5.707071 | false | false | false | false |
myTargetSDK/mytarget-ios | myTargetDemoSwift/myTargetDemo/Views/TitleView.swift | 1 | 1049 | //
// TitleView.swift
// myTargetDemo
//
// Created by Andrey Seredkin on 19/06/2019.
// Copyright © 2019 Mail.Ru Group. All rights reserved.
//
import UIKit
final class TitleView: UIView {
private let stackView = UIStackView()
let title = UILabel()
let version = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
initialize()
}
required init?(coder: NSCoder) {
super.init(coder: coder)
initialize()
}
private func initialize() {
title.textAlignment = .center
version.textAlignment = .center
title.font = UIFont.systemFont(ofSize: 15)
version.font = UIFont.systemFont(ofSize: 10)
stackView.axis = .vertical
stackView.alignment = .fill
stackView.distribution = .fill
stackView.addArrangedSubview(title)
stackView.addArrangedSubview(version)
addSubview(stackView)
}
override func layoutSubviews() {
super.layoutSubviews()
stackView.frame = bounds
}
}
| lgpl-3.0 | 7f82b5421c8a7213406f3c582f7d50bd | 22.818182 | 56 | 0.629771 | 4.478632 | false | false | false | false |
amnuaym/TiAppBuilder | Day3/MyContactList/MyContactList/AppDelegate.swift | 1 | 5282 | //
// AppDelegate.swift
// MyContactList
//
// Created by Amnuay M on 8/28/17.
// Copyright © 2017 Amnuay M. All rights reserved.
//
import UIKit
import CoreData
import GoogleMobileAds
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
// @UIApplicationMain
// class AppDelegate: UIResponder, UIApplicationDelegate {
//
// var window: UIWindow?
let MyAdmobAppID = "ca-app-pub-7050236446859797~6766047856"
internal func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Initialize the Google Mobile Ads SDK.
// Sample AdMob app ID: ca-app-pub-3940256099942544~1458002511
GADMobileAds.configure(withApplicationID: "\(MyAdmobAppID)")
return true
}
// }
// func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// // Override point for customization after application launch.
// return true
// }
func applicationWillResignActive(_ application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}
func applicationDidEnterBackground(_ application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(_ application: UIApplication) {
// Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(_ application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(_ application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var persistentContainer: NSPersistentContainer = {
/*
The persistent container for the application. This implementation
creates and returns a container, having loaded the store for the
application to it. This property is optional since there are legitimate
error conditions that could cause the creation of the store to fail.
*/
let container = NSPersistentContainer(name: "MyContactList")
container.loadPersistentStores(completionHandler: { (storeDescription, error) in
if let error = error as NSError? {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
/*
Typical reasons for an error here include:
* The parent directory does not exist, cannot be created, or disallows writing.
* The persistent store is not accessible, due to permissions or data protection when the device is locked.
* The device is out of space.
* The store could not be migrated to the current model version.
Check the error message to determine what the actual problem was.
*/
fatalError("Unresolved error \(error), \(error.userInfo)")
}
})
return container
}()
// MARK: - Core Data Saving support
func saveContext () {
let context = persistentContainer.viewContext
if context.hasChanges {
do {
try context.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// fatalError() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
fatalError("Unresolved error \(nserror), \(nserror.userInfo)")
}
}
}
}
| gpl-3.0 | a157f45e5907de28ca0093a46d47c6d9 | 46.576577 | 285 | 0.675819 | 5.765284 | false | false | false | false |
ricardopereira/PremierKit | Source/PremierObfuscator.swift | 1 | 2020 | //
// PremierObfuscator.swift
// PremierKit
//
// Created by Ricardo Pereira on 09/06/2020.
// Copyright © 2020 Ricardo Pereira. All rights reserved.
//
// Credit to https://gist.github.com/DejanEnspyra/80e259e3c9adf5e46632631b49cd1007
//
import Foundation
public class Obfuscator {
// MARK: - Variables
/// The salt used to obfuscate and reveal the string.
private let salt: String
// MARK: - Initialization
public init(with salt: String) {
self.salt = salt
}
// MARK: - Instance Methods
/**
This method obfuscates the string passed in using the salt
that was used when the Obfuscator was initialized.
- parameter string: the string to obfuscate
- returns: the obfuscated string in a byte array
*/
public func bytesByObfuscatingString(string: String) -> [UInt8] {
let text = [UInt8](string.utf8)
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var obfuscated = [UInt8]()
for t in text.enumerated() {
obfuscated.append(t.element ^ cipher[t.offset % length])
}
#if DEBUG
print("\nObfuscator")
print("Salt used: \(self.salt)")
print("Swift Code:\n************")
print("// Original \"\(string)\"")
print("let key: [UInt8] = \(obfuscated)\n")
#endif
return obfuscated
}
/**
This method reveals the original string from the obfuscated
byte array passed in. The salt must be the same as the one
used to encrypt it in the first place.
- parameter key: the byte array to reveal
- returns: the original string
*/
public func reveal(key: [UInt8]) -> String {
let cipher = [UInt8](self.salt.utf8)
let length = cipher.count
var decrypted = [UInt8]()
for k in key.enumerated() {
decrypted.append(k.element ^ cipher[k.offset % length])
}
return String(bytes: decrypted, encoding: .utf8)!
}
}
| mit | 5625a41f835383a7d8549b739d9fae0f | 23.925926 | 83 | 0.607231 | 4.013917 | false | false | false | false |
rvald/Wynfood.iOS | Wynfood/SignInViewController.swift | 1 | 5997 | //
// SignInViewController.swift
// Wynfood
//
// Created by craftman on 6/2/17.
// Copyright © 2017 craftman. All rights reserved.
//
import UIKit
class SignInViewController: UIViewController {
// MARK: - Properties
var logInView: LogInView!
var registerView: RegisterView!
// MARK: - View Cycle
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(self.dissmisView), name: Notification.Name("WynfoodDismissViewNotification"), object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(self.presentAlertView), name: Notification.Name("WynfoodPresentAlertNotification"), object: nil)
view.backgroundColor = UIColor(red: 243.0/255.0, green: 243.0/255.0, blue: 244.0/255.0, alpha: 1.0)
logInView = LogInView(frame: CGRect.zero)
registerView = RegisterView(frame: CGRect.zero)
setupView()
}
// MARK: - Views
let closeButton: UIButton = {
let button = UIButton(type: .system)
button.setTitle("Close", for: .normal)
button.addTarget(self, action: #selector(closeButtonTap), for: .touchUpInside)
button.translatesAutoresizingMaskIntoConstraints = false
return button
}()
let segmentedControl: UISegmentedControl = {
let control = UISegmentedControl(items: ["Log In", "Register"])
control.addTarget(self, action: #selector(segementedControlTapped), for: .valueChanged)
control.tintColor = UIColor(red: 0.0/255.0, green: 122.0/255.0, blue: 255.0/255.0, alpha: 1.0)
control.backgroundColor = UIColor.white
control.selectedSegmentIndex = 0
control.translatesAutoresizingMaskIntoConstraints = false
return control
}()
// MARK: - Methods
func setupView() {
view.addSubview(closeButton)
view.addSubview(segmentedControl)
view.addSubview(registerView)
view.addSubview(logInView)
registerView.isHidden = true
// close button constraints
view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 40.0))
view.addConstraint(NSLayoutConstraint(item: closeButton, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0))
// segmented control constraints
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|-88-[v0(36)]", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": segmentedControl]))
view.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0))
view.addConstraint(NSLayoutConstraint(item: segmentedControl, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0))
// log in view constraints
view.addConstraint(NSLayoutConstraint(item: logInView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0))
view.addConstraint(NSLayoutConstraint(item: logInView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-13-[v0]-24-|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": logInView, "v1": segmentedControl]))
// register view constraints
view.addConstraint(NSLayoutConstraint(item: registerView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: -20.0))
view.addConstraint(NSLayoutConstraint(item: registerView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 20.0))
view.addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:[v1]-13-[v0]|", options: NSLayoutFormatOptions(), metrics: nil, views: ["v0": registerView, "v1": segmentedControl]))
}
func presentAlertView(notification: NSNotification) {
let message = notification.userInfo?["message"] as! String
let alert = UIAlertController(title: "Wynfood", message: message, preferredStyle: .alert)
let action = UIAlertAction(title: "OK", style: .default, handler: nil)
alert.addAction(action)
present(alert, animated: true, completion: nil)
}
func dissmisView() {
dismiss(animated: true, completion: nil)
}
// MARK: - Actions
func closeButtonTap() {
dismiss(animated: true, completion: nil)
}
func segementedControlTapped(sender: UISegmentedControl) {
if sender.selectedSegmentIndex == 1 {
UIView.animate(withDuration: 0.5, animations: {
self.logInView.isHidden = true
}, completion: { (true) in
UIView.animate(withDuration: 0.5, animations: {
self.registerView.isHidden = false
})
})
} else if sender.selectedSegmentIndex == 0 {
UIView.animate(withDuration: 0.5, animations: {
self.registerView.isHidden = true
}, completion: { (true) in
UIView.animate(withDuration: 0.5, animations: {
self.logInView.isHidden = false
})
})
}
}
}
| apache-2.0 | 5b6078122debb91b8f41b1583cb90c47 | 38.447368 | 198 | 0.619913 | 4.847211 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.