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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
qxuewei/XWSwiftWB
|
XWSwiftWB/XWSwiftWB/Classes/Main/Visitor/BaseTableVC.swift
|
1
|
1807
|
//
// BaseTableVC.swift
// XWSwiftWB
//
// Created by 邱学伟 on 16/10/26.
// Copyright © 2016年 邱学伟. All rights reserved.
//
import UIKit
class BaseTableVC: UITableViewController {
let visitorView : VisitorView = VisitorView.visitorView()
var isLogin :Bool = UserAccountViewModel.shareInstance.isLogin
override func loadView() {
isLogin ? super.loadView() : loadVisitorView()
}
override func viewDidLoad() {
super.viewDidLoad()
setItem()
}
}
//MARK: - 设置UI界面
extension BaseTableVC{
///设置访客视图
func loadVisitorView() {
visitorView.loginBtn.addTarget(self, action: #selector(BaseTableVC.login) , for: .touchUpInside)
visitorView.registerBtn.addTarget(self, action: #selector(BaseTableVC.register), for: .touchUpInside)
view = visitorView
}
///设置导航栏左右的按钮
func setItem() {
let loginItem : UIBarButtonItem = UIBarButtonItem(title: "登录", style: .plain, target: self, action: #selector(BaseTableVC.login))
navigationItem.rightBarButtonItem = loginItem
let registerItem : UIBarButtonItem = UIBarButtonItem(title: "注册", style: .plain, target: self, action: #selector(BaseTableVC.register))
navigationItem.leftBarButtonItem = registerItem
}
}
//MARK: - 事件监听
extension BaseTableVC{
func login() {
XWLog("login")
//1.创建授权控制器
let oauthVC = OAuthVC()
//2.包装成导航控制器
let oauthNav = UINavigationController.init(rootViewController: oauthVC)
//3.弹出控制器
present(oauthNav, animated: true, completion: nil)
}
func register(){
XWLog("register")
}
}
|
apache-2.0
|
e69be39c28a2d63890f011faa85afd33
| 26.354839 | 143 | 0.639151 | 4.393782 | false | false | false | false |
Beaver/BeaverCodeGen
|
Pods/Yams/Sources/Yams/Decoder.swift
|
1
|
15208
|
//
// Decoder.swift
// Yams
//
// Created by Norio Nomura on 5/6/17.
// Copyright (c) 2017 Yams. All rights reserved.
//
#if swift(>=4.0)
import Foundation
public class YAMLDecoder {
public init() {}
public func decode<T>(_ type: T.Type = T.self,
from yaml: String,
userInfo: [CodingUserInfoKey: Any] = [:]) throws -> T where T: Swift.Decodable {
do {
let node = try Yams.compose(yaml: yaml, .basic) ?? ""
let decoder = _Decoder(referencing: node, userInfo: userInfo)
let container = try decoder.singleValueContainer()
return try container.decode(T.self)
} catch let error as DecodingError {
throw error
} catch {
throw DecodingError.dataCorrupted(.init(codingPath: [],
debugDescription: "The given data was not valid YAML.",
underlyingError: error))
}
}
}
struct _Decoder: Decoder { // swiftlint:disable:this type_name
private let node: Node
init(referencing node: Node, userInfo: [CodingUserInfoKey: Any], codingPath: [CodingKey] = []) {
self.node = node
self.userInfo = userInfo
self.codingPath = codingPath
}
// MARK: - Swift.Decoder Methods
let codingPath: [CodingKey]
let userInfo: [CodingUserInfoKey: Any]
func container<Key>(keyedBy type: Key.Type) throws -> KeyedDecodingContainer<Key> {
guard let mapping = node.mapping else {
throw _typeMismatch(at: codingPath, expectation: Node.Mapping.self, reality: node)
}
return .init(_KeyedDecodingContainer<Key>(decoder: self, wrapping: mapping))
}
func unkeyedContainer() throws -> UnkeyedDecodingContainer {
guard let sequence = node.sequence else {
throw _typeMismatch(at: codingPath, expectation: Node.Sequence.self, reality: node)
}
return _UnkeyedDecodingContainer(decoder: self, wrapping: sequence)
}
func singleValueContainer() throws -> SingleValueDecodingContainer { return self }
// MARK: -
/// constuct `T` from `node`
fileprivate func construct<T: ScalarConstructible>() throws -> T {
guard let constructed = T.construct(from: node) else {
throw _typeMismatch(at: codingPath, expectation: T.self, reality: node)
}
return constructed
}
/// create a new `_Decoder` instance referencing `node` as `key` inheriting `userInfo`
fileprivate func decoder(referencing node: Node, `as` key: CodingKey) -> _Decoder {
return .init(referencing: node, userInfo: userInfo, codingPath: codingPath + [key])
}
}
struct _KeyedDecodingContainer<K: CodingKey> : KeyedDecodingContainerProtocol {
// swiftlint:disable:previous type_name
typealias Key = K
private let decoder: _Decoder
private let mapping: Node.Mapping
fileprivate init(decoder: _Decoder, wrapping mapping: Node.Mapping) {
self.decoder = decoder
self.mapping = mapping
}
// MARK: - Swift.KeyedDecodingContainerProtocol Methods
var codingPath: [CodingKey] { return decoder.codingPath }
var allKeys: [Key] { return mapping.keys.flatMap { $0.string.flatMap(Key.init(stringValue:)) } }
func contains(_ key: Key) -> Bool { return mapping[key.stringValue] != nil }
func decodeNil(forKey key: Key) throws -> Bool {
return try node(for: key) == Node("null", Tag(.null))
}
func decode(_ type: Bool.Type, forKey key: Key) throws -> Bool { return try decoder(for: key).construct() }
func decode(_ type: Int.Type, forKey key: Key) throws -> Int { return try decoder(for: key).construct() }
func decode(_ type: Int8.Type, forKey key: Key) throws -> Int8 { return try decoder(for: key).construct() }
func decode(_ type: Int16.Type, forKey key: Key) throws -> Int16 { return try decoder(for: key).construct() }
func decode(_ type: Int32.Type, forKey key: Key) throws -> Int32 { return try decoder(for: key).construct() }
func decode(_ type: Int64.Type, forKey key: Key) throws -> Int64 { return try decoder(for: key).construct() }
func decode(_ type: UInt.Type, forKey key: Key) throws -> UInt { return try decoder(for: key).construct() }
func decode(_ type: UInt8.Type, forKey key: Key) throws -> UInt8 { return try decoder(for: key).construct() }
func decode(_ type: UInt16.Type, forKey key: Key) throws -> UInt16 { return try decoder(for: key).construct() }
func decode(_ type: UInt32.Type, forKey key: Key) throws -> UInt32 { return try decoder(for: key).construct() }
func decode(_ type: UInt64.Type, forKey key: Key) throws -> UInt64 { return try decoder(for: key).construct() }
func decode(_ type: Float.Type, forKey key: Key) throws -> Float { return try decoder(for: key).construct() }
func decode(_ type: Double.Type, forKey key: Key) throws -> Double { return try decoder(for: key).construct() }
func decode(_ type: String.Type, forKey key: Key) throws -> String { return try decoder(for: key).construct() }
func decode<T>(_ type: T.Type, forKey key: Key) throws -> T where T: Decodable {
return try decoder(for: key).decode(type) // use SingleValueDecodingContainer's method
}
func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type,
forKey key: Key) throws -> KeyedDecodingContainer<NestedKey> {
return try decoder(for: key).container(keyedBy: type)
}
func nestedUnkeyedContainer(forKey key: Key) throws -> UnkeyedDecodingContainer {
return try decoder(for: key).unkeyedContainer()
}
func superDecoder() throws -> Decoder { return try decoder(for: _YAMLCodingKey.super) }
func superDecoder(forKey key: Key) throws -> Decoder { return try decoder(for: key) }
// MARK: -
private func node(for key: CodingKey) throws -> Node {
guard let node = mapping[key.stringValue] else {
throw _keyNotFound(at: codingPath, key, "No value associated with key \(key) (\"\(key.stringValue)\").")
}
return node
}
private func decoder(for key: CodingKey) throws -> _Decoder {
return decoder.decoder(referencing: try node(for: key), as: key)
}
}
struct _UnkeyedDecodingContainer: UnkeyedDecodingContainer { // swiftlint:disable:this type_name
private let decoder: _Decoder
private let sequence: Node.Sequence
fileprivate init(decoder: _Decoder, wrapping sequence: Node.Sequence) {
self.decoder = decoder
self.sequence = sequence
self.currentIndex = 0
}
// MARK: - Swift.UnkeyedDecodingContainer Methods
var codingPath: [CodingKey] { return decoder.codingPath }
var count: Int? { return sequence.count }
var isAtEnd: Bool { return currentIndex >= sequence.count }
var currentIndex: Int
mutating func decodeNil() throws -> Bool {
try throwErrorIfAtEnd(Any?.self)
if currentNode == Node("null", Tag(.null)) {
currentIndex += 1
return true
} else {
return false
}
}
mutating func decode(_ type: Bool.Type) throws -> Bool { return try construct() }
mutating func decode(_ type: Int.Type) throws -> Int { return try construct() }
mutating func decode(_ type: Int8.Type) throws -> Int8 { return try construct() }
mutating func decode(_ type: Int16.Type) throws -> Int16 { return try construct() }
mutating func decode(_ type: Int32.Type) throws -> Int32 { return try construct() }
mutating func decode(_ type: Int64.Type) throws -> Int64 { return try construct() }
mutating func decode(_ type: UInt.Type) throws -> UInt { return try construct() }
mutating func decode(_ type: UInt8.Type) throws -> UInt8 { return try construct() }
mutating func decode(_ type: UInt16.Type) throws -> UInt16 { return try construct() }
mutating func decode(_ type: UInt32.Type) throws -> UInt32 { return try construct() }
mutating func decode(_ type: UInt64.Type) throws -> UInt64 { return try construct() }
mutating func decode(_ type: Float.Type) throws -> Float { return try construct() }
mutating func decode(_ type: Double.Type) throws -> Double { return try construct() }
mutating func decode(_ type: String.Type) throws -> String { return try construct() }
mutating func decode<T>(_ type: T.Type) throws -> T where T: Decodable {
try throwErrorIfAtEnd(type)
let value = try currentDecoder.decode(type) // use SingleValueDecodingContainer's method
currentIndex += 1
return value
}
mutating func nestedContainer<NestedKey>(keyedBy type: NestedKey.Type) throws -> KeyedDecodingContainer<NestedKey> {
// swiftlint:disable:previous line_length
try throwErrorIfAtEnd(KeyedDecodingContainer<NestedKey>.self)
let container = try currentDecoder.container(keyedBy: type)
currentIndex += 1
return container
}
mutating func nestedUnkeyedContainer() throws -> UnkeyedDecodingContainer {
try throwErrorIfAtEnd(UnkeyedDecodingContainer.self)
let container = try currentDecoder.unkeyedContainer()
currentIndex += 1
return container
}
mutating func superDecoder() throws -> Decoder {
try throwErrorIfAtEnd(Decoder.self)
defer { currentIndex += 1 }
return currentDecoder
}
// MARK: -
private var currentKey: CodingKey { return _YAMLCodingKey(index: currentIndex) }
private var currentNode: Node { return sequence[currentIndex] }
private var currentDecoder: _Decoder { return decoder.decoder(referencing: currentNode, as: currentKey) }
private func throwErrorIfAtEnd<T>(_ type: T.Type) throws {
if isAtEnd { throw _valueNotFound(at: codingPath + [currentKey], type, "Unkeyed container is at end.") }
}
private mutating func construct<T: ScalarConstructible>() throws -> T {
try throwErrorIfAtEnd(T.self)
let decoded: T = try currentDecoder.construct()
currentIndex += 1
return decoded
}
}
extension _Decoder: SingleValueDecodingContainer {
// MARK: - Swift.SingleValueDecodingContainer Methods
func decodeNil() -> Bool { return node.null == NSNull() }
func decode(_ type: Bool.Type) throws -> Bool { return try construct() }
func decode(_ type: Int.Type) throws -> Int { return try construct() }
func decode(_ type: Int8.Type) throws -> Int8 { return try construct() }
func decode(_ type: Int16.Type) throws -> Int16 { return try construct() }
func decode(_ type: Int32.Type) throws -> Int32 { return try construct() }
func decode(_ type: Int64.Type) throws -> Int64 { return try construct() }
func decode(_ type: UInt.Type) throws -> UInt { return try construct() }
func decode(_ type: UInt8.Type) throws -> UInt8 { return try construct() }
func decode(_ type: UInt16.Type) throws -> UInt16 { return try construct() }
func decode(_ type: UInt32.Type) throws -> UInt32 { return try construct() }
func decode(_ type: UInt64.Type) throws -> UInt64 { return try construct() }
func decode(_ type: Float.Type) throws -> Float { return try construct() }
func decode(_ type: Double.Type) throws -> Double { return try construct() }
func decode(_ type: String.Type) throws -> String { return try construct() }
func decode<T>(_ type: T.Type) throws -> T where T: Decodable { return try decode() ?? T(from: self) }
// MARK: -
private func decode<T>() throws -> T? {
guard let constructibleType = T.self as? ScalarConstructible.Type else {
return nil
}
guard let value = constructibleType.construct(from: node) else {
throw _valueNotFound(at: codingPath, T.self, "Expected \(T.self) value but found null instead.")
}
return value as? T
}
}
// MARK: - DecodingError helpers
private func _keyNotFound(at codingPath: [CodingKey], _ key: CodingKey, _ description: String) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return.keyNotFound(key, context)
}
private func _valueNotFound(at codingPath: [CodingKey], _ type: Any.Type, _ description: String) -> DecodingError {
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return .valueNotFound(type, context)
}
private func _typeMismatch(at codingPath: [CodingKey], expectation: Any.Type, reality: Any) -> DecodingError {
let description = "Expected to decode \(expectation) but found \(type(of: reality)) instead."
let context = DecodingError.Context(codingPath: codingPath, debugDescription: description)
return .typeMismatch(expectation, context)
}
extension FixedWidthInteger where Self: SignedInteger {
public static func construct(from node: Node) -> Self? {
guard let int = Int.construct(from: node) else { return nil }
return Self.init(exactly: int)
}
}
extension FixedWidthInteger where Self: UnsignedInteger {
public static func construct(from node: Node) -> Self? {
guard let int = UInt.construct(from: node) else { return nil }
return Self.init(exactly: int)
}
}
extension Int16: ScalarConstructible {}
extension Int32: ScalarConstructible {}
extension Int64: ScalarConstructible {}
extension Int8: ScalarConstructible {}
extension UInt16: ScalarConstructible {}
extension UInt32: ScalarConstructible {}
extension UInt64: ScalarConstructible {}
extension UInt8: ScalarConstructible {}
extension Decimal: ScalarConstructible {
public static func construct(from node: Node) -> Decimal? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
return Decimal(string: node.scalar!.string)
}
}
extension URL: ScalarConstructible {
public static func construct(from node: Node) -> URL? {
assert(node.isScalar) // swiftlint:disable:next force_unwrapping
return URL(string: node.scalar!.string)
}
}
#endif
|
mit
|
64ed00d36ae52ffd06c25bfbc9ffbcc0
| 45.650307 | 124 | 0.61632 | 4.739171 | false | false | false | false |
spacedrabbit/SRZoomTransition
|
SRZoomTransition/SRZoomTransition/Cat.swift
|
1
|
915
|
//
// Cat.swift
// SRZoomTransition
//
// Created by Louis Tur on 11/7/15.
// Copyright © 2015 Louis Tur. All rights reserved.
//
import Foundation
import UIKit
import Alamofire
public class Cat {
public var id: String = String()
public var url: String = String()
public var sourceUrl: String = String()
public var catImage: UIImage? = UIImage(named: "placeholderCat")
public init() {
}
required public init(WithId id: String, url: String, sourceUrl: String) {
self.id = id
self.url = url
self.sourceUrl = sourceUrl
self.getImageForUrl(self.url)
}
private func getImageForUrl(catImageUrl: String) {
Alamofire.request(.GET, catImageUrl).responseData({ (response) -> Void in
if let catImageData: NSData = response.data {
if let catImage: UIImage = UIImage(data: catImageData) {
self.catImage = catImage
}
}
})
}
}
|
mit
|
407f22e6207aa24b30c7abacde4ff4af
| 21.875 | 77 | 0.652079 | 3.808333 | false | false | false | false |
SkywellDevelopers/SWSkelethon
|
Example/SWSkelethon/Core/Helpers/Constants.swift
|
1
|
1241
|
//
// Constants.swift
// TemplateProject
//
// Created by Krizhanovskii on 3/3/17.
// Copyright © 2017 skywell.com.ua. All rights reserved.
//
import Foundation
import UIKit
import SWSkelethon
struct Constants {
// Server
struct Server {
static let kBaseUrl = ""
}
// Time values
struct Time {
static let kStandartTime = 0.75
static let kShortTime = 0.35
}
// Keys
enum Keys : String {
case firstLaunch = "FirstLaunch"
func getValue() -> Any? {
let _value = UserDefaults.standard.value(forKey: self.rawValue)
Log.info.log("Getting value for key: <\(self.rawValue)> -> <\(_value)>")
return _value
}
func setValue(_ value:Any) {
Log.info.log("Set value: <\(value)> for key: <\(self.rawValue)>")
UserDefaults.standard.set(value, forKey: self.rawValue)
}
func removeValue() {
Log.info.log("Remove value for key: <\(self.rawValue)>")
UserDefaults.standard.removeObject(forKey: self.rawValue)
}
}
// layer
struct layer {
static let kCornerRaidus : CGFloat = 6
}
}
|
mit
|
2e23b62c4e8dde2e58ca71b7910cf9b7
| 21.545455 | 84 | 0.550806 | 4.161074 | false | false | false | false |
bitomule/KFSwiftImageLoader
|
SwiftImageLoader/MainViewController.swift
|
5
|
4875
|
//
// Created by Kiavash Faisali on 2015-03-17.
// Copyright (c) 2015 Kiavash Faisali. All rights reserved.
//
import UIKit
import KFSwiftImageLoader
final class MainViewController: UIViewController, UITableViewDataSource {
// MARK: - Properties
@IBOutlet weak var imagesTableView: UITableView!
var imageURLStringsArray = [String]()
// MARK: - Memory Warning
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
// MARK: - View Lifecycle
override func viewDidLoad() {
super.viewDidLoad()
loadDuckDuckGoResults()
}
// MARK: - Miscellaneous Methods
func loadDuckDuckGoResults() {
let session = NSURLSession.sharedSession()
let url = NSURL(string: "http://api.duckduckgo.com/?q=simpsons+characters&format=json")!
let request = NSURLRequest(URL: url, cachePolicy: .ReturnCacheDataElseLoad, timeoutInterval: 60.0)
let dataTask = session.dataTaskWithRequest(request) {
(data, response, error) in
dispatch_async(dispatch_get_main_queue()) {
if error == nil {
var jsonError: NSError?
if let jsonDict = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &jsonError) as? [String: AnyObject] where jsonError == nil {
if let relatedTopics = jsonDict["RelatedTopics"] as? [[String: AnyObject]] {
for relatedTopic in relatedTopics {
if let imageURLString = relatedTopic["Icon"]?["URL"] as? String {
if imageURLString != "" {
for _ in 1...3 {
self.imageURLStringsArray.append(imageURLString)
}
}
}
}
if self.imageURLStringsArray.count > 0 {
// Uncomment to randomize the image ordering.
// self.randomizeImages()
self.imagesTableView.reloadData()
}
}
}
}
}
}
dataTask.resume()
}
func randomizeImages() {
for (var i = 0; i < self.imageURLStringsArray.count; i++) {
let randomIndex = Int(arc4random()) % self.imageURLStringsArray.count
let tempValue = self.imageURLStringsArray[randomIndex]
self.imageURLStringsArray[randomIndex] = self.imageURLStringsArray[i]
self.imageURLStringsArray[i] = tempValue
}
}
// MARK: - Protocol Implementations
// MARK: - UITableViewDataSource Protocol
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.imageURLStringsArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
// Even indices should contain imageview cells.
if indexPath.row % 2 == 0 {
let cellIdentifier = "ImageTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ImageTableViewCell
cell.featuredImageView.loadImageFromURLString(self.imageURLStringsArray[indexPath.row], placeholderImage: UIImage(named: "KiavashFaisali")) {
(finished, error) in
if finished {
// Do something in the completion block.
}
else if error != nil {
println("error occurred with description: \(error.localizedDescription)")
}
}
return cell
}
// Odd indices should contain button cells.
else {
let cellIdentifier = "ButtonImageTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! ButtonImageTableViewCell
// Notice that the completion block can be ommitted, since it defaults to nil. The controlState and isBackgroundImage parameters can also be ommitted, as they default to .Normal and false, respectively.
// Please read the documentation for more information.
cell.featuredButtonView.loadImageFromURLString(self.imageURLStringsArray[indexPath.row], placeholderImage: UIImage(named: "KiavashFaisali"), forState: .Normal, isBackgroundImage: false)
return cell
}
}
}
|
mit
|
ff9aa55320a97344dc59b9e387cf0388
| 42.526786 | 214 | 0.564308 | 5.966952 | false | false | false | false |
bitomule/KFSwiftImageLoader
|
KFSwiftImageLoader/KFImageCacheManager.swift
|
1
|
11297
|
/*
KFSwiftImageLoader is available under the MIT license.
Copyright (c) 2015 Kiavash Faisali
https://github.com/kiavashfaisali
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.
*/
//
// Created by Kiavash Faisali on 2015-03-17.
// Copyright (c) 2015 Kiavash Faisali. All rights reserved.
//
import UIKit
import MapKit
import WatchKit
// MARK: - Completion Holder Class
final internal class CompletionHolder {
var completion: ((finished: Bool, error: NSError!) -> Void)?
init(completion: ((Bool, error: NSError!) -> Void)?) {
self.completion = completion
}
}
// MARK: - KFImageCacheManager Class
final public class KFImageCacheManager {
// MARK: - Properties
private struct ImageCacheKeys {
static let img = "img"
static let isDownloading = "isDownloading"
static let observerMapping = "observerMapping"
}
public static let sharedInstance = KFImageCacheManager()
// {"url": {"img": UIImage, "isDownloading": Bool, "observerMapping": {Observer: Int}}}
private var imageCache = [String: [String: AnyObject]]()
internal let session: NSURLSession = {
let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
configuration.requestCachePolicy = .ReturnCacheDataElseLoad
configuration.URLCache = .sharedURLCache()
return NSURLSession(configuration: configuration)
}()
/**
Sets the fade duration time (in seconds) for images when they are being loaded into their views.
A value of 0 implies no fade animation.
The default value is 0.1 seconds.
- returns: An NSTimeInterval value representing time in seconds.
*/
public var fadeAnimationDuration: NSTimeInterval = 0.1
/**
Sets the maximum time (in seconds) that the disk cache will use to maintain a cached response.
The default value is 604800 seconds (1 week).
- returns: An unsigned integer value representing time in seconds.
*/
public var diskCacheMaxAge: UInt = 60 * 60 * 24 * 7 {
willSet {
if newValue == 0 {
NSURLCache.sharedURLCache().removeAllCachedResponses()
}
}
}
/**
Sets the maximum time (in seconds) that the request should take before timing out.
The default value is 60 seconds.
- returns: An NSTimeInterval value representing time in seconds.
*/
public var timeoutIntervalForRequest: NSTimeInterval = 60.0 {
willSet {
self.session.configuration.timeoutIntervalForRequest = newValue
}
}
/**
Sets the cache policy which the default requests and underlying session configuration use to determine caching behaviour.
The default value is ReturnCacheDataElseLoad.
- returns: An NSURLRequestCachePolicy value representing the cache policy.
*/
public var requestCachePolicy: NSURLRequestCachePolicy = .ReturnCacheDataElseLoad {
willSet {
self.session.configuration.requestCachePolicy = newValue
}
}
private init() {
// Initialize the disk cache capacity to 50 MB.
let diskURLCache = NSURLCache(memoryCapacity: 0, diskCapacity: 50 * 1024 * 1024, diskPath: nil)
NSURLCache.setSharedURLCache(diskURLCache)
NSNotificationCenter.defaultCenter().addObserverForName(UIApplicationDidReceiveMemoryWarningNotification, object: nil, queue: NSOperationQueue.mainQueue()) {
_ in
self.imageCache.removeAll(keepCapacity: false)
}
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
// MARK: - Image Cache Subscripting
internal subscript (key: String) -> UIImage? {
get {
return imageCacheEntryForKey(key)[ImageCacheKeys.img] as? UIImage
}
set {
if let image = newValue {
var imageCacheEntry = imageCacheEntryForKey(key)
imageCacheEntry[ImageCacheKeys.img] = image
setImageCacheEntry(imageCacheEntry, forKey: key)
if let observerMapping = imageCacheEntry[ImageCacheKeys.observerMapping] as? [NSObject: Int] {
for (observer, initialIndexIdentifier) in observerMapping {
switch observer {
case let imageView as UIImageView:
loadObserverAsImageView(imageView, forImage: image, withInitialIndexIdentifier: initialIndexIdentifier)
case let button as UIButton:
loadObserverAsButton(button, forImage: image, withInitialIndexIdentifier: initialIndexIdentifier)
case let annotationView as MKAnnotationView:
loadObserverAsAnnotationView(annotationView, forImage: image)
case let interfaceImage as WKInterfaceImage:
loadObserverAsInterfaceImage(interfaceImage, forImage: image, withKey: key)
default:
break
}
}
removeImageCacheObserversForKey(key)
}
}
}
}
// MARK: - Image Cache Methods
internal func imageCacheEntryForKey(key: String) -> [String: AnyObject] {
if let imageCacheEntry = self.imageCache[key] {
return imageCacheEntry
}
else {
let imageCacheEntry: [String: AnyObject] = [ImageCacheKeys.isDownloading: false, ImageCacheKeys.observerMapping: [NSObject: Int]()]
self.imageCache[key] = imageCacheEntry
return imageCacheEntry
}
}
internal func setImageCacheEntry(imageCacheEntry: [String: AnyObject], forKey key: String) {
self.imageCache[key] = imageCacheEntry
}
internal func isDownloadingFromURL(urlString: String) -> Bool {
let isDownloading = imageCacheEntryForKey(urlString)[ImageCacheKeys.isDownloading] as? Bool
return isDownloading ?? false
}
internal func setIsDownloadingFromURL(isDownloading: Bool, forURLString urlString: String) {
var imageCacheEntry = imageCacheEntryForKey(urlString)
imageCacheEntry[ImageCacheKeys.isDownloading] = isDownloading
setImageCacheEntry(imageCacheEntry, forKey: urlString)
}
internal func addImageCacheObserver(observer: NSObject, withInitialIndexIdentifier initialIndexIdentifier: Int, forKey key: String) {
var imageCacheEntry = imageCacheEntryForKey(key)
if var observerMapping = imageCacheEntry[ImageCacheKeys.observerMapping] as? [NSObject: Int] {
observerMapping[observer] = initialIndexIdentifier
imageCacheEntry[ImageCacheKeys.observerMapping] = observerMapping
setImageCacheEntry(imageCacheEntry, forKey: key)
}
}
internal func removeImageCacheObserversForKey(key: String) {
var imageCacheEntry = imageCacheEntryForKey(key)
if var observerMapping = imageCacheEntry[ImageCacheKeys.observerMapping] as? [NSObject: Int] {
observerMapping.removeAll(keepCapacity: false)
imageCacheEntry[ImageCacheKeys.observerMapping] = observerMapping
setImageCacheEntry(imageCacheEntry, forKey: key)
}
}
// MARK: - Observer Methods
internal func loadObserverAsImageView(observer: UIImageView, forImage image: UIImage, withInitialIndexIdentifier initialIndexIdentifier: Int) {
if initialIndexIdentifier == observer.indexPathIdentifier {
dispatch_async(dispatch_get_main_queue()) {
UIView.transitionWithView(observer, duration: self.fadeAnimationDuration, options: .TransitionCrossDissolve, animations: {
observer.image = image
}, completion: nil)
observer.completionHolder.completion?(finished: true, error: nil)
}
}
else {
observer.completionHolder.completion?(finished: false, error: nil)
}
}
internal func loadObserverAsButton(observer: UIButton, forImage image: UIImage, withInitialIndexIdentifier initialIndexIdentifier: Int) {
if initialIndexIdentifier == observer.indexPathIdentifier {
dispatch_async(dispatch_get_main_queue()) {
UIView.transitionWithView(observer, duration: self.fadeAnimationDuration, options: .TransitionCrossDissolve, animations: {
if observer.isBackgroundImage == true {
observer.setBackgroundImage(image, forState: observer.controlStateHolder.controlState)
}
else {
observer.setImage(image, forState: observer.controlStateHolder.controlState)
}
}, completion: nil)
observer.completionHolder.completion?(finished: true, error: nil)
}
}
else {
observer.completionHolder.completion?(finished: false, error: nil)
}
}
internal func loadObserverAsAnnotationView(observer: MKAnnotationView, forImage image: UIImage) {
dispatch_async(dispatch_get_main_queue()) {
UIView.transitionWithView(observer, duration: self.fadeAnimationDuration, options: .TransitionCrossDissolve, animations: {
observer.image = image
}, completion: nil)
observer.completionHolder.completion?(finished: true, error: nil)
}
}
internal func loadObserverAsInterfaceImage(observer: WKInterfaceImage, forImage image: UIImage, withKey key: String) {
dispatch_async(dispatch_get_main_queue()) {
// If there's already a cached image on the Apple Watch, simply set the image directly.
if WKInterfaceDevice.currentDevice().cachedImages[key] != nil {
observer.setImageNamed(key)
}
else {
observer.setImageData(UIImagePNGRepresentation(image))
}
observer.completionHolder.completion?(finished: true, error: nil)
}
}
}
|
mit
|
657a97e97ed8d6087443e628219b01ab
| 43.476378 | 464 | 0.654953 | 5.505361 | false | false | false | false |
drmohundro/SWXMLHash
|
SWXMLHashPlayground.playground/Pages/Introduction.xcplaygroundpage/Contents.swift
|
1
|
2273
|
// swiftlint:disable force_unwrapping
/*:
## SWXMLHash Playground
SWXMLHash is a relatively simple way to parse XML in Swift.
Feel free to play around here with the samples and try the library out.
### Simple example
*/
import Foundation
import SWXMLHash
let xmlWithNamespace = """
<root xmlns:h=\"http://www.w3.org/TR/html4/\"
xmlns:f=\"http://www.w3schools.com/furniture\">
<h:table>
<h:tr>
<h:td>Apples</h:td>
<h:td>Bananas</h:td>
</h:tr>
</h:table>
<f:table>
<f:name>African Coffee Table</f:name>
<f:width>80</f:width>
<f:length>120</f:length>
</f:table>
</root>
"""
var xml = XMLHash.parse(xmlWithNamespace)
// one root element
let count = xml["root"].all.count
// "Apples"
xml["root"]["h:table"]["h:tr"]["h:td"][0].element!.text
// enumerate all child elements (procedurally)
func enumerate(indexer: XMLIndexer, level: Int) {
for child in indexer.children {
let name = child.element!.name
print("\(level) \(name)")
enumerate(indexer: child, level: level + 1)
}
}
enumerate(indexer: xml, level: 0)
// enumerate all child elements (functionally)
func reduceName(names: String, elem: XMLIndexer) -> String {
return names + elem.element!.name + elem.children.reduce(", ", reduceName)
}
xml.children.reduce("elements: ", reduceName)
//: ### Custom Conversion/Deserialization
// custom types conversion
let booksXML = """
<root>
<books>
<book>
<title>Book A</title>
<price>12.5</price>
<year>2015</year>
</book>
<book>
<title>Book B</title>
<price>10</price>
<year>1988</year>
</book>
<book>
<title>Book C</title>
<price>8.33</price>
<year>1990</year>
<amount>10</amount>
</book>
<books>
</root>
"""
struct Book: XMLObjectDeserialization {
let title: String
let price: Double
let year: Int
let amount: Int?
static func deserialize(_ node: XMLIndexer) throws -> Book {
return try Book(
title: node["title"].value(),
price: node["price"].value(),
year: node["year"].value(),
amount: node["amount"].value()
)
}
}
xml = XMLHash.parse(booksXML)
let books: [Book] = try xml["root"]["books"]["book"].value()
|
mit
|
cc57c693d41b609950a67cbf2d1015a2
| 20.855769 | 78 | 0.610207 | 3.332845 | false | false | false | false |
jlandon/Alexandria
|
Sources/Alexandria/UICollectionView+Extensions.swift
|
1
|
13289
|
//
// UICollectionView+Extensions.swift
//
// Created by Jonathan Landon on 11/19/15.
//
// The MIT License (MIT)
//
// Copyright (c) 2014-2016 Oven Bits, LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import UIKit
extension UICollectionView {
/// Returns a UICollectionView with the specified layout.
public convenience init(layout: UICollectionViewFlowLayout) {
self.init(frame: .zero, collectionViewLayout: layout)
}
// MARK: Cells
/**
Registers a UICollectionViewCell for use in a UICollectionView.
- parameter type: The type of cell to register.
- parameter reuseIdentifier: The reuse identifier for the cell (optional).
By default, the class name of the cell is used as the reuse identifier.
Example:
```
class CustomCell: UICollectionViewCell {}
let collectionView = UICollectionView()
// registers the CustomCell class with a reuse identifier of "CustomCell"
collectionView.registerCell(CustomCell)
```
*/
public func registerCell<T: UICollectionViewCell>(_ type: T.Type, withIdentifier reuseIdentifier: String = String(describing: T.self)) {
register(T.self, forCellWithReuseIdentifier: reuseIdentifier)
}
/**
Dequeues a UICollectionViewCell for use in a UICollectionView.
- parameter type: The type of the cell.
- parameter indexPath: The index path at which to dequeue a new cell.
- parameter reuseIdentifier: The reuse identifier for the cell (optional).
- returns: A force-casted UICollectionViewCell of the specified type.
By default, the class name of the cell is used as the reuse identifier.
Example:
```
class CustomCell: UICollectionViewCell {}
let collectionView = UICollectionView()
// dequeues a CustomCell class
let cell = collectionView.dequeueReusableCell(CustomCell.self, forIndexPath: indexPath)
```
*/
public func dequeueCell<T: UICollectionViewCell>(_ type: T.Type = T.self,
withIdentifier reuseIdentifier: String = String(describing: T.self),
for indexPath: IndexPath) -> T
{
guard let cell = dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as? T else {
fatalError("Unknown cell type (\(T.self)) for reuse identifier: \(reuseIdentifier)")
}
return cell
}
// MARK: Headers
/**
Registers a UICollectionReusableView for use in a UICollectionView section header.
- parameter type: The type of header view to register.
- parameter reuseIdentifier: The reuse identifier for the header view (optional).
By default, the class name of the header view is used as the reuse identifier.
Example:
```
class CustomHeader: UICollectionReusableView {}
let collectionView = UICollectionView()
// registers the CustomCell class with a reuse identifier of "CustomHeader"
collectionView.registerHeader(CustomHeader)
```
*/
public func registerHeader<T: UICollectionReusableView>(_ type: T.Type, withIdentifier reuseIdentifier: String = String(describing: T.self)) {
register(T.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: reuseIdentifier)
}
/**
Dequeues a UICollectionReusableView for use in a UICollectionView section header.
- parameter type: The type of the header view.
- parameter indexPath: The index path at which to dequeue a new header view.
- parameter reuseIdentifier: The reuse identifier for the header view (optional).
- returns: A force-casted UICollectionReusableView of the specified type.
By default, the class name of the header view is used as the reuse identifier.
Example:
```
class CustomHeader: UICollectionReusableView {}
let collectionView = UICollectionView()
// dequeues a CustomHeader class
let footerView = collectionView.dequeueReusableHeader(CustomHeader.self, forIndexPath: indexPath)
```
*/
public func dequeueHeader<T: UICollectionReusableView>(_ type: T.Type = T.self,
withIdentifier reuseIdentifier: String = String(describing: T.self),
for indexPath: IndexPath) -> T
{
guard let header = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionHeader, withReuseIdentifier: reuseIdentifier, for: indexPath) as? T else {
fatalError("Unknown header type (\(T.self)) for reuse identifier: \(reuseIdentifier)")
}
return header
}
// MARK: Footers
/**
Registers a UICollectionReusableView for use in a UICollectionView section footer.
- parameter type: The type of footer view to register.
- parameter reuseIdentifier: The reuse identifier for the footer view (optional).
By default, the class name of the footer view is used as the reuse identifier.
Example:
```
class CustomFooter: UICollectionReusableView {}
let collectionView = UICollectionView()
// registers the CustomFooter class with a reuse identifier of "CustomFooter"
collectionView.registerFooter(CustomFooter)
```
*/
public func registerFooter<T: UICollectionReusableView>(_ type: T.Type, withIdentifier reuseIdentifier: String = String(describing: T.self)) {
register(T.self, forSupplementaryViewOfKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: reuseIdentifier)
}
/**
Dequeues a UICollectionReusableView for use in a UICollectionView section footer.
- parameter type: The type of the footer view.
- parameter indexPath: The index path at which to dequeue a new footer view.
- parameter reuseIdentifier: The reuse identifier for the footer view (optional).
- returns: A force-casted UICollectionReusableView of the specified type.
By default, the class name of the footer view is used as the reuse identifier.
Example:
```
class CustomFooter: UICollectionReusableView {}
let collectionView = UICollectionView()
// dequeues a CustomFooter class
let footerView = collectionView.dequeueReusableFooter(CustomFooter.self, forIndexPath: indexPath)
```
*/
public func dequeueFooter<T: UICollectionReusableView>(_ type: T.Type = T.self,
withIdentifier reuseIdentifier: String = String(describing: T.self),
for indexPath: IndexPath) -> T
{
guard let footer = dequeueReusableSupplementaryView(ofKind: UICollectionView.elementKindSectionFooter, withReuseIdentifier: reuseIdentifier, for: indexPath) as? T else {
fatalError("Unknown footer type (\(T.self)) for reuse identifier: \(reuseIdentifier)")
}
return footer
}
/**
Inserts rows into self.
- parameter indices: The rows indices to insert into self.
- parameter section: The section in which to insert the rows (optional, defaults to 0).
- parameter completion: The completion handler, called after the rows have been inserted (optional).
*/
public func insert(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) {
guard !indices.isEmpty else { return }
let indexPaths = indices.map { IndexPath(row: $0, section: section) }
performBatchUpdates({ self.insertItems(at: indexPaths) }, completion: completion)
}
/**
Deletes rows from self.
- parameter indices: The rows indices to delete from self.
- parameter section: The section in which to delete the rows (optional, defaults to 0).
- parameter completion: The completion handler, called after the rows have been deleted (optional).
*/
public func delete(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) {
guard !indices.isEmpty else { return }
let indexPaths = indices.map { IndexPath(row: $0, section: section) }
performBatchUpdates({ self.deleteItems(at: indexPaths) }, completion: completion)
}
/**
Reloads rows in self.
- parameter indices: The rows indices to reload in self.
- parameter section: The section in which to reload the rows (optional, defaults to 0).
- parameter completion: The completion handler, called after the rows have been reloaded (optional).
*/
public func reload(_ indices: [Int], section: Int = 0, completion: @escaping (Bool) -> Void = { _ in }) {
guard !indices.isEmpty else { return }
let indexPaths = indices.map { IndexPath(row: $0, section: section) }
performBatchUpdates({ self.reloadItems(at: indexPaths) }, completion: completion)
}
}
// MARK: - IndexPathTraversing
extension UICollectionView {
/// The minimum ("starting") `IndexPath` for traversing a `UICollectionView` "sequentially".
public var minimumIndexPath: IndexPath {
return IndexPath(item: 0, section: 0)
}
/// The maximum ("ending") `IndexPath` for traversing a `UICollectionView` "sequentially".
public var maximumIndexPath: IndexPath {
let lastSection = max(0, numberOfSections - 1)
let lastItem = max(0, numberOfItems(inSection: lastSection) - 1)
return IndexPath(item: lastItem, section: lastSection)
}
/**
When "sequentially" traversing a `UICollectionView`, what's the next `IndexPath` after the given `IndexPath`.
- parameter indexPath: The current indexPath; the path we want to find what comes after.
- returns: The next indexPath, or nil if we're at the maximumIndexPath
- SeeAlso: `var maximumIndexpath`
*/
public func indexPath(after indexPath: IndexPath) -> IndexPath? {
if indexPath == maximumIndexPath {
return nil
}
assertIsValid(indexPath: indexPath)
let lastItem = numberOfItems(inSection: indexPath.section)
if indexPath.item == lastItem {
return IndexPath(item: 0, section: indexPath.section + 1)
} else {
return IndexPath(item: indexPath.item + 1, section: indexPath.section)
}
}
/**
When "sequentially" traversing a `UICollectionView`, what's the previous `IndexPath` before the given `IndexPath`.
- parameter indexPath: The current indexPath; the path we want to find what comes before.
- returns: The prior indexPath, or nil if we're at the minimumIndexPath
- SeeAlso: `var minimumIndexPath`
*/
public func indexPath(before indexPath: IndexPath) -> IndexPath? {
if indexPath == minimumIndexPath {
return nil
}
assertIsValid(indexPath: indexPath)
if indexPath.item == 0 {
let lastItem = numberOfItems(inSection: indexPath.section - 1)
return IndexPath(item: lastItem, section: indexPath.section - 1)
} else {
return IndexPath(item: indexPath.item - 1, section: indexPath.section)
}
}
private func assertIsValid(indexPath: IndexPath, file: StaticString = #file, line: UInt = #line) {
let maxPath = maximumIndexPath
assert(
indexPath.section <= maxPath.section && indexPath.section >= 0,
"Index path \(indexPath) is outside the bounds set by the minimum (\(minimumIndexPath)) and maximum (\(maxPath)) index path",
file: file,
line: line
)
let itemCount = numberOfItems(inSection: indexPath.section)
assert(
indexPath.item < itemCount && indexPath.item >= 0,
"Index path \(indexPath) item index is outside the bounds of the items (\(itemCount)) in the indexPath's section",
file: file,
line: line
)
}
}
|
mit
|
aae4b6ceaf1f6c2ff236768bfa6c3fc0
| 39.889231 | 177 | 0.660546 | 5.254646 | false | false | false | false |
WeMadeCode/ZXPageView
|
Example/Pods/SwifterSwift/Sources/SwifterSwift/SwiftStdlib/IntExtensions.swift
|
1
|
5997
|
//
// IntExtensions.swift
// SwifterSwift
//
// Created by Omar Albeik on 8/6/16.
// Copyright © 2016 SwifterSwift
//
#if canImport(CoreGraphics)
import CoreGraphics
#endif
// MARK: - Properties
public extension Int {
/// SwifterSwift: CountableRange 0..<Int.
var countableRange: CountableRange<Int> {
return 0..<self
}
/// SwifterSwift: Radian value of degree input.
var degreesToRadians: Double {
return Double.pi * Double(self) / 180.0
}
/// SwifterSwift: Degree value of radian input
var radiansToDegrees: Double {
return Double(self) * 180 / Double.pi
}
/// SwifterSwift: UInt.
var uInt: UInt {
return UInt(self)
}
/// SwifterSwift: Double.
var double: Double {
return Double(self)
}
/// SwifterSwift: Float.
var float: Float {
return Float(self)
}
#if canImport(CoreGraphics)
/// SwifterSwift: CGFloat.
var cgFloat: CGFloat {
return CGFloat(self)
}
#endif
/// SwifterSwift: String formatted for values over ±1000 (example: 1k, -2k, 100k, 1kk, -5kk..)
var kFormatted: String {
var sign: String {
return self >= 0 ? "" : "-"
}
let abs = Swift.abs(self)
if abs == 0 {
return "0k"
} else if abs >= 0 && abs < 1000 {
return "0k"
} else if abs >= 1000 && abs < 1000000 {
return String(format: "\(sign)%ik", abs / 1000)
}
return String(format: "\(sign)%ikk", abs / 100000)
}
/// SwifterSwift: Array of digits of integer value.
var digits: [Int] {
guard self != 0 else { return [0] }
var digits = [Int]()
var number = abs
while number != 0 {
let xNumber = number % 10
digits.append(xNumber)
number /= 10
}
digits.reverse()
return digits
}
#if canImport(Foundation) && !os(Linux)
/// SwifterSwift: Number of digits of integer value.
var digitsCount: Int {
guard self != 0 else { return 1 }
let number = Double(abs)
return Int(log10(number) + 1)
}
#endif
}
// MARK: - Methods
public extension Int {
#if canImport(Foundation) && !os(Linux)
/// SwifterSwift: check if given integer prime or not.
/// Warning: Using big numbers can be computationally expensive!
/// - Returns: true or false depending on prime-ness
func isPrime() -> Bool {
// To improve speed on latter loop :)
if self == 2 { return true }
guard self > 1 && self % 2 != 0 else { return false }
// Explanation: It is enough to check numbers until
// the square root of that number. If you go up from N by one,
// other multiplier will go 1 down to get similar result
// (integer-wise operation) such way increases speed of operation
let base = Int(sqrt(Double(self)))
for int in Swift.stride(from: 3, through: base, by: 2) where self % int == 0 {
return false
}
return true
}
#endif
/// SwifterSwift: Roman numeral string from integer (if applicable).
///
///10.romanNumeral() -> "X"
///
/// - Returns: The roman numeral string.
func romanNumeral() -> String? {
// https://gist.github.com/kumo/a8e1cb1f4b7cff1548c7
guard self > 0 else { // there is no roman numeral for 0 or negative numbers
return nil
}
let romanValues = ["M", "CM", "D", "CD", "C", "XC", "L", "XL", "X", "IX", "V", "IV", "I"]
let arabicValues = [1000, 900, 500, 400, 100, 90, 50, 40, 10, 9, 5, 4, 1]
var romanValue = ""
var startingValue = self
for (index, romanChar) in romanValues.enumerated() {
let arabicValue = arabicValues[index]
let div = startingValue / arabicValue
if div > 0 {
for _ in 0..<div {
romanValue += romanChar
}
startingValue -= arabicValue * div
}
}
return romanValue
}
#if canImport(Foundation) && !os(Linux)
/// SwifterSwift: Rounds to the closest multiple of n
func roundToNearest(_ number: Int) -> Int {
return number == 0 ? self : Int(round(Double(self) / Double(number))) * number
}
#endif
}
// MARK: - Operators
#if canImport(Foundation) && !os(Linux)
precedencegroup PowerPrecedence { higherThan: MultiplicationPrecedence }
infix operator ** : PowerPrecedence
/// SwifterSwift: Value of exponentiation.
///
/// - Parameters:
/// - lhs: base integer.
/// - rhs: exponent integer.
/// - Returns: exponentiation result (example: 2 ** 3 = 8).
func ** (lhs: Int, rhs: Int) -> Double {
// http://nshipster.com/swift-operators/
return pow(Double(lhs), Double(rhs))
}
#endif
#if canImport(Foundation) && !os(Linux)
prefix operator √
/// SwifterSwift: Square root of integer.
///
/// - Parameter int: integer value to find square root for
/// - Returns: square root of given integer.
// swiftlint:disable:next identifier_name
public prefix func √ (int: Int) -> Double {
// http://nshipster.com/swift-operators/
return sqrt(Double(int))
}
#endif
infix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameters:
/// - lhs: integer number.
/// - rhs: integer number.
/// - Returns: tuple of plus-minus operation (example: 2 ± 3 -> (5, -1)).
// swiftlint:disable:next identifier_name
func ± (lhs: Int, rhs: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return (lhs + rhs, lhs - rhs)
}
prefix operator ±
/// SwifterSwift: Tuple of plus-minus operation.
///
/// - Parameter int: integer number
/// - Returns: tuple of plus-minus operation (example: ± 2 -> (2, -2)).
// swiftlint:disable:next identifier_name
public prefix func ± (int: Int) -> (Int, Int) {
// http://nshipster.com/swift-operators/
return 0 ± int
}
|
mit
|
9ec8f705b3cd507c4a5bd0065af7fe8c
| 26.832558 | 98 | 0.582219 | 3.942029 | false | false | false | false |
joshjeong/Flicks
|
Flicks/Movie.swift
|
1
|
3322
|
//
// Movie.swift
// Flicks
//
// Created by Josh Jeong on 3/29/17.
// Copyright © 2017 JoshJeong. All rights reserved.
//
import Foundation
class Movie {
var movies = [Movie]()
var adult: Bool?
var backdropPath: String?
var genreIds: [Int]?
var id: Int?
var originalLanguage: String?
var originalTitle: String?
var overview: String?
var popularity: Float?
var posterPath: String?
var releaseDate: String?
var title: String?
var video: Bool?
var voteAvg: Float?
var voteCount: Float?
init?(json: [String: Any]) {
guard let adult = json["adult"] as? Bool,
let backdropPath = json["backdrop_path"] as? String,
let genreIds = json["genre_ids"] as? [Int],
let id = json["id"] as? Int,
let originalLanguage = json["original_language"] as? String,
let originalTitle = json["original_title"] as? String,
let overview = json["overview"] as? String,
let popularity = json["popularity"] as? Float,
let posterPath = json["poster_path"] as? String,
let releaseDate = json["release_date"] as? String,
let title = json["title"] as? String,
let video = json["video"] as? Bool,
let voteAvg = json["vote_average"] as? Float,
let voteCount = json["vote_count"] as? Float
else {
print("Incorrect JSON")
return nil
}
self.backdropPath = backdropPath
self.genreIds = genreIds
self.id = id
self.originalLanguage = originalLanguage
self.originalTitle = originalTitle
self.overview = overview
self.popularity = popularity
self.posterPath = posterPath
self.releaseDate = releaseDate
self.title = title
self.video = video
self.voteAvg = voteAvg
self.voteCount = voteCount
}
}
extension Movie {
static func fetchNowPlayingMovies(endpoint: String, successCallBack: @escaping ([Movie]) -> (), errorCallBack: ((Error?) -> ())?) {
let apiKey = "47809af88c3a5d4813ca5f235604fea6"
let url = URL(string: "https://api.themoviedb.org/3/movie/\(endpoint)?api_key=\(apiKey)")!
let request = URLRequest(url: url, cachePolicy: .reloadIgnoringLocalCacheData, timeoutInterval: 10)
let session = URLSession(configuration: .default, delegate: nil, delegateQueue: OperationQueue.main)
let task: URLSessionDataTask = session.dataTask(with: request) { (data: Data?, response: URLResponse?, error: Error?) in
var movies: [Movie] = []
if let error = error {
errorCallBack?(error)
} else if let data = data,
let json = try? JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
if let results = json?["results"] as? [[String: AnyObject]] {
for result in results {
if let movie = Movie(json: result) {
movies.append(movie)
}
}
}
successCallBack(movies)
}
}
task.resume()
}
}
|
mit
|
7a35686f08253abcda35d3baff8b2947
| 32.887755 | 135 | 0.559169 | 4.493911 | false | false | false | false |
kickstarter/ios-oss
|
KsApi/models/templates/LocationTemplates.swift
|
1
|
1558
|
extension Location {
internal static let template = Location(
country: "US",
displayableName: "Brooklyn, NY",
id: 42,
localizedName: "Brooklyn, NY",
name: "Brooklyn"
)
internal static let brooklyn = Location(
country: "US",
displayableName: "Brooklyn, NY",
id: 1,
localizedName: "Brooklyn, NY",
name: "Brooklyn"
)
internal static let losAngeles = Location(
country: "US",
displayableName: "Los Angeles, CA",
id: 2,
localizedName: "Los Angeles, CA",
name: "Los Angeles"
)
internal static let portland = Location(
country: "US",
displayableName: "Portland, OR",
id: 3,
localizedName: "Portland, OR",
name: "Portland"
)
internal static let london = Location(
country: "GB",
displayableName: "London, GB",
id: 4,
localizedName: "London, GB",
name: "London"
)
internal static let usa = Location(
country: "US",
displayableName: "United States",
id: 5,
localizedName: "United States",
name: "United States"
)
internal static let canada = Location(
country: "CA",
displayableName: "Canada",
id: 6,
localizedName: "Canada",
name: "Canada"
)
internal static let greatBritain = Location(
country: "GB",
displayableName: "Great Britain",
id: 7,
localizedName: "Great Britain",
name: "Great Britain"
)
internal static let australia = Location(
country: "AU",
displayableName: "Australia",
id: 8,
localizedName: "Australia",
name: "Australia"
)
}
|
apache-2.0
|
f4568b3728b10a1b981d64438bcd1e10
| 20.342466 | 46 | 0.620026 | 3.581609 | false | false | false | false |
lucasmpaim/GuizionCardView
|
Example/MyPlayground.playground/Contents.swift
|
1
|
531
|
//: Playground - noun: a place where people can play
import UIKit
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
let view = UIImageView(frame: CGRect(x: 0, y: 0, width: 100, height: 100))
view.backgroundColor = UIColor.redColor()
let label = UILabel(frame: CGRect(x: 0,y: 0,width: 100,height: 100))
label.text = "huehuehue"
view.addSubview(label)
XCPlaygroundPage.currentPage.liveView = view
let cardNumber = "012345678"
cardNumber.substringToIndex(cardNumber.startIndex.advancedBy(4))
|
mit
|
909e458a1f4c27cc6e571cf696cb2d75
| 22.086957 | 74 | 0.768362 | 3.765957 | false | false | false | false |
kevin-zqw/play-swift
|
swift-lang/13. Inheritance.playground/section-1.swift
|
1
|
4548
|
// ------------------------------------------------------------------------------------------------
// Things to know:
//
// * There is no default base class for Swift objects. Any class that doesn't derive from
// another class is a base class.
// ------------------------------------------------------------------------------------------------
// Let's start with a simple base class:
class Vehicle
{
var numberOfWheels: Int
var maxPassengers: Int
func description() -> String
{
return "\(numberOfWheels) wheels; up to \(maxPassengers) passengers"
}
// Must initialize any properties that do not have a default value
init()
{
numberOfWheels = 0
maxPassengers = 1
}
}
// ------------------------------------------------------------------------------------------------
// Subclasses
//
// Now let's subclass the Vehicle to create a two-wheeled vehicle called a Bicycle
class Bicycle: Vehicle
{
// We'll make this a 2-wheeled vehicle
override init()
{
super.init()
numberOfWheels = 2
}
}
// We can call a member from the superclass
let bicycle = Bicycle()
bicycle.description()
// Subclasses can also be subclassed
class Tandem: Bicycle
{
// This bicycle has 2 passengers
override init()
{
super.init()
maxPassengers = 2
}
}
// init methods need override also
// Here, we'll create a car that includes a new description by overriding the superclass' instance
// method
class Car: Vehicle
{
// Adding a new property
var speed: Double = 0.0
// New initialization, starting with super.init()
override init()
{
super.init()
maxPassengers = 5
numberOfWheels = 4
}
// Using the override keyword to specify that we're overriding a function up the inheritance
// chain. It is a compilation error to leave out 'override' if a method exists up the chain.
override func description() -> String
{
// We start with the default implementation of description then tack our stuff onto it
return super.description() + "; " + "traveling at \(speed) mph"
}
}
// Here, we'll check our description to see that it does indeed give us something different from
// the superclass' default description:
let car = Car()
car.speed = 55
car.description()
// ------------------------------------------------------------------------------------------------
// Overriding Properties
//
// We can override property getters and setters. This applies to any property, including stored and
// computed properties
//
// When we do this, our overridden property must include the name of the property as well as the
// property's type.
class SpeedLimitedCar: Car
{
// Make sure to specify the name and type
override var speed: Double
{
get
{
return super.speed
}
// We need a setter since the super's property is read/write
//
// However, if the super was read-only, we wouldn't need this setter unless we wanted to
// add write capability.
set
{
super.speed = min(newValue, 40.0)
}
}
}
// We can see our override in action
var speedLimitedCar = SpeedLimitedCar()
speedLimitedCar.speed = 60
speedLimitedCar.speed
// We can also override property observers
class AutomaticCar: Car
{
var gear = 1
override var speed: Double
{
// Set the gear based on changes to speed
didSet { gear = Int(speed / 10.0) + 1 }
// Since we're overriding the property observer, we're not allowed to override the
// getter/setter.
//
// The following lines will not compile:
//
// get { return super.speed }
// set { super.speed = newValue }
}
}
// Here is our overridden observers in action
var automaticCar = AutomaticCar()
automaticCar.speed = 35.0
automaticCar.gear
// ------------------------------------------------------------------------------------------------
// Preenting Overrides
//
// We can prevent a subclass from overriding a particular method or property using the 'final'
// keyword.
//
// final can be applied to: class, var, func, class methods and subscripts
//
// Here, we'll prevent an entire class from being subclassed by applying the . Because of this,
// the finals inside the class are not needed, but are present for descriptive purposes. These
// additional finals may not compile in the future, but they do today:
final class AnotherAutomaticCar: Car
{
// This variable cannot be overridden
final var gear = 1
// We can even prevent overridden functions from being further refined
final override var speed: Double
{
didSet { gear = Int(speed / 10.0) + 1 }
}
}
// Use final to prevent a method, property, or subscript from being overridden.
|
apache-2.0
|
323033b6818aced1a084156d7714c36a
| 25.911243 | 99 | 0.636763 | 4.127042 | false | false | false | false |
openaphid/PureLayout
|
PureLayout/Example-iOS/Demos/iOSDemo4ViewController.swift
|
5
|
4134
|
//
// iOSDemo4ViewController.swift
// PureLayout Example-iOS
//
// Copyright (c) 2015 Tyler Fox
// https://github.com/smileyborg/PureLayout
//
import UIKit
import PureLayout
@objc(iOSDemo4ViewController)
class iOSDemo4ViewController: UIViewController {
let blueLabel: UILabel = {
let label = UILabel.newAutoLayoutView()
label.backgroundColor = .blueColor()
label.numberOfLines = 1
label.lineBreakMode = .ByClipping
label.textColor = .whiteColor()
label.text = NSLocalizedString("Lorem ipsum", comment: "")
return label
}()
let redLabel: UILabel = {
let label = UILabel.newAutoLayoutView()
label.backgroundColor = .redColor()
label.numberOfLines = 0
label.textColor = .whiteColor()
label.text = NSLocalizedString("Lorem ipsum", comment: "")
return label
}()
let greenView: UIView = {
let view = UIView.newAutoLayoutView()
view.backgroundColor = .greenColor()
return view
}()
var didSetupConstraints = false
override func loadView() {
view = UIView()
view.backgroundColor = UIColor(white: 0.1, alpha: 1.0)
view.addSubview(blueLabel)
view.addSubview(redLabel)
view.addSubview(greenView)
view.setNeedsUpdateConstraints() // bootstrap Auto Layout
}
override func updateViewConstraints() {
/**
NOTE: To observe the effect of leading & trailing attributes, you need to change the OS language setting from a left-to-right language,
such as English, to a right-to-left language, such as Arabic.
This demo project includes localized strings for Arabic, so you will see the Lorem Ipsum text in Arabic if the system is set to that language.
See this method of easily forcing the simulator's language from Xcode: http://stackoverflow.com/questions/8596168/xcode-run-project-with-specified-localization
*/
let smallPadding: CGFloat = 20.0
let largePadding: CGFloat = 50.0
if (!didSetupConstraints) {
// Prevent the blueLabel from compressing smaller than required to fit its single line of text
blueLabel.setContentCompressionResistancePriority(UILayoutPriorityRequired, forAxis: .Vertical)
// Position the single-line blueLabel at the top of the screen spanning the width, with some small insets
blueLabel.autoPinToTopLayoutGuideOfViewController(self, withInset: smallPadding)
blueLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: smallPadding)
blueLabel.autoPinEdgeToSuperviewEdge(.Trailing, withInset: smallPadding)
// Make the redLabel 60% of the width of the blueLabel
redLabel.autoMatchDimension(.Width, toDimension: .Width, ofView: blueLabel, withMultiplier: 0.6)
// The redLabel is positioned below the blueLabel, with its leading edge to its superview, and trailing edge to the greenView
redLabel.autoPinEdge(.Top, toEdge: .Bottom, ofView: blueLabel, withOffset: smallPadding)
redLabel.autoPinEdgeToSuperviewEdge(.Leading, withInset: smallPadding)
redLabel.autoPinEdgeToSuperviewEdge(.Bottom, withInset: largePadding)
// The greenView is positioned below the blueLabel, with its leading edge to the redLabel, and trailing edge to its superview
greenView.autoPinEdge(.Leading, toEdge: .Trailing, ofView: redLabel, withOffset: largePadding)
greenView.autoPinEdge(.Top, toEdge: .Bottom, ofView: blueLabel, withOffset: smallPadding)
greenView.autoPinEdgeToSuperviewEdge(.Trailing, withInset: smallPadding)
// Match the greenView's height to its width (keeping a consistent aspect ratio)
greenView.autoMatchDimension(.Width, toDimension: .Height, ofView: greenView)
didSetupConstraints = true
}
super.updateViewConstraints()
}
}
|
mit
|
50db88e1062c629a77f4db58b649acbd
| 42.978723 | 167 | 0.662554 | 5.49734 | false | false | false | false |
hpsoar/Today
|
Today/ItemDetailViewController.swift
|
1
|
15000
|
//
// ItemDetailViewController.swift
// Today
//
// Created by Aldrich Huang on 8/3/14.
// Copyright (c) 2014 beacon. All rights reserved.
//
import UIKit
import QuartzCore
class Line: UIView {
init(length: CGFloat, width: CGFloat, color: UIColor) {
super.init(frame: CGRectMake(0, 0, length, width))
self.backgroundColor = color
}
}
extension UIView {
var width: CGFloat {
get {
return self.frame.size.width
}
set {
var frame = self.frame
frame.size.width = newValue
self.frame = frame
}
}
var height: CGFloat {
get {
return self.frame.size.height
}
set {
var frame = self.frame
frame.size.height = newValue
self.frame = frame
}
}
var top: CGFloat {
get {
return self.frame.origin.y
}
set {
var frame = self.frame
frame.origin.y = newValue
self.frame = frame
}
}
var left: CGFloat {
get {
return self.frame.origin.x
}
set {
var frame = self.frame
frame.origin.x = newValue
self.frame = frame
}
}
var bottom: CGFloat {
get {
return self.frame.origin.y + self.frame.size.height
}
set {
var frame = self.frame
frame.origin.y = newValue - frame.size.height
self.frame = frame
}
}
var right: CGFloat {
get {
return self.frame.origin.x + self.frame.size.width
}
set {
var frame = self.frame
frame.origin.x = newValue - frame.size.width
self.frame = frame
}
}
}
class BorderedView: UIView {
var leftBorder: UIView?
var rightBorder: UIView?
var topBorder: UIView?
var bottomBorder: UIView?
func border(direction: NSInteger) -> UIView! {
switch direction {
case 1:
return self.createBorder(&self.leftBorder, x: 0, y: 0, width: 1, height: self.height, direction: direction)
case 2:
return self.createBorder(&self.topBorder, x: 0, y: 0, width: self.width, height: 1, direction: direction)
case 3:
return self.createBorder(&self.rightBorder, x: self.width - 1, y: 0, width: 1, height: self.height, direction: direction)
default:
return self.createBorder(&self.bottomBorder, x: 0, y: self.height - 1, width: self.width, height: 1, direction: direction)
}
}
func createBorder(border: UIViewPointer, x: CGFloat, y: CGFloat, width: CGFloat, height: CGFloat, direction: NSInteger) -> UIView! {
if !border.memory {
var view = UIView(x: x, y: y, width: width, height: height)
switch direction {
case 1:
view.autoresizingMask = UIViewAutoresizing.FlexibleHeight
case 2:
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth
case 3:
view.autoresizingMask = UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleLeftMargin
default:
view.autoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin
}
self.addSubview(view)
border.memory = view
}
return border.memory
}
}
class SwitchView: BorderedView {
var titleLabel: UILabel
var varSwitch: UISwitch
var on: Bool {
get {
return varSwitch.on
}
}
init(frame: CGRect, title: NSString, value: Bool) {
self.titleLabel = UILabel(frame: frame)
self.varSwitch = UISwitch(frame: frame)
self.titleLabel.text = title
self.varSwitch.on = value
super.init(frame: frame)
self.addSubview(self.titleLabel)
self.addSubview(self.varSwitch)
self.titleLabel.setTranslatesAutoresizingMaskIntoConstraints(false)
self.varSwitch.setTranslatesAutoresizingMaskIntoConstraints(false)
var views = [ "label": self.titleLabel, "switch": self.varSwitch]
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("V:|[label]|", options: nil, metrics: nil, views: views))
self.addConstraints(NSLayoutConstraint.constraintsWithVisualFormat("H:|-10-[label]-[switch]-10-|", options: NSLayoutFormatOptions.AlignAllCenterY, metrics: nil, views: views))
}
func setTextColor(color: UIColor) {
self.titleLabel.textColor = color
self.border(2).backgroundColor = UIColor.whiteColor()
}
}
protocol ItemDetailViewControllerDelegate {
func itemDetailViewControllerDismissed(controller: ItemDetailViewController)
func itemDetailViewController(controller: ItemDetailViewController, finishedEditingItem item: Item?, withNewItem newItem: Item) -> Bool
func itemDetailViewController(controller: ItemDetailViewController, willDeleteItem item: Item) -> Bool
}
class ItemDetailViewController: UIViewController, UITextFieldDelegate, UIAlertViewDelegate {
var item: Item?
var container: UIView!
var titleField: UITextField!
var allowShareSwitch: SwitchView!
var checkedSwitch: SwitchView!
var saveBtn: UIButton!
var closeBtn: UIButton!
var deleteBtn: UIButton!
var buttonContainer: BorderedView!
var delegate: ItemDetailViewControllerDelegate?
var topBar: UIView!
init(item: Item?) {
self.item = item
super.init(nibName: nil, bundle: nil)
}
override func viewDidLoad() {
super.viewDidLoad()
self.view.backgroundColor = UIColor.color(0x5ac8fa)
self.view.clipsToBounds = true
self.topBar = UIView(x: 0, y: 20, width: self.view.width, height: 44)
self.view.addSubview(self.topBar)
var closeIcon = CloseIcon(frame: CGRectMake(13, 26, 32, 32), color: UIColor.whiteColor())
var closeBtn = UIButton(frame: CGRectMake(7, 0, 44, 44))
closeBtn.setImage(closeIcon.snapshot(), forState: UIControlState.Normal)
closeBtn.addTarget(self, action: "cancel", forControlEvents: UIControlEvents.TouchUpInside)
self.closeBtn = closeBtn
self.topBar.addSubview(closeBtn)
self.saveBtn = UIButton(frame: CGRectMake(0, 0, 44, 44))
self.saveBtn.right = self.view.width - 20
self.saveBtn.setTitle("Save", forState: UIControlState.Normal)
self.saveBtn.addTarget(self, action: "save", forControlEvents: UIControlEvents.TouchUpInside)
self.topBar.addSubview(self.saveBtn)
var width: CGFloat = 280
var xOffset: CGFloat = (320 - width) / 2
var height: CGFloat = 60
self.container = UIView(x: 0, y: 13, width: 320, height: height * 4)
self.view.addSubview(self.container)
self.titleField = UITextField(frame: CGRectMake(xOffset, 0, width, 40))
if self.item {
self.titleField.text = self.item!.title
}
else {
self.titleField.placeholder = "New Item"
}
self.titleField.clearButtonMode = UITextFieldViewMode.WhileEditing
self.titleField.textAlignment = NSTextAlignment.Center
self.titleField.returnKeyType = UIReturnKeyType.Done
self.titleField.delegate = self
self.titleField.textColor = UIColor.whiteColor()
self.container.addSubview(self.titleField)
var allowShare = false
var checked = false
if self.item {
allowShare = self.item!.allowShare
checked = self.item!.checked
}
self.allowShareSwitch = SwitchView(frame: CGRectMake(xOffset, self.titleField.bottom, width, height), title: "Allow Share", value: allowShare)
self.allowShareSwitch!.setTextColor(UIColor.whiteColor())
self.container.addSubview(self.allowShareSwitch)
// TODO: only show this for today's item
self.checkedSwitch = SwitchView(frame: CGRectMake(xOffset, self.allowShareSwitch.bottom, width, height), title: "Checked", value: checked)
self.checkedSwitch!.setTextColor(UIColor.whiteColor())
self.container.addSubview(self.checkedSwitch)
self.buttonContainer = BorderedView(frame: CGRectMake(xOffset, self.checkedSwitch.bottom, width, height))
self.buttonContainer.border(2).backgroundColor = UIColor.whiteColor()
self.container.addSubview(self.buttonContainer)
if self.item {
self.deleteBtn = UIButton(frame: CGRectMake(0, 0, 80, 36))
self.deleteBtn.setTitle("Delete", forState: UIControlState.Normal)
self.deleteBtn.layer.cornerRadius = 5
self.deleteBtn.layer.borderColor = UIColor.whiteColor().CGColor
self.deleteBtn.layer.borderWidth = 1
self.deleteBtn.center = CGPointMake(self.buttonContainer.width / 2, self.buttonContainer.height / 2)
self.deleteBtn.addTarget(self, action: "delete", forControlEvents: UIControlEvents.TouchUpInside)
self.buttonContainer.addSubview(self.deleteBtn)
}
}
var window: UIWindow?
var anchorView: UIView?
func showFromView(view: UIView) {
if !window {
window = UIWindow(frame: UIScreen.mainScreen().bounds)
}
if window {
self.anchorView = view
self.window!.addSubview(self.view)
self.show(true, fromView: view)
}
}
var showed = false
func show(show: Bool, fromView view: UIView) {
if window {
window!.hidden = false
self.titleField.resignFirstResponder()
var duration = 0.3
var pAni = CAKeyframeAnimation(keyPath: "position")
pAni.duration = duration
var hAni = CAKeyframeAnimation(keyPath: "bounds.size")
hAni.duration = duration
var ani2 = CAKeyframeAnimation(keyPath: "position.y")
ani2.duration = duration
var alpahAni = CAKeyframeAnimation(keyPath: "opacity")
alpahAni.duration = duration
var frame = window!.convertRect(view.frame, fromView: view.superview)
var size0 = frame.size
var position0 = CGPointMake(frame.origin.x + 0.5 * size0.width, frame.origin.y + 0.5 * size0.height)
var size2 = window!.bounds.size
var position2 = CGPointMake(0.5 * size2.width, 0.5 * size2.height)
var positionY2:CGFloat = 13.0 + 0.5 * self.container.height
var endY2:CGFloat = 64 + 0.5 * self.container.height
var middleY2:CGFloat = (positionY2 + endY2) * 0.5
if show {
var arr = [ position0, position2 ]
pAni.values = [ NSValue(CGPoint: position0), NSValue(CGPoint: position2) ]
hAni.values = [ NSValue(CGSize: size0), NSValue(CGSize: size2) ]
ani2.values = [positionY2, endY2]
alpahAni.values = [ 0, 1 ]
self.view.layer.position = position2
self.view.layer.bounds = window!.bounds
self.container.layer.position.y = endY2
self.container.layer.opacity = 1
self.topBar.layer.opacity = 1
}
else {
pAni.values = [ NSValue(CGPoint: position2), NSValue(CGPoint: position0) ]
hAni.values = [ NSValue(CGSize: size2), NSValue(CGSize: size0) ]
ani2.values = [endY2, positionY2]
alpahAni.values = [ 1, 0 ]
self.view.layer.position = position0
self.view.frame = frame
self.container.layer.position.y = positionY2
self.container.layer.opacity = 0
self.topBar.layer.opacity = 0
}
pAni.delegate = self
self.view.layer.addAnimation(pAni, forKey: nil)
self.view.layer.addAnimation(hAni, forKey: nil)
self.container.layer.addAnimation(ani2, forKey: nil)
self.container.layer.addAnimation(alpahAni, forKey: nil)
self.topBar.layer.addAnimation(alpahAni, forKey: nil)
}
}
func dismiss() {
if self.anchorView {
self.show(false, fromView: self.anchorView!)
}
SVProgressHUD.dismiss()
}
override func animationDidStop(anim: CAAnimation!, finished flag: Bool) {
if showed {
for v : AnyObject in self.window!.subviews {
v.removeFromSuperview()
}
self.anchorView = nil
self.window!.hidden = true
self.window = nil
if delegate {
delegate!.itemDetailViewControllerDismissed(self)
}
}
else {
showed = true
self.titleField.becomeFirstResponder()
}
}
func save() -> Bool {
if delegate {
if !titleField!.text.isEmpty {
var item2: Item!
if self.item {
item2 = Item(id:self.item!.id, title: titleField!.text, checked: checkedSwitch!.on, allowShare: allowShareSwitch!.on)
}
else {
item2 = Item(title: titleField!.text, checked: checkedSwitch!.on, allowShare: allowShareSwitch!.on)
}
if delegate!.itemDetailViewController(self, finishedEditingItem:self.item, withNewItem: item2) {
self.dismiss()
return true
}
else {
SVProgressHUD.showErrorWithStatus("item named \(item2.title) already exists!")
}
}
}
return false
}
func cancel() {
self.dismiss()
}
func delete() {
var alert = UIAlertView()
alert.title = "Warning"
alert.message = "Do you want to delete this item?"
alert.delegate = self
alert.addButtonWithTitle("No")
alert.addButtonWithTitle("Yes")
alert.show()
}
func alertView(alertView: UIAlertView!, clickedButtonAtIndex buttonIndex: Int) {
if buttonIndex == 1 {
if self.delegate {
if self.delegate!.itemDetailViewController(self, willDeleteItem: self.item!) {
self.dismiss()
}
}
}
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
return self.save()
}
func textField(textField: UITextField!, shouldChangeCharactersInRange range: NSRange, replacementString string: String!) -> Bool {
return true
}
}
|
gpl-2.0
|
373b6b59bbb04c02c4add57a5c7a39b5
| 33.883721 | 183 | 0.589667 | 4.677268 | false | false | false | false |
TonnyTao/HowSwift
|
how_to_update_view_in_mvvm.playground/Sources/RxSwift/RxSwift/Observables/First.swift
|
8
|
1288
|
//
// First.swift
// RxSwift
//
// Created by Krunoslav Zaher on 7/31/17.
// Copyright © 2017 Krunoslav Zaher. All rights reserved.
//
private final class FirstSink<Element, Observer: ObserverType> : Sink<Observer>, ObserverType where Observer.Element == Element? {
typealias Parent = First<Element>
func on(_ event: Event<Element>) {
switch event {
case .next(let value):
self.forwardOn(.next(value))
self.forwardOn(.completed)
self.dispose()
case .error(let error):
self.forwardOn(.error(error))
self.dispose()
case .completed:
self.forwardOn(.next(nil))
self.forwardOn(.completed)
self.dispose()
}
}
}
final class First<Element>: Producer<Element?> {
private let source: Observable<Element>
init(source: Observable<Element>) {
self.source = source
}
override func run<Observer: ObserverType>(_ observer: Observer, cancel: Cancelable) -> (sink: Disposable, subscription: Disposable) where Observer.Element == Element? {
let sink = FirstSink(observer: observer, cancel: cancel)
let subscription = self.source.subscribe(sink)
return (sink: sink, subscription: subscription)
}
}
|
mit
|
17ec68072f11dfc62010d1010c5fc180
| 30.390244 | 172 | 0.62704 | 4.377551 | false | false | false | false |
AboutObjectsTraining/swift-comp-reston-2017-02
|
examples/swift-tool/ArraysBridged.playground/Contents.swift
|
1
|
461
|
import Foundation
let names = NSArray(array: ["Jim", "Pat", "Jill"])
let s = names.componentsJoinedByString(", ")
print(s)
//class Dog: NSObject
//{
// var name: String
//
// init(name: String) {
// self.name = name
// }
//
// func bark() {
// println("Woof! Woof!")
// }
//}
//
//let dogs = [
// Dog(name: "Rover"),
// Dog(name: "Fido"),
// Dog(name: "Spot"),
//]
//
//let foo: NSArray = dogs
//
//print(foo)
|
mit
|
54c40a859cc03be5bae7f19fefbdd425
| 13.870968 | 50 | 0.496746 | 2.810976 | false | false | false | false |
rjalkuino/youtubeApiSample
|
YTSample/ViewController.swift
|
1
|
2740
|
//
// ViewController.swift
// YTSample
//
// Created by robert john alkuino on 12/28/16.
// Copyright © 2016 thousandminds. All rights reserved.
//
import UIKit
import youtube_ios_player_helper
class ViewController: UIViewController {
let playerView = YTPlayerView()
let baseURLString = "https://www.googleapis.com"
var ytDatas:[YoutubeApiMapper] = []
let tableviewVideoList = UITableView()
override func viewDidLoad() {
super.viewDidLoad()
let videoPlayerY = view.frame.height/3
playerView.frame = CGRect(x: 0,y: 0,width: view.frame.width,height: videoPlayerY)
view.backgroundColor = UIColor.blue
playerView.load(withVideoId: "gh6GT40zKCo")
view.addSubview(playerView)
tableviewVideoList.frame = CGRect(x:0,y:videoPlayerY,width:view.frame.width,height:view.frame.height - videoPlayerY)
view.addSubview(tableviewVideoList)
tableviewVideoList.delegate = self
tableviewVideoList.dataSource = self
tableviewVideoList.register(YoutubeTableViewCell.self, forCellReuseIdentifier: "Cell")
let params = ["part": "snippet","channelId":"UCE_M8A5yxnLfW0KghEeajjw","key":"AIzaSyASbUWRlzaWcFPna8M1PmgaLWNzk1Jf0ns"]
ApiService<YoutubeApiMapper>().request(keyPath:"items",urlEndpoint: "/youtube/v3/search", params: params, method: .get, completion: { json in
if let jsonData = json {
self.ytDatas = jsonData
print(jsonData)
self.tableviewVideoList.reloadData()
}
})
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
extension ViewController: UITableViewDelegate {
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! YoutubeTableViewCell
let infos = ytDatas[indexPath.row]
cell.bind(cellInfo: infos)
return cell
}
func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
return 100
}
}
extension ViewController : UITableViewDataSource {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return ytDatas.count
}
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let infos = ytDatas[indexPath.row]
playerView.load(withVideoId: infos.id!)
}
}
|
apache-2.0
|
88861a82a978ac0ef26eedc373e922e3
| 32.402439 | 149 | 0.665206 | 4.468189 | false | false | false | false |
kagemiku/ios-clean-architecture-sample
|
ios-clean-architecture-sample/AppDelegate.swift
|
1
|
1238
|
//
// AppDelegate.swift
// ios-clean-architecture-sample
//
// Created by KAGE on 1/4/17.
// Copyright © 2017 KAGE. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let rootVC = GitHubRepositoryTableViewControllerBuilder.build()
let navigationVC = UINavigationController(rootViewController: rootVC)
navigationVC.navigationBar.backgroundColor = UIColor(hex: 0xF6F6F6)
navigationVC.navigationBar.isTranslucent = false
self.window = UIWindow(frame: UIScreen.main.bounds)
self.window?.rootViewController = navigationVC
self.window?.makeKeyAndVisible()
return true
}
func applicationWillResignActive(_ application: UIApplication) { }
func applicationDidEnterBackground(_ application: UIApplication) { }
func applicationWillEnterForeground(_ application: UIApplication) { }
func applicationDidBecomeActive(_ application: UIApplication) { }
func applicationWillTerminate(_ application: UIApplication) { }
}
|
mit
|
eb7cc613c334118ba8324c2d2599f2a2
| 31.552632 | 144 | 0.74131 | 5.401747 | false | false | false | false |
VirgilSecurity/virgil-sdk-keys-ios
|
Source/BaseClient/Networking/NetworkRetryOperation.swift
|
1
|
8471
|
//
// Copyright (C) 2015-2020 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
/// NetworkRetryOperation errors
///
/// - timeout: timeout
/// - reachabilityError: SCNetworkReachability returned error
public enum NetworkRetryOperationError: LocalizedError {
case timeout
case reachabilityError
/// Human-readable localized description
public var errorDescription: String? {
switch self {
case .timeout:
return "Timeout has fired"
case .reachabilityError:
return "SCNetworkReachability returned error"
}
}
}
/// Class for network operation with retry
open class NetworkRetryOperation: GenericOperation<Response> {
/// Last network operations
public private(set) var lastNetworkOperation: GenericOperation<Response>?
/// Timeout for whole operation with retries
static let timeout: TimeInterval = 120
/// Request
public let request: ServiceRequest
/// Retry
public let retry: RetryProtocol
/// Token context
public let tokenContext: TokenContext
/// Access Token Provider
public let accessTokenProvider: AccessTokenProvider
/// Conntection
public let connection: HttpConnectionProtocol
/// Token
public private(set) var token: AccessToken? = nil
/// Reachability
public let reachability: ReachabilityProtocol
/// Initializer
///
/// - Parameters:
/// - request: request
/// - retry: retry
/// - tokenContext: token context
/// - accessTokenProvider: access token provider
/// - connection: connection
public init(request: ServiceRequest,
retry: RetryProtocol,
tokenContext: TokenContext,
accessTokenProvider: AccessTokenProvider,
connection: HttpConnectionProtocol,
reachability: ReachabilityProtocol? = nil) {
self.request = request
self.retry = retry
self.tokenContext = tokenContext
self.accessTokenProvider = accessTokenProvider
self.connection = connection
self.reachability = reachability ?? Reachability()
super.init()
}
/// Main
override open func main() {
guard !self.isCancelled else {
self.finish()
return
}
var now = Date()
let timeoutDate = now.addingTimeInterval(NetworkRetryOperation.timeout)
var forceRefreshToken = true
do {
let response = try { () -> Response? in
var tokenContext = self.tokenContext
while true {
guard !self.isCancelled else {
return nil
}
guard now < timeoutDate else {
Log.debug("Request to \(request.url.absoluteString) timeout")
throw NetworkRetryOperationError.timeout
}
let tokenExpired: Bool
if let oldToken = self.token, let jwt = oldToken as? Jwt {
tokenExpired = jwt.isExpired(date: now)
}
else {
tokenExpired = false
}
if forceRefreshToken || tokenExpired {
let token = try OperationUtils
.makeGetTokenOperation(tokenContext: tokenContext,
accessTokenProvider: self.accessTokenProvider)
.startSync()
.get()
guard !self.isCancelled else {
return nil
}
now = Date()
guard now < timeoutDate else {
Log.debug("Request to \(request.url.absoluteString) timeout")
throw NetworkRetryOperationError.timeout
}
self.request.setAccessToken(token.stringRepresentation())
self.token = token
}
let lastNetworkOperation = try self.connection.send(self.request)
self.lastNetworkOperation = lastNetworkOperation
let result = lastNetworkOperation.startSync()
let retryChoice: RetryChoice
switch result {
case .success(let response):
retryChoice = self.retry.retryChoice(for: self.request, with: response)
case .failure(let error):
retryChoice = self.retry.retryChoice(for: self.request, with: error)
}
switch retryChoice {
case .noRetry:
return try result.get()
case .retryService(let retryDelay):
Log.debug("Retrying request to \(request.url.absoluteString) in \(retryDelay) s")
guard now.addingTimeInterval(retryDelay) < timeoutDate else {
Log.debug("Request to \(request.url.absoluteString) timeout")
throw NetworkRetryOperationError.timeout
}
Thread.sleep(forTimeInterval: retryDelay)
Log.debug("Retrying request to \(request.url.absoluteString)")
forceRefreshToken = false
case .retryAuth:
Log.debug("Retrying request to \(request.url.absoluteString) with new auth")
tokenContext = TokenContext(identity: tokenContext.identity,
service: tokenContext.service,
operation: tokenContext.operation,
forceReload: true)
forceRefreshToken = true
case .retryConnection:
Log.debug("Retrying request to \(request.url.absoluteString) due to connection problems")
try self.reachability.waitTillReachable(timeoutDate: timeoutDate,
url: request.url.absoluteString)
forceRefreshToken = false
}
now = Date()
}
}()
if let response = response {
self.result = .success(response)
}
}
catch {
self.result = .failure(error)
}
self.finish()
}
/// Cancel
override open func cancel() {
self.lastNetworkOperation?.cancel()
super.cancel()
}
}
|
bsd-3-clause
|
a8108f5d1e0bec38e67356c26d0de80d
| 34.295833 | 113 | 0.562035 | 5.89492 | false | false | false | false |
apple/swift-driver
|
Sources/SwiftDriver/ToolingInterface/ToolingUtil.swift
|
1
|
4520
|
//===------- ToolingUtil.swift - Swift Driver Source Version--------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import class TSCBasic.DiagnosticsEngine
import struct TSCBasic.Diagnostic
import class TSCBasic.ProcessSet
import enum TSCBasic.ProcessEnv
import var TSCBasic.localFileSystem
import SwiftOptions
/// Generates the list of arguments that would be passed to the compiler
/// frontend from the given driver arguments.
///
/// \param ArgList The driver arguments (i.e. normal arguments for \c swiftc).
/// \param ForceNoOutputs If true, override the output mode to "-typecheck" and
/// produce no outputs. For example, this disables "-emit-module" and "-c" and
/// prevents the creation of temporary files.
/// \param outputFrontendArgs Contains the resulting frontend invocation command
/// \param emittedDiagnostics Contains the diagnostics emitted by the driver
///
/// \returns true on error
///
/// \note This function is not intended to create invocations which are
/// suitable for use in REPL or immediate modes.
public func getSingleFrontendInvocationFromDriverArguments(argList: [String],
outputFrontendArgs: inout [String],
emittedDiagnostics: inout [Diagnostic],
forceNoOutputs: Bool = false) -> Bool {
var args: [String] = []
args.append(contentsOf: argList)
// When creating a CompilerInvocation, ensure that the driver creates a single
// frontend command.
args.append("-whole-module-optimization")
// Explicitly disable batch mode to avoid a spurious warning when combining
// -enable-batch-mode with -whole-module-optimization. This is an
// implementation detail.
args.append("-disable-batch-mode");
// Prevent having a separate job for emit-module, we would like
// to just have one job
args.append("-no-emit-module-separately-wmo")
// Avoid using filelists
args.append("-driver-filelist-threshold");
args.append(String(Int.max));
let diagnosticsEngine = DiagnosticsEngine()
defer { emittedDiagnostics = diagnosticsEngine.diagnostics }
do {
args = try ["swiftc"] + Driver.expandResponseFiles(args,
fileSystem: localFileSystem,
diagnosticsEngine: diagnosticsEngine)
let optionTable = OptionTable()
var parsedOptions = try optionTable.parse(Array(args), for: .batch, delayThrows: true)
if forceNoOutputs {
// Clear existing output modes and supplementary outputs.
parsedOptions.eraseAllArguments(in: .modes)
parsedOptions.eraseSupplementaryOutputs()
parsedOptions.addOption(.typecheck, argument: .none)
}
// Instantiate the driver, setting up the toolchain in the process, etc.
let resolver = try ArgsResolver(fileSystem: localFileSystem)
let executor = SimpleExecutor(resolver: resolver,
fileSystem: localFileSystem,
env: ProcessEnv.vars)
var driver = try Driver(args: parsedOptions.commandLine,
diagnosticsEngine: diagnosticsEngine,
executor: executor)
if diagnosticsEngine.hasErrors {
return true
}
let buildPlan = try driver.planBuild()
if diagnosticsEngine.hasErrors {
return true
}
let compileJobs = buildPlan.filter({ $0.kind == .compile })
guard let compileJob = compileJobs.spm_only else {
diagnosticsEngine.emit(.error_expected_one_frontend_job())
return true
}
if !compileJob.commandLine.starts(with: [.flag("-frontend")]) {
diagnosticsEngine.emit(.error_expected_frontend_command())
return true
}
outputFrontendArgs = try executor.description(of: compileJob,
forceResponseFiles: false).components(separatedBy: " ")
} catch {
print("Unexpected error: \(error).")
return true
}
return false
}
|
apache-2.0
|
c8b96b44f8ac318295facfedca7b56b5
| 40.46789 | 105 | 0.643142 | 5.067265 | false | false | false | false |
Chen-Dixi/SwiftHashDict
|
sy4/sy4/ViewController.swift
|
1
|
7601
|
//
// ViewController.swift
// sy4
//
// Created by Dixi-Chen on 16/6/16.
// Copyright © 2016年 Dixi-Chen. All rights reserved.
//
import UIKit
class ViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate
{
//展示列表
var tableView: UITableView!
//搜索控制器
var countrySearchController: UISearchController!
var searchArray:[flight] = [flight]() {
didSet {self.tableView.reloadData()}
}
var hashtable = hashdict<Int,flight>(sz:14,k: -1)
var flightArray = [Constants.fl1,Constants.fl2,Constants.fl3,Constants.fl4,Constants.fl5,Constants.fl6,Constants.fl7,Constants.fl8,Constants.fl9,Constants.fl10,Constants.fl11]
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let searchButton = UIBarButtonItem(title: "hashSearch", style: .Plain, target: self, action: #selector(ViewController.madeHashSearch))
self.navigationItem.rightBarButtonItem = searchButton
for i in 0..<flightArray.count{
hashtable.insert(flightArray[i].getPrice(), e: flightArray[i]) //set price as key,flight as value
}
QuickSort(&flightArray, first: 0, last: flightArray.count-1)
self.view.backgroundColor = UIColor.cyanColor()
//创建表视图
tableView = UITableView(frame: self.view.bounds, style: .Plain)
tableView!.delegate = self
tableView!.dataSource = self
tableView.backgroundColor = UIColor.whiteColor()
// let cell: UINib = UINib(nibName: "Cell", bundle: NSBundle.mainBundle())
//
// tableView.registerNib(cell, forCellReuseIdentifier: "cell")
self.view.addSubview(tableView!)
//配置搜索框
//初始化
countrySearchController = UISearchController(searchResultsController: nil)
//设置代理---在UISearchBar文字改变时被通知到
countrySearchController.searchResultsUpdater = self
//点击searchBar跳转到另一个页面
countrySearchController.searchBar.delegate = self
//隐藏导航栏
countrySearchController.hidesNavigationBarDuringPresentation = true
//false不会暗化当前view,若使用另一个viewController来显示当前结果时可以用到
countrySearchController.dimsBackgroundDuringPresentation = false
//设置类型
countrySearchController.searchBar.searchBarStyle = .Minimal
//设置大小
countrySearchController.searchBar.sizeToFit()
//设置提示文字
countrySearchController.searchBar.placeholder = NSLocalizedString("请输入搜索内容", comment: "搜索条的占位符")
//设置为tableView的头视图
tableView.tableHeaderView = countrySearchController.searchBar
//设置为导航栏的标题view
// self.navigationItem.titleView = countrySearchController.searchBar
//保证UISearchController在激活状态下用户push到下一个viewController之后searchBar不会仍留在页面
definesPresentationContext = true
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
//判断searchBar的状态---active在点击searchBar时会自动变为true
return self.countrySearchController.active ? self.searchArray.count : self.flightArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
var cell: UITableViewCell? = tableView.dequeueReusableCellWithIdentifier("cell")
if cell == nil {
cell = UITableViewCell(style: .Subtitle, reuseIdentifier: "cell")
// cell = NSBundle.mainBundle().loadNibNamed("Cell", owner: nil, options: nil).first as? Cell
}
// cell?.la.text = "aaa"
cell?.backgroundColor = UIColor.clearColor()
if self.countrySearchController.active {
// print(self.searchArray.count)
cell!.textLabel?.text = self.searchArray[indexPath.row].getFlightId()
cell!.detailTextLabel?.text = self.searchArray[indexPath.row].getStartPlace() + " -> " + self.searchArray[indexPath.row].getEndPlace() + " \(self.searchArray[indexPath.row].getPrice())元"
return cell!
}else {
cell!.textLabel?.text = self.flightArray[indexPath.row].getFlightId()
cell!.detailTextLabel?.text = self.flightArray[indexPath.row].getStartPlace() + " -> " + self.flightArray[indexPath.row].getEndPlace() + " \(self.flightArray[indexPath.row].getPrice())元"
return cell!
}
}
func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
return !self.countrySearchController.active
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
if self.countrySearchController.active {
self.countrySearchController.searchBar.text = cell?.textLabel?.text
}
}
//更新搜索结果
func updateSearchResultsForSearchController(searchController: UISearchController) {
//修改cancel按钮
self.countrySearchController.searchBar.showsCancelButton = true
for sousuo in self.countrySearchController.searchBar.subviews {
for cancel in sousuo.subviews {
if cancel.isKindOfClass(UIButton) {
let btn = cancel as! UIButton
btn.setTitle("取消", forState: .Normal)
}
}
}
//使用谓词
// self.searchArray.removeAll(keepCapacity: false)
//
// let searchPredicate = NSPredicate(format: "SELF CONTAINS[c] %@", searchController.searchBar.text!)
// let array = (self.shoolArray as NSArray).filteredArrayUsingPredicate(searchPredicate)
// self.searchArray = array as! [String]
//判断字符是否包含某一字符
if var textToSearch = self.countrySearchController.searchBar.text {
self.searchArray = self.flightArray.filter({ (str) -> Bool in
//去除字符串中的字符,这里去除空格字符组
textToSearch = textToSearch.stringByTrimmingCharactersInSet(NSCharacterSet.whitespaceCharacterSet())
return str.getFlightId().containsString(textToSearch) || str.getStartPlace().containsString(textToSearch)
})
}
self.tableView.reloadData()
}
//Mark: - perform segue
func madeHashSearch()
{
self.performSegueWithIdentifier("hashSearch", sender: nil)
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
if let hsvc = segue.destinationViewController as? HashSearchViewController{
hsvc.hashtable = self.hashtable
}
}
}
|
mit
|
7d4ade1a7e5e2d7ad788a966889b5304
| 38.922222 | 198 | 0.642917 | 5.074859 | false | false | false | false |
jevy-wangfei/FeedMeIOS
|
HistoryOrdersTableViewController.swift
|
1
|
5427
|
//
// HistoryOrdersTableViewController.swift
// FeedMeIOS
//
// Created by Jun Chen on 3/04/2016.
// Copyright © 2016 FeedMe. All rights reserved.
//
import UIKit
class HistoryOrdersTableViewController: UITableViewController {
var historyOrders: HistoryOrders?
override func viewDidLoad() {
super.viewDidLoad()
self.setBackground(self)
self.setBar(self)
self.navigationItem.rightBarButtonItem = self.editButtonItem()
if Reachability.isConnectedToNetwork() {
self.loadData()
} else {
Reachability.alertNoInternetConnection(self)
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Load data source
// TODO: HTTP GET
func loadData() -> Bool {
var currentOrders:[Order]? = [Order]()
let curOrder1 = Order(userID: FeedMe.Variable.userID, restaurantID: 1)
curOrder1.totalPrice = 100
curOrder1.setTime()
currentOrders = currentOrders! + [curOrder1]
var pastOrders:[Order]? = [Order]()
let pastOrder1 = Order(userID: FeedMe.Variable.userID, restaurantID: 1)
pastOrder1.totalPrice = 200
pastOrder1.setTime()
pastOrders = pastOrders! + [pastOrder1]
historyOrders = HistoryOrders(currentOrders: currentOrders, pastOrders: pastOrders)
return true
}
// MARK: - Table view data source
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 2
}
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
switch section {
case 0:
return historyOrders!.getCurrentOrders()!.count
case 1:
return historyOrders!.getPastOrders()!.count
default:
return 0
}
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cellIdentifier = "HistoryOrdersTableViewCell"
let cell = tableView.dequeueReusableCellWithIdentifier(cellIdentifier, forIndexPath: indexPath) as! HistoryOrdersTableViewCell
// Configure the cell...
var order: Order?
switch indexPath.section {
case 0:
order = historyOrders!.getCurrentOrders()![indexPath.row]
cell.OrderStateLabel.text = "Being Cooked"
case 1:
order = historyOrders!.getPastOrders()![indexPath.row]
cell.OrderStateLabel.text = "Finished"
default:
break
}
if((indexPath.row)%2 == 0) {
cell.backgroundColor = FeedMe.transColor4
} else {
cell.backgroundColor = FeedMe.transColor7
}
cell.GrandTotalLabel.text = "$\(order!.totalPrice)"
cell.OrderDateLabel.text = order!.orderTime!
return cell
}
override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {
switch section {
case 0:
return "Current Orders (\(historyOrders!.getCurrentOrders()!.count))"
case 1:
return "History Orders (\(historyOrders!.getPastOrders()!.count))"
default:
return ""
}
}
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView, canEditRowAtIndexPath indexPath: NSIndexPath) -> Bool {
// Return false if you do not want the specified item to be editable.
switch indexPath.section {
case 0:
return false
case 1:
return true
default:
false
}
return false
}
// 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
historyOrders!.delete("HISTORY", index: indexPath.row)
tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
// Update header information of the history orders section
tableView.reloadSections(NSIndexSet(index: 1), withRowAnimation: UITableViewRowAnimation.None)
}
}
/*
// 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 false if you do not want the item to be re-orderable.
return true
}
*/
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
mit
|
db0b4af58a64f6675f990aa4bda7beca
| 31.106509 | 157 | 0.632694 | 5.324828 | false | false | false | false |
jad6/CV
|
Swift/Jad's CV/Other/Helpers/Contactor.swift
|
1
|
1666
|
//
// Contactor.swift
// Jad's CV
//
// Created by Jad Osseiran on 19/07/2014.
// Copyright (c) 2014 Jad. All rights reserved.
//
import UIKit
import MessageUI
class Contactor: NSObject, MFMailComposeViewControllerDelegate {
//MARK:- Properties
class var sharedContactor: Contactor {
struct Static {
static let instance = Contactor()
}
return Static.instance
}
var viewController: UIViewController?
//MARK:- Logic
class func call(#number: String) {
if UIDevice.canCall() {
let telPhone = "tel://" + number.stringByReplacingOccurrencesOfString(" ", withString: "")
let phoneURL = NSURL(string: telPhone)
let application = UIApplication.sharedApplication()
if application.canOpenURL(phoneURL) {
application.openURL(phoneURL)
}
}
}
func email(#reciepients: [String]?, fromController controller: UIViewController) {
if UIDevice.canEmail() {
let mailComposer = MFMailComposeViewController()
mailComposer.mailComposeDelegate = self
mailComposer.setToRecipients(reciepients)
controller.presentViewController(mailComposer, animated: true, completion: nil)
viewController = controller
}
}
func mailComposeController(controller: MFMailComposeViewController!, didFinishWithResult result: MFMailComposeResult, error: NSError!) {
error?.handle()
viewController!.dismissViewControllerAnimated(true) {
self.viewController = nil
}
}
}
|
bsd-3-clause
|
b2174ea3955096825f0ea7f0b729fcb9
| 28.245614 | 140 | 0.62425 | 5.49835 | false | false | false | false |
achimk/Cars
|
CarsApp/Features/Cars/List/CarsListPresentationItem.swift
|
1
|
957
|
//
// CarsListPresentationItem.swift
// CarsApp
//
// Created by Joachim Kret on 29/07/2017.
// Copyright © 2017 Joachim Kret. All rights reserved.
//
import Foundation
protocol CarsListItemPresentable: CarConvertible {
var title: String { get }
var subtitle: String { get }
}
struct CarsListPresentationItem: CarsListItemPresentable {
let car: CarType
var title: String {
return car.name ?? ""
}
var subtitle: String {
var items: Array<String> = []
if let brand = car.brand {
items.append(brand)
}
if let model = car.model {
items.append(model)
}
if let year = CarsModelEntityMapper.year(from: car.manufactureDate) {
items.append(String("(\(year))"))
}
return items.joined(separator: " ")
}
init(_ car: CarType) {
self.car = car
}
func asCar() -> CarType {
return car
}
}
|
mit
|
aa40ceffbc3f1f0f6c559b319d504acf
| 18.916667 | 77 | 0.579498 | 3.966805 | false | false | false | false |
laurentVeliscek/AudioKit
|
AudioKit/Common/Nodes/Effects/Filters/Tone Complement Filter/AKToneComplementFilter.swift
|
1
|
3875
|
//
// AKToneComplementFilter.swift
// AudioKit
//
// Created by Aurelius Prochazka, revision history on Github.
// Copyright (c) 2016 Aurelius Prochazka. All rights reserved.
//
import AVFoundation
/// A complement to the AKLowPassFilter.
///
/// - Parameters:
/// - input: Input node to process
/// - halfPowerPoint: Half-Power Point in Hertz. Half power is defined as peak power / square root of 2.
///
public class AKToneComplementFilter: AKNode, AKToggleable {
// MARK: - Properties
internal var internalAU: AKToneComplementFilterAudioUnit?
internal var token: AUParameterObserverToken?
private var halfPowerPointParameter: AUParameter?
/// Ramp Time represents the speed at which parameters are allowed to change
public var rampTime: Double = AKSettings.rampTime {
willSet {
if rampTime != newValue {
internalAU?.rampTime = newValue
internalAU?.setUpParameterRamp()
}
}
}
/// Half-Power Point in Hertz. Half power is defined as peak power / square root of 2.
public var halfPowerPoint: Double = 1000.0 {
willSet {
if halfPowerPoint != newValue {
if internalAU!.isSetUp() {
halfPowerPointParameter?.setValue(Float(newValue), originator: token!)
} else {
internalAU?.halfPowerPoint = Float(newValue)
}
}
}
}
/// Tells whether the node is processing (ie. started, playing, or active)
public var isStarted: Bool {
return internalAU!.isPlaying()
}
// MARK: - Initialization
/// Initialize this filter node
///
/// - Parameters:
/// - input: Input node to process
/// - halfPowerPoint: Half-Power Point in Hertz. Half power is defined as peak power / square root of 2.
///
public init(
_ input: AKNode,
halfPowerPoint: Double = 1000.0) {
self.halfPowerPoint = halfPowerPoint
var description = AudioComponentDescription()
description.componentType = kAudioUnitType_Effect
description.componentSubType = 0x61746f6e /*'aton'*/
description.componentManufacturer = 0x41754b74 /*'AuKt'*/
description.componentFlags = 0
description.componentFlagsMask = 0
AUAudioUnit.registerSubclass(
AKToneComplementFilterAudioUnit.self,
asComponentDescription: description,
name: "Local AKToneComplementFilter",
version: UInt32.max)
super.init()
AVAudioUnit.instantiateWithComponentDescription(description, options: []) {
avAudioUnit, error in
guard let avAudioUnitEffect = avAudioUnit else { return }
self.avAudioNode = avAudioUnitEffect
self.internalAU = avAudioUnitEffect.AUAudioUnit as? AKToneComplementFilterAudioUnit
AudioKit.engine.attachNode(self.avAudioNode)
input.addConnectionPoint(self)
}
guard let tree = internalAU?.parameterTree else { return }
halfPowerPointParameter = tree.valueForKey("halfPowerPoint") as? AUParameter
token = tree.tokenByAddingParameterObserver {
address, value in
dispatch_async(dispatch_get_main_queue()) {
if address == self.halfPowerPointParameter!.address {
self.halfPowerPoint = Double(value)
}
}
}
internalAU?.halfPowerPoint = Float(halfPowerPoint)
}
// MARK: - Control
/// Function to start, play, or activate the node, all do the same thing
public func start() {
self.internalAU!.start()
}
/// Function to stop or bypass the node, both are equivalent
public func stop() {
self.internalAU!.stop()
}
}
|
mit
|
1b3eac63cec0cc5601bf9199401e46c3
| 30.762295 | 110 | 0.623742 | 5.279292 | false | false | false | false |
IBM-MIL/IBM-Ready-App-for-Venue
|
iOS/Venue/Extensions/UIColorExtension.swift
|
1
|
1625
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
extension UIColor {
convenience init(hex: Int, alpha: CGFloat = 1.0) {
let red = CGFloat((hex & 0xFF0000) >> 16) / 255.0
let green = CGFloat((hex & 0xFF00) >> 8) / 255.0
let blue = CGFloat((hex & 0xFF)) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
class func venueRed(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 255.0/255.0, green: 23.0/255.0, blue: 68.0/255.0, alpha: alpha)}
class func venueBabyBlue(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 231.0/255.0, green: 245.0/255.0, blue: 255.0/255.0, alpha: alpha)}
class func venueLightBlue(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 124.0/255.0, green: 199.0/255.0, blue: 255.0/255.0, alpha: alpha)}
class func venueNavyBlue(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 38.0/255.0, green: 74.0/255.0, blue: 96.0/255.0, alpha: alpha)}
class func venueDarkGray(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 153.0/255.0, green: 153.0/255.0, blue: 153.0/255.0, alpha: alpha)}
class func venueLightGreen(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 0.0/255.0, green: 200.0/255.0, blue: 83.0/255.0, alpha: alpha)}
class func venueLightOrange(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 255.0/255.0, green: 171.0/255.0, blue: 0.0/255.0, alpha: alpha)}
class func venueSelectionBlue(alpha: CGFloat = 1.0) -> UIColor{return UIColor(red: 51.0/255.0, green: 153.0/255.0, blue: 255.0/255.0, alpha: alpha)}
}
|
epl-1.0
|
5d1b2f47909520badeb1edc9744ecfc8
| 64 | 152 | 0.660714 | 2.894831 | false | false | false | false |
li-xinyang/OSND_P2_1_MemeMe
|
App_00_ClickCounter/ClickerCounter/ClickerCounter/ViewController.swift
|
1
|
1319
|
//
// ViewController.swift
// ClickerCounter
//
// Created by Xinyang Li on 12/3/15.
// Copyright © 2015 Xinyang Li. All rights reserved.
//
import UIKit
class ViewController: UIViewController {
// Declare the count and label properties
var count = 0
@IBOutlet weak var label: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
@IBAction func btn_inc(sender: UIButton) {
incrementCount()
}
@IBAction func btn_dec(sender: UIButton) {
decrementCount()
}
@IBAction func btn_toggleBackground(sender: UIButton) {
toggleBackgroundColor()
}
// Increase counter and set label text based on the count
func incrementCount() {
self.count++
self.label.text = "\(self.count)"
}
// Decrease counter and set label text based on the count
func decrementCount() {
self.count--
self.label.text = "\(self.count)"
}
// Toggle root view background color
func toggleBackgroundColor() {
let activeColor = UIColor(red:0.99, green:0.96, blue:0.89, alpha:1)
if (self.view.backgroundColor == activeColor) {
self.view.backgroundColor = UIColor.whiteColor()
} else {
self.view.backgroundColor = activeColor
}
}
}
|
mit
|
169e68a909380719d506abb6affed6a2
| 22.963636 | 75 | 0.616844 | 4.210863 | false | false | false | false |
hovansuit/FoodAndFitness
|
FoodAndFitness/Controllers/History/CalendarController/CalendarController.swift
|
1
|
2465
|
//
// CalendarController.swift
// FoodAndFitness
//
// Created by Mylo Ho on 3/30/17.
// Copyright © 2017 SuHoVan. All rights reserved.
//
import UIKit
import FSCalendar
import SwiftDate
final class CalendarController: RootSideMenuViewController {
@IBOutlet fileprivate(set) weak var calendar: FSCalendar!
lazy var viewModel: CalendarViewModel = CalendarViewModel()
override func setupUI() {
super.setupUI()
title = Strings.history
navigationBar()
configureCalendar()
}
private func navigationBar() {
navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Next", style: .plain, target: self, action: #selector(gotoHistory))
rightButtonEnabled()
}
private func configureCalendar() {
calendar.delegate = self
calendar.dataSource = self
}
fileprivate func rightButtonEnabled() {
guard let selectedCell = viewModel.selectedCell else {
navigationItem.rightBarButtonItem?.isEnabled = false
return
}
navigationItem.rightBarButtonItem?.isEnabled = selectedCell.numberOfEvents > 0
}
@objc private func gotoHistory() {
guard let selectedCell = viewModel.selectedCell, let selectedDate = viewModel.selectedDate else {
let error = NSError(message: Strings.Errors.noHistory)
error.show()
return
}
let numberOfEvents = selectedCell.numberOfEvents
if numberOfEvents > 0 {
let historyViewController = HistoryViewController()
historyViewController.viewModel = HistoryViewModel(date: selectedDate)
navigationController?.pushViewController(historyViewController, animated: true)
}
}
}
// MARK: - FSCalendarDataSource
extension CalendarController: FSCalendarDataSource {
func calendar(_ calendar: FSCalendar, numberOfEventsFor date: Date) -> Int {
// if !date.isToday && viewModel.didHaveEvents(forDate: date) {
if viewModel.didHaveEvents(forDate: date) {
return 1
} else {
return 0
}
}
}
// MARK: - FSCalendarDelegate
extension CalendarController: FSCalendarDelegate {
func calendar(_ calendar: FSCalendar, didSelect date: Date, at monthPosition: FSCalendarMonthPosition) {
viewModel.selectedCell = calendar.cell(for: date, at: monthPosition)
viewModel.selectedDate = date
rightButtonEnabled()
}
}
|
mit
|
2fea4d14663e1b79535fd01b95b4f9ee
| 31.421053 | 135 | 0.674513 | 5.101449 | false | false | false | false |
bitboylabs/selluv-ios
|
selluv-ios/selluv-ios/Classes/Controller/UI/Tabs/Tab3Sell/views/SLV350SellerBankCell.swift
|
1
|
1289
|
//
// SLV350SellerBankCell.swift
// selluv-ios
//
// Created by 조백근 on 2017. 1. 12..
// Copyright © 2017년 BitBoy Labs. All rights reserved.
//
import UIKit
class SLV350SellerBankCell: UICollectionViewCell {
@IBOutlet weak var bankNameLabel: UILabel!
@IBOutlet weak var bankSelectButton: CaretDn180dWheelButton!
var btnBlock: TouchBlock?
override init(frame: CGRect) {
super.init(frame: frame)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
override open func awakeFromNib() {
super.awakeFromNib()
}
override func layoutSubviews() {
super.layoutSubviews()
}
//MARK: Setup
func setupButton(block: @escaping TouchBlock) {
self.btnBlock = block
}
@IBAction func touchBank2(_ sender: Any) {
let button = sender as! UIButton
DispatchQueue.main.async {
self.bankSelectButton.isHighlighted = button.isHighlighted
}
self.bankSelectButton.sendActions(for: .touchUpInside)
}
@IBAction func touchBankSelectButton(_ sender: Any) {
if self.btnBlock != nil {
let button = sender as! UIButton
self.btnBlock!(button)
}
}
}
|
mit
|
465e90c44f6978255a4e298c74661fcd
| 23.150943 | 70 | 0.617188 | 4.398625 | false | false | false | false |
uias/Tabman
|
Sources/Tabman/Bar/BarIndicator/TMBarIndicatorContainer.swift
|
1
|
1614
|
//
// TMBarIndicatorContainer.swift
// Tabman
//
// Created by Merrick Sapsford on 02/09/2018.
// Copyright © 2022 UI At Six. All rights reserved.
//
import UIKit
/// Container view that embeds a `TMBarIndicator`.
///
/// Used for providing AutoLayout properties to `TMBarIndicatorLayoutHandler`.
internal final class TMBarIndicatorContainer<Indicator: TMBarIndicator>: UIView {
// MARK: Properties
private(set) var layoutHandler: TMBarIndicatorLayoutHandler!
// MARK: Init
init(for indicator: Indicator) {
super.init(frame: .zero)
isUserInteractionEnabled = false
layout(indicator: indicator)
}
@available(*, unavailable)
required init?(coder aDecoder: NSCoder) {
fatalError()
}
// MARK: Layout
private func layout(indicator: Indicator) {
guard indicator.superview == nil else {
fatalError("Indicator already has a superview.")
}
addSubview(indicator)
indicator.translatesAutoresizingMaskIntoConstraints = false
let leading = indicator.leftAnchor.constraint(equalTo: leftAnchor)
let top = indicator.topAnchor.constraint(equalTo: topAnchor)
let bottom = indicator.bottomAnchor.constraint(equalTo: bottomAnchor)
let width = indicator.widthAnchor.constraint(equalToConstant: 0.0)
NSLayoutConstraint.activate([leading, top, bottom, width])
self.layoutHandler = TMBarIndicatorLayoutHandler(leading: leading,
width: width)
}
}
|
mit
|
f0106c5fbf782f020e5dd37d65ceb388
| 30.019231 | 81 | 0.647861 | 5.136943 | false | false | false | false |
raulriera/HuntingKit
|
HuntingKit/Vote.swift
|
1
|
583
|
//
// Vote.swift
// HuntingKit
//
// Created by Raúl Riera on 14/05/2015.
// Copyright (c) 2015 Raul Riera. All rights reserved.
//
import Foundation
public struct Vote: Model {
public let id: Int
public let user: User
public init?(dictionary: NSDictionary) {
if let id = dictionary["id"] as? Int,
let userDictionary = dictionary["user"] as? NSDictionary,
let user = User(dictionary: userDictionary) {
self.id = id
self.user = user
} else {
return nil
}
}
}
|
mit
|
dfa4a9c30fa65a3eca3ed76614a8ba5f
| 20.592593 | 69 | 0.556701 | 4.12766 | false | false | false | false |
hanhailong/practice-swift
|
ResearchKit/ResearchKitDemo/ResearchKitDemo/SurveyTask.swift
|
3
|
1855
|
//
// SurveyTask.swift
// ResearchKitDemo
//
// Created by Domenico on 19/06/15.
// Copyright (c) 2015 Domenico. All rights reserved.
//
import ResearchKit
public var SurveyTask: ORKOrderedTask{
var steps = [ORKStep]()
// Instruction step
var instructionStep = ORKInstructionStep(identifier: "InstructionStep")
instructionStep.title = "The Three Questions"
instructionStep.text = "Who would cross the Bridge of Death must answer me these questions three, ere the other side they see."
//instructionStep.image = UIImage(named: "Image")
steps += [instructionStep]
// Name question
let nameAnswerFormat = ORKTextAnswerFormat(maximumLength: 20)
nameAnswerFormat.multipleLines = false
let nameQuestionStepTitle = "What is your name?"
let nameQuestionStep = ORKQuestionStep(identifier: "NameQuestion", title: nameQuestionStepTitle, answer: nameAnswerFormat)
steps += [nameQuestionStep]
// What is your quest question
let questQuestionStepTitle = "What is your quest?"
let textChoices = [
ORKTextChoice(text: "Create a ResearchKit App", value: 0),
ORKTextChoice(text: "Seek the Holy Grail", value: 1),
ORKTextChoice(text: "Find a shrubbery", value: 2)
]
let questAnswerFormat: ORKTextChoiceAnswerFormat = ORKAnswerFormat.choiceAnswerFormatWithStyle(.SingleChoice, textChoices: textChoices)
let questQuestionStep = ORKQuestionStep(identifier: "TextChoiceQuestionStep", title: questQuestionStepTitle, answer: questAnswerFormat)
steps += [questQuestionStep]
// Summary
let summaryStep = ORKCompletionStep(identifier: "SummaryStep")
summaryStep.title = "Right. Off you go!"
summaryStep.text = "That was easy!"
steps += [summaryStep]
return ORKOrderedTask(identifier: "SurveyTask", steps: steps)
}
|
mit
|
7c2c68aedef0533f6f6f1553d7252480
| 37.645833 | 139 | 0.716442 | 4.480676 | false | false | false | false |
tardieu/swift
|
test/IDE/complete_func_body_typechecking.swift
|
31
|
7213
|
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_1 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_2 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_3 | %FileCheck %s -check-prefix=ERROR_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_4 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_5 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_6 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_7 | %FileCheck %s -check-prefix=ERROR_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IN_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IN_CONSTRUCTOR_2 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IN_DESTRUCTOR_1 | %FileCheck %s -check-prefix=FOO_STRUCT_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_2 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_3 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_4 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_IN_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=TC_VAR_IF_IN_DESTRUCTOR_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_2 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IN_CONSTRUCTOR_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
// RUN: %target-swift-ide-test -code-completion -source-filename %s -code-completion-token=EXPR_POSTFIX_BEGIN_IN_DESTRUCTOR_1 | %FileCheck %s -check-prefix=LOCALS_COMMON
struct FooStruct {
var instanceVar = 0
init(_ instanceVar: Int = 0) { }
func instanceFunc0() {}
func builderFunc1() -> FooStruct {
return self
}
func builderFunc2(_ a: Int) -> FooStruct {
return self
}
}
// FOO_STRUCT_COMMON: Begin completions
// FOO_STRUCT_COMMON-NEXT: Decl[InstanceVar]/CurrNominal: instanceVar[#Int#]{{; name=.+$}}
// FOO_STRUCT_COMMON-NEXT: Decl[InstanceMethod]/CurrNominal: instanceFunc0()[#Void#]{{; name=.+$}}
// FOO_STRUCT_COMMON-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc1()[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_COMMON-NEXT: Decl[InstanceMethod]/CurrNominal: builderFunc2({#(a): Int#})[#FooStruct#]{{; name=.+$}}
// FOO_STRUCT_COMMON-NEXT: End completions
// ERROR_COMMON: found code completion token
// ERROR_COMMON-NOT: Begin completions
// LOCALS_COMMON: Begin completions
// LOCALS_COMMON-DAG: Decl[LocalVar]/Local: localInt[#Int#]{{; name=.+$}}
// LOCALS_COMMON-DAG: Decl[LocalVar]/Local: localFooObject[#FooStruct#]{{; name=.+$}}
// LOCALS_COMMON: End completions
func testTypecheckVar1() {
var localFooObject = FooStruct()
localFooObject.#^TC_VAR_1^#
}
func testTypecheckVar2() {
var localFooObject = FooStruct(42)
localFooObject.#^TC_VAR_2^#
}
func testTypecheckVar3() {
// FIXME: We don't display any useful completions here, although we could --
// it is obvious that 'foo' could only have type 'FooStruct'.
//
// In any case, ensure that we don't crash.
var localFooObject = FooStruct(unknown_var)
localFooObject.#^TC_VAR_3^#
}
func testTypecheckVar4() {
var localInt = 42
var localFooObject = FooStruct(localInt)
localFooObject.#^TC_VAR_4^#
}
func testTypecheckVar5() {
var localInt = 42
FooStruct(localInt).#^TC_VAR_5^#
}
func testTypecheckVar6() {
var localInt = 42
FooStruct(localInt).builderFunc1().#^TC_VAR_6^#
}
func testTypecheckVar7() {
// FIXME: We don't display any useful completions here, although we could --
// it is obvious that the expression could only have type 'FooStruct'.
//
// In any case, ensure that we don't crash.
var localInt = 42
FooStruct(localInt).builderFunc2(unknown_var).#^TC_VAR_7^#
}
class TestTypeCheckVarInConstructor1 {
init() {
var localFooObject = FooStruct()
localFooObject.#^TC_VAR_IN_CONSTRUCTOR_1^#
}
}
class TestTypeCheckVarInConstructor2 {
init { // Missing parameters
var localFooObject = FooStruct()
localFooObject.#^TC_VAR_IN_CONSTRUCTOR_2^#
}
}
class TestTypeCheckVarInDestructor1 {
deinit {
var localFooObject = FooStruct()
localFooObject.#^TC_VAR_IN_DESTRUCTOR_1^#
}
}
func testTypecheckVarInIf1() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
#^TC_VAR_IF_1^#
}
}
func testTypecheckVarInIf2() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
} else {
#^TC_VAR_IF_2^#
}
}
func testTypecheckVarInIf3() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if {
#^TC_VAR_IF_3^#
}
}
func testTypecheckVarInIf4() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if {
} else {
#^TC_VAR_IF_4^#
}
}
class TestTypeCheckVarInIfInConstructor1 {
init() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
#^TC_VAR_IF_IN_CONSTRUCTOR_1^#
}
}
}
class TestTypeCheckVarInIfInDestructor1 {
deinit {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {
#^TC_VAR_IF_IN_DESTRUCTOR_1^#
}
}
}
func testExprPostfixBegin1() {
var localInt = 42
var localFooObject = FooStruct(localInt)
#^EXPR_POSTFIX_BEGIN_1^#
}
func testExprPostfixBegin2() {
var localInt = 42
var localFooObject = FooStruct(localInt)
if true {}
#^EXPR_POSTFIX_BEGIN_2^#
}
class TestTypeCheckExprPostfixBeginInConstructor1 {
init() {
var localInt = 42
var localFooObject = FooStruct(localInt)
#^EXPR_POSTFIX_BEGIN_IN_CONSTRUCTOR_1^#
}
}
class TestTypeCheckExprPostfixBeginInDestructor1 {
deinit {
var localInt = 42
var localFooObject = FooStruct(localInt)
#^EXPR_POSTFIX_BEGIN_IN_DESTRUCTOR_1^#
}
}
|
apache-2.0
|
4286f55b38d6efcb78423bb7ab0619f5
| 34.357843 | 170 | 0.713434 | 3.356445 | false | true | false | false |
brentdax/swift
|
stdlib/public/core/PrefixWhile.swift
|
2
|
10311
|
//===-- PrefixWhile.swift - Lazy views for prefix(while:) -----*- swift -*-===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
/// A sequence whose elements consist of the initial consecutive elements of
/// some base sequence that satisfy a given predicate.
@_fixed_layout // lazy-performance
public struct LazyPrefixWhileSequence<Base: Sequence> {
public typealias Element = Base.Element
@inlinable // lazy-performance
internal init(_base: Base, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
}
extension LazyPrefixWhileSequence {
/// An iterator over the initial elements traversed by a base iterator that
/// satisfy a given predicate.
///
/// This is the associated iterator for the `LazyPrefixWhileSequence`,
/// `LazyPrefixWhileCollection`, and `LazyPrefixWhileBidirectionalCollection`
/// types.
@_fixed_layout // lazy-performance
public struct Iterator {
public typealias Element = Base.Element
@usableFromInline // lazy-performance
internal var _predicateHasFailed = false
@usableFromInline // lazy-performance
internal var _base: Base.Iterator
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
@inlinable // lazy-performance
internal init(_base: Base.Iterator, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
}
}
extension LazyPrefixWhileSequence.Iterator: IteratorProtocol, Sequence {
@inlinable // lazy-performance
public mutating func next() -> Element? {
// Return elements from the base iterator until one fails the predicate.
if !_predicateHasFailed, let nextElement = _base.next() {
if _predicate(nextElement) {
return nextElement
} else {
_predicateHasFailed = true
}
}
return nil
}
}
extension LazyPrefixWhileSequence: Sequence {
public typealias SubSequence = AnySequence<Element> // >:(
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), predicate: _predicate)
}
}
extension LazyPrefixWhileSequence: LazySequenceProtocol {
public typealias Elements = LazyPrefixWhileSequence
}
extension LazySequenceProtocol {
/// Returns a lazy sequence of the initial consecutive elements that satisfy
/// `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the sequence as
/// its argument and returns `true` if the element should be included or
/// `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
@inlinable // lazy-performance
public __consuming func prefix(
while predicate: @escaping (Elements.Element) -> Bool
) -> LazyPrefixWhileSequence<Self.Elements> {
return LazyPrefixWhileSequence(_base: self.elements, predicate: predicate)
}
}
/// A lazy `${Collection}` wrapper that includes the initial consecutive
/// elements of an underlying collection that satisfy a predicate.
///
/// - Note: The performance of accessing `endIndex`, `last`, any methods that
/// depend on `endIndex`, or moving an index depends on how many elements
/// satisfy the predicate at the start of the collection, and may not offer
/// the usual performance given by the `Collection` protocol. Be aware,
/// therefore, that general operations on `${Self}` instances may not have
/// the documented complexity.
@_fixed_layout // lazy-performance
public struct LazyPrefixWhileCollection<Base: Collection> {
public typealias Element = Base.Element
public typealias SubSequence = Slice<LazyPrefixWhileCollection<Base>>
@inlinable // lazy-performance
internal init(_base: Base, predicate: @escaping (Element) -> Bool) {
self._base = _base
self._predicate = predicate
}
@usableFromInline // lazy-performance
internal var _base: Base
@usableFromInline // lazy-performance
internal let _predicate: (Element) -> Bool
}
extension LazyPrefixWhileCollection: Sequence {
public typealias Iterator = LazyPrefixWhileSequence<Base>.Iterator
@inlinable // lazy-performance
public __consuming func makeIterator() -> Iterator {
return Iterator(_base: _base.makeIterator(), predicate: _predicate)
}
}
extension LazyPrefixWhileCollection {
/// A position in the base collection of a `LazyPrefixWhileCollection` or the
/// end of that collection.
@_frozen // lazy-performance
@usableFromInline
internal enum _IndexRepresentation {
case index(Base.Index)
case pastEnd
}
/// A position in a `LazyPrefixWhileCollection` or
/// `LazyPrefixWhileBidirectionalCollection` instance.
@_fixed_layout // lazy-performance
public struct Index {
/// The position corresponding to `self` in the underlying collection.
@usableFromInline // lazy-performance
internal let _value: _IndexRepresentation
/// Creates a new index wrapper for `i`.
@inlinable // lazy-performance
internal init(_ i: Base.Index) {
self._value = .index(i)
}
/// Creates a new index that can represent the `endIndex` of a
/// `LazyPrefixWhileCollection<Base>`. This is not the same as a wrapper
/// around `Base.endIndex`.
@inlinable // lazy-performance
internal init(endOf: Base) {
self._value = .pastEnd
}
}
}
extension LazyPrefixWhileCollection.Index: Comparable {
@inlinable // lazy-performance
public static func == (
lhs: LazyPrefixWhileCollection<Base>.Index,
rhs: LazyPrefixWhileCollection<Base>.Index
) -> Bool {
switch (lhs._value, rhs._value) {
case let (.index(l), .index(r)):
return l == r
case (.pastEnd, .pastEnd):
return true
case (.pastEnd, .index), (.index, .pastEnd):
return false
}
}
@inlinable // lazy-performance
public static func < (
lhs: LazyPrefixWhileCollection<Base>.Index,
rhs: LazyPrefixWhileCollection<Base>.Index
) -> Bool {
switch (lhs._value, rhs._value) {
case let (.index(l), .index(r)):
return l < r
case (.index, .pastEnd):
return true
case (.pastEnd, _):
return false
}
}
}
extension LazyPrefixWhileCollection.Index: Hashable where Base.Index: Hashable {
/// Hashes the essential components of this value by feeding them into the
/// given hasher.
///
/// - Parameter hasher: The hasher to use when combining the components
/// of this instance.
@inlinable
public func hash(into hasher: inout Hasher) {
switch _value {
case .index(let value):
hasher.combine(value)
case .pastEnd:
hasher.combine(Int.max)
}
}
}
extension LazyPrefixWhileCollection: Collection {
@inlinable // lazy-performance
public var startIndex: Index {
return Index(_base.startIndex)
}
@inlinable // lazy-performance
public var endIndex: Index {
// If the first element of `_base` satisfies the predicate, there is at
// least one element in the lazy collection: Use the explicit `.pastEnd` index.
if let first = _base.first, _predicate(first) {
return Index(endOf: _base)
}
// `_base` is either empty or `_predicate(_base.first!) == false`. In either
// case, the lazy collection is empty, so `endIndex == startIndex`.
return startIndex
}
@inlinable // lazy-performance
public func index(after i: Index) -> Index {
_precondition(i != endIndex, "Can't advance past endIndex")
guard case .index(let i) = i._value else {
_preconditionFailure("Invalid index passed to index(after:)")
}
let nextIndex = _base.index(after: i)
guard nextIndex != _base.endIndex && _predicate(_base[nextIndex]) else {
return Index(endOf: _base)
}
return Index(nextIndex)
}
@inlinable // lazy-performance
public subscript(position: Index) -> Element {
switch position._value {
case .index(let i):
return _base[i]
case .pastEnd:
_preconditionFailure("Index out of range")
}
}
}
extension LazyPrefixWhileCollection: BidirectionalCollection
where Base: BidirectionalCollection {
@inlinable // lazy-performance
public func index(before i: Index) -> Index {
switch i._value {
case .index(let i):
_precondition(i != _base.startIndex, "Can't move before startIndex")
return Index(_base.index(before: i))
case .pastEnd:
// Look for the position of the last element in a non-empty
// prefix(while:) collection by searching forward for a predicate
// failure.
// Safe to assume that `_base.startIndex != _base.endIndex`; if they
// were equal, `_base.startIndex` would be used as the `endIndex` of
// this collection.
_sanityCheck(!_base.isEmpty)
var result = _base.startIndex
while true {
let next = _base.index(after: result)
if next == _base.endIndex || !_predicate(_base[next]) {
break
}
result = next
}
return Index(result)
}
}
}
extension LazyPrefixWhileCollection: LazyCollectionProtocol {
public typealias Elements = LazyPrefixWhileCollection
}
extension LazyCollectionProtocol {
/// Returns a lazy collection of the initial consecutive elements that
/// satisfy `predicate`.
///
/// - Parameter predicate: A closure that takes an element of the collection
/// as its argument and returns `true` if the element should be included
/// or `false` otherwise. Once `predicate` returns `false` it will not be
/// called again.
@inlinable // lazy-performance
public __consuming func prefix(
while predicate: @escaping (Element) -> Bool
) -> LazyPrefixWhileCollection<Elements> {
return LazyPrefixWhileCollection(
_base: self.elements, predicate: predicate)
}
}
|
apache-2.0
|
ee9c6dc3065c30fa45151e65ec19752e
| 31.942492 | 83 | 0.683251 | 4.431027 | false | false | false | false |
codefirst/AsakusaSatelliteSwiftClient
|
Classes/ios/Auth.swift
|
1
|
1305
|
import SafariServices
import UIKit
public class Auth: NSObject, SFSafariViewControllerDelegate {
public var completion: ((String?) -> Void)? // apiKey if signed in
public private(set) var signinVC: SFSafariViewController?
public func presentSignInViewController(on onVC: UIViewController, rootURL: URL, callbackScheme: String) {
guard let authURL = URL(string: "/auth/twitter?callback_scheme=\(callbackScheme)", relativeTo: rootURL) else { return }
let vc = SFSafariViewController(url: authURL)
vc.delegate = self
vc.modalPresentationStyle = .formSheet
onVC.present(vc, animated: true, completion: nil)
self.signinVC = vc
}
public func open(url: URL, options: [UIApplication.OpenURLOptionsKey : Any]) -> Bool {
let components = NSURLComponents(url: url, resolvingAgainstBaseURL: false)
if let apiKey = components?.queryItems?.filter({$0.name == "api_key"}).first?.value {
// signed in
completion?(apiKey)
} else {
// not signed in
completion?(nil)
}
signinVC?.dismiss(animated: true, completion: nil)
return true
}
public func safariViewControllerDidFinish(_ controller: SFSafariViewController) {
signinVC = nil
}
}
|
mit
|
db7e6352f40398a88356a2b1c294c275
| 37.382353 | 127 | 0.65977 | 4.961977 | false | false | false | false |
mokemokechicken/DeepTransition
|
Pod/Classes/ViewController/UIViewControllerExtension.swift
|
1
|
3914
|
//
// UIViewControllerExtension.swift
// DeepTransitionSample
//
// Created by 森下 健 on 2014/12/23.
// Copyright (c) 2014年 Yumemi. All rights reserved.
//
import UIKit
@objc public protocol HasControllerName {
optional var controllerName : String { get }
}
private var transitionAgentKey: UInt8 = 0
extension UIViewController : TransitionViewControllerProtocol, HasControllerName {
public var transition : TransitionCenterProtocol { return TransitionServiceLocater.transitionCenter }
public var transitionAgent: TransitionAgentProtocol? {
get {
return objc_getAssociatedObject(self, &transitionAgentKey) as? TransitionAgentProtocol
}
set {
objc_setAssociatedObject(self, &transitionAgentKey, newValue, UInt(OBJC_ASSOCIATION_RETAIN))
}
}
public func setupAgent(path: TransitionPath) {
if self.transitionAgent?.transitionPath == path {
return
}
transitionAgent = createTransitionAgent(path)
transitionAgent!.delegate = self
if transitionAgent!.delegateDefaultImpl == nil {
transitionAgent!.delegateDefaultImpl = createTransitionDefaultHandler(path)
}
}
public func viewDidShow() {
reportViewDidAppear()
}
public func reportViewDidAppear() {
if let path = transitionAgent?.transitionPath {
mylog("reportViewDidAppear: \(path.path)")
transition.reportViewDidAppear(path)
}
}
public func createTransitionAgent(path: TransitionPath) -> TransitionAgentProtocol {
return TransitionAgent(path: path)
}
public func createTransitionDefaultHandler(path: TransitionPath) -> TransitionAgentDelegate {
return TransitionDefaultHandler(viewController: self, path: path)
}
public func getControllerName() -> String? {
return (self as HasControllerName).controllerName
}
}
extension UINavigationController {
override public func viewDidShow() {
super.viewDidShow()
viewControllers?.last?.viewDidShow()
}
}
private struct ViewControllerInContainer {
let index : Int
let name : String?
let vc : UIViewController
}
extension UITabBarController {
public func findViewControllerInCollection(name: String) -> (index: Int, vc: UIViewController)? {
for vcInfo in rootViewControllersInCollection() {
if vcInfo.name == name {
return (index: vcInfo.index, vc: vcInfo.vc)
}
}
return nil
}
public func setupAgentToInnerNameController() {
if let path = self.transitionAgent?.transitionPath {
for vcInfo in rootViewControllersInCollection() {
if let name = vcInfo.name {
vcInfo.vc.setupAgent(path.appendPath(TransitionPath(path: "#\(name)")))
}
}
}
}
private func findNotContainerViewController(vc: UIViewController!) -> UIViewController? {
if vc == nil {
return vc
}
switch vc {
case let (nav as UINavigationController):
return findNotContainerViewController(nav.viewControllers?.first as? UIViewController)
default:
return vc
}
}
private func rootViewControllersInCollection() -> [ViewControllerInContainer] {
var ret = [ViewControllerInContainer]()
var index = 0
for innerVC in viewControllers as? [UIViewController] ?? [] {
if let vc = findNotContainerViewController(innerVC) {
ret.append(ViewControllerInContainer(index: index, name: vc.getControllerName(), vc: vc))
}
index++
}
return ret
}
}
private func mylog(s: String) {
#if DEBUG
NSLog(s)
#endif
}
|
mit
|
be47b0ec0f7618a00932723e8b91a3d7
| 29.046154 | 105 | 0.632873 | 5.046512 | false | false | false | false |
rene-dohan/CS-IOS
|
Renetik/Renetik/Classes/Core/Extensions/Renetik/CSMainController+Menu.swift
|
1
|
976
|
//
// CSMainController.swift
// Renetik
//
// Created by Rene Dohan on 3/14/19.
//
import Foundation
import RenetikObjc
public extension CSMainController {
@discardableResult
public func menu(title: String = "", image: UIImage? = nil,
type: UIBarButtonItem.SystemItem? = nil,
onClick: ((CSMenuItem) -> Void)? = nil) -> CSMenuItem {
menuAdd().item(with: title, type: type, image: image, action: onClick)
}
@discardableResult
public func menu(title: String = "", image: UIImage? = nil,
type: UIBarButtonItem.SystemItem? = nil,
onClick: (Func)? = nil) -> CSMenuItem {
menuAdd().item(with: title, type: type, image: image, action: { _ in onClick?() })
}
@discardableResult
public func menu(view: UIView,
onClick: ((CSMenuItem) -> Void)? = nil) -> CSMenuItem {
menuAdd().item(with: view, action: onClick)
}
}
|
mit
|
45a562da171ebd7842581c6bb396677d
| 30.483871 | 90 | 0.577869 | 4.153191 | false | false | false | false |
jianghongbing/APIReferenceDemo
|
UIKit/UIViewController/UIViewController/LifeCircleViewController.swift
|
1
|
4699
|
//
// LifeCircleViewController.swift
// UIViewController
//
// Created by pantosoft on 2017/6/26.
// Copyright © 2017年 jianghongbing. All rights reserved.
//
import UIKit
class LifeCircleViewController: UIViewController {
// @IBOutlet weak var redView: UIView!
// @IBOutlet weak var widthConstraint: NSLayoutConstraint!
// @IBOutlet weak var heightConstraint: NSLayoutConstraint!
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
debugPrint(#function)
}
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
debugPrint(#function)
}
// @objc private func test(_ sender: Any) {
//
// view.layoutIfNeeded()
// }
// convenience init() {
// self.init(nibName: nil, bundle: nil)
// debugPrint(#function)
// }
//1.在load view中可以将view controller中默认的View替换成自定义的view
override func loadView() {
view = UIView()
view.backgroundColor = UIColor.orange
debugPrint(#function)
// navigationItem.rightBarButtonItem = UIBarButtonItem(title: "test", style: .plain, target: self, action: #selector(test(_:)))
}
override func viewDidLoad() {
super.viewDidLoad()
debugPrint(#function)
title = "Life Circle"
let redView = UIView()
redView.backgroundColor = .red
redView.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(redView)
redView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
redView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true
redView.widthAnchor.constraint(equalToConstant: 100).isActive = true
redView.heightAnchor.constraint(equalToConstant: 100).isActive = true
//view controller的生命周期,下面是各个方法调用的顺序
//1.初始化.如果通过storyboard获取的viewController,那么会调用initWithCoder方法,如果是通过xib方式,会调用initWihtNibName:bundle的方法,如果是通过纯代码的方式,那么会调用init
//2.awakeFromNib: 通过storyboard或者xib的方式,会走awakeFromNib的方法,纯代码方式不会走该方法
//3.loadView: 可以在这个方法中将view controller中的view换成自己定义的view
//4.viewDidLoad:视图已经加载完成的时候调用,该方法只会调用一次
//5.viewWillAppear:view将要出现的时候会调用该方法,每一次view 将要出现的时候都会调用,可能会调用多次
//6.viewWillLayoutSubViews:view中的subView将要布局的时候,会收到该消息,可能会调用多次
//7.viewDidLayoutSubViews:view中的subView都布局完成的时候,会收到该消息,可能会调用多次
//8.viewDidAppear:view以及view的subView显示完成的时候调用,可能会调用多次
//7.viewWillDisappear:在view将要消息的时候会收到该消息,可能会调用多次
//8.viewDidDisappear: 在view已经消息的时候会收到该消息,可能会调用多次
//9.didReceiveMemoryWarning:在收到内存警告的时候,会收到该消息
//10.dealloc当控制器对象被回收的时候,会收到该消息
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
debugPrint(#function)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
debugPrint(#function)
}
override func viewWillDisappear(_ animated: Bool) {
super.viewWillDisappear(animated)
debugPrint(#function)
}
override func viewDidDisappear(_ animated: Bool) {
super.viewDidDisappear(animated)
debugPrint(#function)
}
override func viewWillLayoutSubviews() {
super.viewWillLayoutSubviews()
debugPrint(#function)
}
override func viewDidLayoutSubviews() {
super.viewDidLayoutSubviews()
debugPrint(#function)
}
override func didReceiveMemoryWarning() {
debugPrint(#function)
}
override func awakeFromNib() {
super.awakeFromNib()
debugPrint(#function)
}
deinit {
debugPrint(#function)
}
override func updateViewConstraints() {
super.updateViewConstraints()
print(#function)
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
view.setNeedsUpdateConstraints()
}
}
|
mit
|
c20b745bbe3bc4425c172544c722bfa7
| 31.253968 | 134 | 0.666093 | 4.571429 | false | false | false | false |
luowei/Swift-Samples
|
LWPickerLabel/TextLabel/LWAddressLabel.swift
|
1
|
10951
|
//
// LWAddressLabel.swift
// LWAddressLabel
//
// Created by luowei on 16/8/6.
// Copyright © 2016年 wodedata. All rights reserved.
//
import UIKit
class LWAddressLabel: UILabel {
var provinceId:String = "0"
var cityId:String = "0"
var areaId:String = "0"
var townId:String = "0"
lazy var _inputView: LWAddressPickerView? = {
guard let inputV = LWAddressPickerView.loadFromNibNamed("LWAddressPickerView") as? LWAddressPickerView as LWAddressPickerView? else{return nil}
inputV.responder = self
return inputV
}()
// MARK: - Override
override var inputView: UIView? {
get { return _inputView }
// set {
// guard let v = newValue as? LWAddressPickerView as LWAddressPickerView? else{ return }
// _inputView = v
// }
}
override func awakeFromNib() {
self.userInteractionEnabled = true
let gesture = UITapGestureRecognizer(target: self, action: #selector(LWAddressLabel.tapSelf(_:)))
gesture.numberOfTapsRequired = 1
self.addGestureRecognizer(gesture)
}
override func canBecomeFirstResponder() -> Bool {
return self.enabled
}
override func resignFirstResponder() -> Bool {
return super.resignFirstResponder()
}
func tapSelf(sender: AnyObject) {
self.becomeFirstResponder()
}
func setAddress(province provinceId:String,province:String,cityId:String,city:String,areaId:String,area:String,townId:String,town:String){
self.provinceId = provinceId
self.cityId = cityId
self.areaId = areaId
self.townId = townId
self.text = province + city + area + town
}
}
enum AddrFiled {
case Province(String?)
case City(String?)
case Area(String?)
case Town(String?)
}
class LWAddressPickerView: UIView {
@IBOutlet weak var provinceBtn: UIButton!
@IBOutlet weak var cityBtn: UIButton!
@IBOutlet weak var areaBtn: UIButton!
@IBOutlet weak var townBtn: UIButton!
@IBOutlet weak var clearBtn: UIButton!
@IBOutlet weak var pickView: UITableView!
weak var responder: UIResponder?
var addressService: LWAddressService?
var provinceData:[LWAddress]?
var cityData:[LWAddress]?
var areaData:[LWAddress]?
var townData:[LWAddress]?
var selProvince:String = "0"
var selCity:String = "0"
var selArea:String = "0"
var selTown:String = "0"
var showFiled:AddrFiled = .Province("0")
override func awakeFromNib() {
super.awakeFromNib()
clearBtn.touchAreaEdgeInsets = UIEdgeInsetsMake(-5, -5, -5, -5)
self.pickView.registerClass(LWAddressTableViewCell.self, forCellReuseIdentifier: "cell")
self.pickView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15)
self.pickView.tableFooterView = UIView(frame: CGRect.zero)
guard let service = try? LWAddressService.open() as LWAddressService? else{ return }
addressService = service
}
@IBAction func ok(){
guard let label = responder as? LWAddressLabel as LWAddressLabel? else{return}
guard let province = provinceBtn.titleLabel?.text as String? where province != "请选择" && province != "" else{return}
guard let city = cityBtn.titleLabel?.text as String? where city != "请选择" && city != "" else{return}
guard let area = areaBtn.titleLabel?.text as String? where area != "请选择" && area != "" else{return}
guard let town = townBtn.titleLabel?.text as String? where townBtn.selected && town != "请选择" && town != "" else{
label.setAddress(province:selProvince, province: province, cityId: selCity, city: city, areaId: selArea, area: area, townId: selTown, town: "")
responder?.resignFirstResponder()
return
}
label.setAddress(province:selProvince, province: province, cityId: selCity, city: city, areaId: selArea, area: area, townId: selTown, town: town)
responder?.resignFirstResponder()
}
@IBAction func close(){
responder?.resignFirstResponder()
}
@IBAction func clearBtnStatus(){
provinceBtn.selected = false;
cityBtn.selected = false;
areaBtn.selected = false;
townBtn.selected = false;
provinceBtn.setTitle("请选择", forState: .Normal)
cityBtn.setTitle("请选择", forState: .Normal)
areaBtn.setTitle("请选择", forState: .Normal)
townBtn.setTitle("请选择", forState: .Normal)
selProvince = "0"
selCity = "0"
selArea = "0"
selTown = "0"
showFiled = .Province(nil)
self.pickView.reloadData()
self.pickView.setContentOffset(CGPoint(x:0,y:0), animated: false)
}
@IBAction func provinceBtnClick(){
cityBtn.selected = false;
areaBtn.selected = false;
townBtn.selected = false;
cityBtn.setTitle("请选择", forState: .Normal)
areaBtn.setTitle("请选择", forState: .Normal)
townBtn.setTitle("请选择", forState: .Normal)
selCity = "0"
selArea = "0"
selTown = "0"
showFiled = .Province(nil)
self.pickView.reloadData()
}
@IBAction func cityBtnClick(){
if !provinceBtn.selected {
return
}
areaBtn.selected = false;
townBtn.selected = false;
areaBtn.setTitle("请选择", forState: .Normal)
townBtn.setTitle("请选择", forState: .Normal)
selArea = "0"
selTown = "0"
showFiled = .City(selProvince)
self.pickView.reloadData()
}
@IBAction func areaBtnClick(){
if !cityBtn.selected {
return
}
townBtn.selected = false;
townBtn.setTitle("请选择", forState: .Normal)
selTown = "0"
showFiled = .Area(selCity)
self.pickView.reloadData()
}
@IBAction func townBtnClick(){
if !areaBtn.selected {
return
}
showFiled = .Town(selArea)
self.pickView.reloadData()
}
}
extension LWAddressPickerView: UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
var count = 0
switch showFiled {
case .Province( _):
provinceData = addressService?.provinceList()
guard let data = provinceData as [LWAddress]? else { return 0 }
count = data.count
case .City( _):
cityData = addressService?.cityList(selProvince)
guard let data = cityData as [LWAddress]? else { return 0 }
count = data.count
case .Area(_):
areaData = addressService?.areaList(selCity)
guard let data = areaData as [LWAddress]? else { return 0 }
count = data.count
case .Town(_):
townData = addressService?.townList(selArea)
guard let data = townData as [LWAddress]? else { return 0 }
return data.count
}
return count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
guard let cell = tableView.dequeueReusableCellWithIdentifier("cell") as? LWAddressTableViewCell as LWAddressTableViewCell? else{ return UITableViewCell() }
cell.accessoryType = .None
switch showFiled {
case .Province(_):
guard let data = provinceData as [LWAddress]? else { return UITableViewCell() }
cell.textLabel?.text = data[indexPath.row].name
if(data[indexPath.row].ownId == selProvince){
cell.accessoryType = .Checkmark
}
case .City(_):
guard let data = cityData as [LWAddress]? else { return UITableViewCell() }
cell.textLabel?.text = data[indexPath.row].name
if(data[indexPath.row].ownId == selCity){
cell.accessoryType = .Checkmark
}
case .Area(_):
guard let data = areaData as [LWAddress]? else { return UITableViewCell() }
cell.textLabel?.text = data[indexPath.row].name
if(data[indexPath.row].ownId == selArea){
cell.accessoryType = .Checkmark
}
case .Town(_):
guard let data = townData as [LWAddress]? else { return UITableViewCell() }
cell.textLabel?.text = data[indexPath.row].name
if(data[indexPath.row].ownId == selTown){
cell.accessoryType = .Checkmark
}
}
return cell
}
}
extension LWAddressPickerView:UITableViewDelegate{
func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
return 30
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
// guard let cell = tableView.cellForRowAtIndexPath(indexPath) as? LWAddressTableViewCell as LWAddressTableViewCell? else{return}
tableView.deselectRowAtIndexPath(indexPath, animated: false)
switch showFiled {
case .Province(_):
guard let data = provinceData as [LWAddress]? else {return}
selProvince = data[indexPath.row].ownId
provinceBtn.setTitle(data[indexPath.row].name, forState: .Normal)
provinceBtn.selected = true
showFiled = .City(selProvince)
case .City(_):
guard let data = cityData as [LWAddress]? else {return}
selCity = data[indexPath.row].ownId
cityBtn.setTitle(data[indexPath.row].name, forState: .Normal)
cityBtn.selected = true
showFiled = .Area(selCity)
case .Area(_):
guard let data = areaData as [LWAddress]? else {return}
selArea = data[indexPath.row].ownId
areaBtn.setTitle(data[indexPath.row].name, forState: .Normal)
areaBtn.selected = true
showFiled = .Town(selArea)
case .Town(_):
guard let data = townData as [LWAddress]? else {return}
selTown = data[indexPath.row].ownId
townBtn.setTitle(data[indexPath.row].name, forState: .Normal)
townBtn.selected = true
showFiled = .Town(data[indexPath.row].superId)
}
tableView.reloadData()
}
}
class LWAddressTableViewCell : UITableViewCell{
var selId = "0"
override init(style: UITableViewCellStyle, reuseIdentifier: String?){
super.init(style: style, reuseIdentifier: reuseIdentifier)
self.textLabel?.font = UIFont.systemFontOfSize(14)
self.textLabel?.textColor = UIColor(red: 0.21, green: 0.21, blue: 0.21, alpha: 1)
}
required init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
}
}
|
apache-2.0
|
f24e15f07e1f4062f4ae94dda46b0a3f
| 34.272727 | 163 | 0.613586 | 4.517256 | false | false | false | false |
JiLiZART/InAppValidator
|
Sources/InAppValidator/iTunes/iTunesResponse.swift
|
1
|
2393
|
import Foundation
public struct iTunesResponse: ResponseProtocol {
public enum Status: Int {
case OK = 0
// The App Store could not read the JSON object you provided.
case APPSTORE_CANNOT_READ = 21000
// The data in the receipt-data property was malformed or missing.
case DATA_MALFORMED = 21002
// The receipt could not be authenticated.
case RECEIPT_NOT_AUTHENTICATED = 21003
// The shared secret you provided does not match the shared secret on file for your account.
// Only returned for iOS 6 style transaction receipts for auto-renewable subscriptions.
case SHARED_SECRET_NOT_MATCH = 21004
// The receipt server is not currently available.
case RECEIPT_SERVER_UNAVAILABLE = 21005
// This receipt is valid but the subscription has expired. When this status code is returned to your server, the receipt data is also decoded and returned as part of the response.
// Only returned for iOS 6 style transaction receipts for auto-renewable subscriptions.
case RECEIPT_VALID_BUT_SUB_EXPIRED = 21006
// This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead.
// special case for app review handling - forward any request that is intended for the Sandbox but was sent to Production, this is what the app review team does
case SANDBOX_RECEIPT_SENT_TO_PRODUCTION = 21007
// This receipt is from the production environment, but it was sent to the test environment for verification. Send it to the production environment instead.
case PRODUCTION_RECEIPT_SENT_TO_SANDBOX = 21008
}
internal var json: [String: Any]? = nil
public var receipt: ReceiptProtocol? {
guard let receipt = try? iTunesReceipt(json: self.json) else {
return nil
}
return receipt
}
public var isValid: Bool {
guard let code = self.receipt?.code else {
return false
}
guard let status = iTunesResponse.Status(rawValue: code) else {
return false
}
switch (status) {
case .OK:
return true
default:
return false
}
}
init(json: [String: Any]?) {
self.json = json
}
}
|
mit
|
c8fb0fdc5fbaa33b1f8f30ea2d66af1b
| 40.982456 | 187 | 0.65608 | 4.766932 | false | true | false | false |
samgreen/SGGameNetworking
|
SGGameNetworking/GameViewController.swift
|
1
|
1430
|
//
// GameViewController.swift
// SGGameNetworking
//
// Created by Sam Green on 11/3/15.
// Copyright © 2015 Sam Green. All rights reserved.
//
import Foundation
import UIKit
class GameViewController: UIViewController {
var playerToView = [SGGamePlayer: UIView]()
var server: SGGameServer? {
didSet {
self.server?.delegate = self
}
}
var client: SGGameClient? {
didSet {
self.client?.delegate = self
}
}
}
extension GameViewController: SGGameServerDelegate {
func playerDidConnect(player: SGGamePlayer) {
let view = UIView(frame: CGRect(x: 0, y: 0, width: 64, height: 64))
view.addSubview(view)
playerToView[player] = view
}
func playerDidDisconnect(player: SGGamePlayer) {
if let view = playerToView[player] {
view.removeFromSuperview()
}
}
func didReceivePacketFromPlayer(player: SGGamePlayer, packet: SGGamePacket) {
print("Received packet from player")
}
}
extension GameViewController: SGGameClientDelegate {
func didFindServerHost(host: SGGameServerHost) {
print("Found host: \(host.name)")
}
func didConnect() {
}
func didDisconnect() {
}
func didReceivePacketFromPlayer(packet: SGGamePacket, player: SGGamePlayer) {
print("Received packet from player")
}
}
|
apache-2.0
|
671619bd0b66c45ed54a6a8dc7112ad8
| 22.442623 | 81 | 0.621414 | 4.343465 | false | false | false | false |
finn-no/Finjinon
|
Sources/PhotoCaptureViewController/ImagePickerAdapter.swift
|
1
|
2365
|
//
// Copyright (c) 2017 FINN.no AS. All rights reserved.
//
import UIKit
import MobileCoreServices
import Photos
public protocol ImagePickerAdapter {
// Return a UIViewController suitable for picking one or more images. The supplied selectionHandler may be called more than once.
// the argument is a dictionary with either (or both) the UIImagePickerControllerOriginalImage or UIImagePickerControllerReferenceURL keys
// The completion handler will be called when done, supplying the caller with a didCancel flag which will be true
// if the user cancelled the image selection process.
// NOTE: The caller is responsible for dismissing any presented view controllers in the completion handler.
func viewControllerForImageSelection(_ selectedAssetsHandler: @escaping ([PHAsset]) -> Void, completion: @escaping (Bool) -> Void) -> UIViewController
}
open class ImagePickerControllerAdapter: NSObject, ImagePickerAdapter, UIImagePickerControllerDelegate, UINavigationControllerDelegate {
var selectionHandler: ([PHAsset]) -> Void = { _ in }
var completionHandler: (_ didCancel: Bool) -> Void = { _ in }
open func viewControllerForImageSelection(_ selectedAssetsHandler: @escaping ([PHAsset]) -> Void, completion: @escaping (Bool) -> Void) -> UIViewController {
selectionHandler = selectedAssetsHandler
completionHandler = completion
let picker = UIImagePickerController()
picker.mediaTypes = [kUTTypeImage as String]
picker.delegate = self
return picker
}
open func imagePickerController(_: UIImagePickerController, didFinishPickingMediaWithInfo info: [UIImagePickerController.InfoKey: Any]) {
guard let referenceURL = info[.referenceURL] as? URL else {
completionHandler(true)
return
}
let fetchResult = PHAsset.fetchAssets(withALAssetURLs: [referenceURL], options: nil)
if let asset = fetchResult.firstObject {
selectionHandler([asset])
completionHandler(false)
} else {
NSLog("*** Failed to fetch PHAsset for asset library URL: \(referenceURL): \(String(describing: fetchResult.firstObject))")
completionHandler(true)
}
}
open func imagePickerControllerDidCancel(_: UIImagePickerController) {
completionHandler(true)
}
}
|
mit
|
3c04aff18e5bbb772b446ce320fb9e77
| 43.622642 | 161 | 0.716279 | 5.698795 | false | false | false | false |
yoichitgy/SwinjectSimpleExample
|
SwinjectSimpleExampleTests/WeatherFetcherSpec.swift
|
2
|
2969
|
//
// WeatherFetcherSpec.swift
// SwinjectSimpleExample
//
// Created by Yoichi Tagaya on 8/10/15.
// Copyright (c) 2015 Swinject Contributors. All rights reserved.
//
import Quick
import Nimble
import Swinject
@testable import SwinjectSimpleExample
class WeatherFetcherSpec: QuickSpec {
struct StubNetwork: Networking {
fileprivate static let json =
"{" +
"\"list\": [" +
"{" +
"\"id\": 2643743," +
"\"name\": \"London\"," +
"\"weather\": [" +
"{" +
"\"main\": \"Rain\"" +
"}" +
"]" +
"}," +
"{" +
"\"id\": 3451190," +
"\"name\": \"Rio de Janeiro\"," +
"\"weather\": [" +
"{" +
"\"main\": \"Clear\"" +
"}" +
"]" +
"}" +
"]" +
"}"
func request(_ response: @escaping (Data?) -> ()) {
let data = StubNetwork.json.data(using: String.Encoding.utf8, allowLossyConversion: false)
response(data)
}
}
override func spec() {
var container: Container!
beforeEach {
container = Container()
// Registrations for the network using Alamofire.
container.register(Networking.self) { _ in Network() }
container.register(WeatherFetcher.self) { r in
WeatherFetcher(networking: r.resolve(Networking.self)!)
}
// Registration for the stub network.
container.register(Networking.self, name: "stub") { _ in StubNetwork() }
container.register(WeatherFetcher.self, name: "stub") { r in
WeatherFetcher(networking: r.resolve(Networking.self, name: "stub")!)
}
}
it("returns cities.") {
var cities: [City]?
let fetcher = container.resolve(WeatherFetcher.self)!
fetcher.fetch { cities = $0 }
expect(cities).toEventuallyNot(beNil())
expect(cities?.count).toEventually(beGreaterThan(0))
}
it("fills weather data.") {
var cities: [City]?
let fetcher = container.resolve(WeatherFetcher.self, name: "stub")!
fetcher.fetch { cities = $0 }
expect(cities?[0].id).toEventually(equal(2643743))
expect(cities?[0].name).toEventually(equal("London"))
expect(cities?[0].weather).toEventually(equal("Rain"))
expect(cities?[1].id).toEventually(equal(3451190))
expect(cities?[1].name).toEventually(equal("Rio de Janeiro"))
expect(cities?[1].weather).toEventually(equal("Clear"))
}
}
}
|
mit
|
73ef6924fd4a653d75f5d6ead75a1fd5
| 33.523256 | 102 | 0.471202 | 4.973199 | false | false | false | false |
farhanpatel/firefox-ios
|
Storage/SQL/SQLiteFavicons.swift
|
3
|
3182
|
/* 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 Deferred
import Shared
open class SQLiteFavicons {
let db: BrowserDB
required public init(db: BrowserDB) {
self.db = db
}
public func getFaviconIDQuery(url: String) -> (sql: String, args: Args?) {
var args: Args = []
args.append(url)
return (sql: "SELECT id FROM \(TableFavicons) WHERE url = ? LIMIT 1", args: args)
}
public func getInsertFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) {
var args: Args = []
args.append(favicon.url)
args.append(favicon.width)
args.append(favicon.height)
args.append(favicon.date)
args.append(favicon.type.rawValue)
return (sql: "INSERT INTO \(TableFavicons) (url, width, height, date, type) VALUES (?,?,?,?,?)", args: args)
}
public func getUpdateFaviconQuery(favicon: Favicon) -> (sql: String, args: Args?) {
var args = Args()
args.append(favicon.width)
args.append(favicon.height)
args.append(favicon.date)
args.append(favicon.type.rawValue)
args.append(favicon.url)
return (sql: "UPDATE \(TableFavicons) SET width = ?, height = ?, date = ?, type = ? WHERE url = ?", args: args)
}
public func getCleanupFaviconsQuery() -> (sql: String, args: Args?) {
return (sql: "DELETE FROM \(TableFavicons) " +
"WHERE \(TableFavicons).id NOT IN (" +
"SELECT faviconID FROM \(TableFaviconSites) " +
"UNION ALL " +
"SELECT faviconID FROM \(TableBookmarksLocal) WHERE faviconID IS NOT NULL " +
"UNION ALL " +
"SELECT faviconID FROM \(TableBookmarksMirror) WHERE faviconID IS NOT NULL" +
")", args: nil)
}
public func insertOrUpdateFavicon(_ favicon: Favicon) -> Deferred<Maybe<Int>> {
return db.withConnection { conn -> Int in
self.insertOrUpdateFaviconInTransaction(favicon, conn: conn) ?? 0
}
}
func insertOrUpdateFaviconInTransaction(_ favicon: Favicon, conn: SQLiteDBConnection) -> Int? {
let query = self.getFaviconIDQuery(url: favicon.url)
let cursor = conn.executeQuery(query.sql, factory: IntFactory, withArgs: query.args)
if let id = cursor[0] {
let updateQuery = self.getUpdateFaviconQuery(favicon: favicon)
do {
try conn.executeChange(updateQuery.sql, withArgs: updateQuery.args)
} catch {
return nil
}
return id
}
let insertQuery = self.getInsertFaviconQuery(favicon: favicon)
do {
try conn.executeChange(insertQuery.sql, withArgs: insertQuery.args)
} catch {
return nil
}
return conn.lastInsertedRowID
}
public func cleanupFavicons() -> Success {
return self.db.run([getCleanupFaviconsQuery()])
}
}
|
mpl-2.0
|
92758a972e20bc087072a5d56939d892
| 35.574713 | 119 | 0.595852 | 4.401107 | false | false | false | false |
bromas/ActivityViewController
|
ActivityViewController/ActivitiesViewController.swift
|
1
|
4679
|
//
// ActivitiesViewController.swift
// ApplicationVCSample
//
// Created by Brian Thomas on 4/4/15.
// Copyright (c) 2015 Brian Thomas. All rights reserved.
//
import Foundation
import UIKit
public typealias ActivityGenerator = () -> UIViewController
open class ActivityViewController : UIViewController {
open var enableLogging: Bool = false
open var animating: Bool = false
internal var transitionManager: ActivityTransitionManager!
internal let activitiesManager: ActivityManager = ActivityManager()
private var hasInitialized: Bool = false
open var initialActivityIdentifier: String?
// Runs on the first display of a controller.
open var configureContainerView: (UIView) -> () = { view in }
// Runs when an activity is first initialized
open var activityInitiationClosure: (_ identifer: String, _ controller: UIViewController) -> () = { identifier, controller in }
// Runs each time an activity is presented.
open var activityConfigurationClosure: (_ identifer: String, _ controller: UIViewController) -> () = { identifier, controller in }
/* Lifecycle */
open override func viewDidLoad() {
super.viewDidLoad()
transitionManager = ActivityTransitionManager(containerController: self)
}
open override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
if let foundIdentifier = initialActivityIdentifier, !hasInitialized {
if case .first(let activity) = activitiesManager.activityForIdentifier(foundIdentifier) {
_ = transitionManager.initializeDisplayWithController(activity.controller)
}
}
hasInitialized = true
}
/* End Lifecycle */
open func registerGenerator(_ identifier: String, generator: @escaping ActivityGenerator) {
activitiesManager.registerGenerator(identifier, generator: generator)
}
open func flushInactiveActivitiesForIdentifier(_ identifier: String) {
activitiesManager.flushInactiveActivitiesForIdentifier(identifier)
}
// TODO: Cannot display a new controller of the same activityIdentifier atm. Refactor previous activity or activity stack to be queriable?
open func performActivityOperation(_ operation: ActivityOperation) {
// ignores calls to perform an activity operation while the controller is still animating.
guard !animating else {
return
}
let activityResult: ActivityResult
switch operation.selectRule {
case .new:
activitiesManager.flushInactiveActivitiesForIdentifier(operation.activityIdentifier)
activityResult = activitiesManager.activityForIdentifier(operation.activityIdentifier)
case .any:
activityResult = activitiesManager.activityForIdentifier(operation.activityIdentifier)
case .previous:
activityResult = activitiesManager.viewControllerForPreviousActivity()
}
processActivityResult(activityResult, withOperation: operation)
}
fileprivate func processActivityResult(_ activityResult: ActivityResult, withOperation operation: ActivityOperation) -> Void {
if enableLogging { print("Activity: \(activityResult)") }
switch activityResult {
case .first(let activity), .fresh(let activity):
activityInitiationClosure(activity.identifier, activity.controller)
activityConfigurationClosure(activity.identifier, activity.controller)
transitionManager.transitionToVC(activity.controller, withOperation: operation)
case .retrieved(let activity):
activityConfigurationClosure(activity.identifier, activity.controller)
transitionManager.transitionToVC(activity.controller, withOperation: operation)
case .current(_): break
case .error: break
}
}
}
// Helper functions for finding the right ActivityViewController to call operations on.
extension ActivityViewController {
public static var rootController: ActivityViewController? {
let delegate = UIApplication.shared.delegate
let rootController = delegate?.window??.rootViewController as? ActivityViewController
if let appVC = rootController {
return appVC
} else {
return .none
}
}
// Only works if the controller is a child controller of the activityVC (it must be the active activities controller.)
public static func closestParentOfController(_ controller: UIViewController) -> ActivityViewController? {
var inspectedController: UIViewController? = controller
while inspectedController != .none {
let parent = inspectedController?.parent
if let parentActivity = parent as? ActivityViewController {
return parentActivity
}
inspectedController = parent
}
return .none
}
}
|
mit
|
64fff3af16276f4e0d1c42627db79dd1
| 36.134921 | 140 | 0.747809 | 5.281038 | false | false | false | false |
WillH1983/BaseClassesSwift
|
Pod/Source Files/ServiceLayer/CustomMappingTransforms.swift
|
1
|
1942
|
//
// CustomMappingTransforms.swift
// Pods
//
// Created by William Hindenburg on 1/9/16.
//
//
import Foundation
import ObjectMapper
open class BaseClassesDateTransform: TransformType {
public typealias Object = Date
public typealias JSON = String
public init() {}
open func transformFromJSON(_ value: Any?) -> Date? {
if let timeInt = value as? Double {
return Date(timeIntervalSince1970: TimeInterval(timeInt))
}
if let timeStr = value as? String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let date = dateFormatter.date(from: timeStr)
return date
}
return nil
}
open func transformToJSON(_ value: Date?) -> String? {
if let date = value {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
dateFormatter.timeZone = TimeZone(identifier: "UTC")
let dateString = dateFormatter.string(from: date)
return dateString
}
return nil
}
}
open class BaseClassesDecimalNumberTransform: TransformType {
public typealias Object = NSDecimalNumber
public typealias JSON = String
public init() {}
open func transformFromJSON(_ value: Any?) -> NSDecimalNumber? {
if let stringValue = value as? String {
let number = NSDecimalNumber(string: stringValue)
return number
}
return nil
}
open func transformToJSON(_ value: NSDecimalNumber?) -> String? {
if let numberValue = value {
let formatter = NumberFormatter()
let stringValue = formatter.string(from: numberValue)
return stringValue
}
return nil
}
}
|
mit
|
23bc1147ab514ba5260b2937eba463e1
| 27.558824 | 69 | 0.599382 | 5.031088 | false | false | false | false |
kshin/Kana
|
Source/Season.swift
|
1
|
696
|
//
// Season.swift
// Kana
//
// Created by Ivan Lisovyi on 16/09/2016.
// Copyright © 2016 Ivan Lisovyi. All rights reserved.
//
import Foundation
import Unbox
public enum Season: String {
case spring
case summer
case fall
case winter
}
extension Season: UnboxableEnum {}
extension Season: ExpressibleByIntegerLiteral {
public typealias IntegerLiteralType = Int
public init(integerLiteral value: Season.IntegerLiteralType) {
switch value {
case 1:
self = .winter
case 2:
self = .spring
case 3:
self = .summer
case 4:
self = .fall
default:
self = .winter
}
}
}
|
mit
|
68759ef86c6ec2fe59303ab1f7f04814
| 17.289474 | 65 | 0.601439 | 4.212121 | false | false | false | false |
csnu17/My-Swift-learning
|
initialization/BlastOff.playground/Contents.swift
|
1
|
4120
|
import Foundation
struct RocketConfiguration {
let name: String = "Athena 9 Heavy"
let numberOfFirstStageCores: Int = 3
let numberOfSecondStageCores: Int = 1
let numberOfStageReuseLandingLegs: Int? = nil
}
struct RocketStageConfiguration {
let propellantMass: Double
let liquidOxygenMass: Double
let nominalBurnTime: Int
}
extension RocketStageConfiguration {
init(propellantMass: Double, liquidOxygenMass: Double) {
self.propellantMass = propellantMass
self.liquidOxygenMass = liquidOxygenMass
self.nominalBurnTime = 180
}
}
struct Weather {
let temperatureCelsius: Double
let windSpeedKilometersPerHour: Double
init(temperatureFahrenheit: Double = 72, windSpeedMilesPerHour: Double = 5) {
self.temperatureCelsius = (temperatureFahrenheit - 32) / 1.8
self.windSpeedKilometersPerHour = windSpeedMilesPerHour * 1.609344
}
}
struct GuidanceSensorStatus {
var currentZAngularVelocityRadiansPerMinute: Double
let initialZAngularVelocityRadiansPerMinute: Double
var needsCorrection: Bool
init(zAngularVelocityDegreesPerMinute: Double, needsCorrection: Bool = false) {
let radiansPerMinute = zAngularVelocityDegreesPerMinute * 0.01745329251994
self.currentZAngularVelocityRadiansPerMinute = radiansPerMinute
self.initialZAngularVelocityRadiansPerMinute = radiansPerMinute
self.needsCorrection = needsCorrection
}
init(zAngularVelocityDegreesPerMinute: Double, needsCorrection: Int) {
self.init(zAngularVelocityDegreesPerMinute: zAngularVelocityDegreesPerMinute,
needsCorrection: (needsCorrection > 0))
}
}
struct CombustionChamberStatus {
var temperatureKelvin: Double
var pressureKiloPascals: Double
init(temperatureKelvin: Double, pressureKiloPascals: Double) {
print("Phase 1 init")
self.temperatureKelvin = temperatureKelvin
self.pressureKiloPascals = pressureKiloPascals
print("CombustionChamberStatus fully initialized")
print("Phase 2 init")
}
init(temperatureCelsius: Double, pressureAtmospheric: Double) {
print("Phase 1 delegating init")
let temperatureKelvin = temperatureCelsius + 273.15
let pressureKiloPascals = pressureAtmospheric * 101.325
self.init(temperatureKelvin: temperatureKelvin, pressureKiloPascals: pressureKiloPascals)
print("Phase 2 delegating init")
}
}
struct TankStatus {
var currentVolume: Double
var currentLiquidType: String?
init?(currentVolume: Double, currentLiquidType: String?) {
if currentVolume < 0 {
return nil
}
if currentVolume > 0 && currentLiquidType == nil {
return nil
}
self.currentVolume = currentVolume
self.currentLiquidType = currentLiquidType
}
}
enum InvalidAstronautDataError: Error {
case EmptyName
case InvalidAge
}
struct Astronaut {
let name: String
let age: Int
init(name: String, age: Int) throws {
if name.isEmpty {
throw InvalidAstronautDataError.EmptyName
}
if age < 18 || age > 70 {
throw InvalidAstronautDataError.InvalidAge
}
self.name = name
self.age = age
}
}
let athena9Heavy = RocketConfiguration()
let stageOneConfiguration = RocketStageConfiguration(propellantMass: 119.1, liquidOxygenMass: 276.0)
let currentWeather = Weather()
currentWeather.temperatureCelsius
currentWeather.windSpeedKilometersPerHour
let guidanceStatus = GuidanceSensorStatus(zAngularVelocityDegreesPerMinute: 2.2)
guidanceStatus.currentZAngularVelocityRadiansPerMinute // 0.038
guidanceStatus.needsCorrection // false
CombustionChamberStatus(temperatureCelsius: 32, pressureAtmospheric: 0.96)
if let tankStatus = TankStatus(currentVolume: -10.0, currentLiquidType: nil) {
print("Nice, tank status created.") // Printed!
} else {
print("Oh no, an initialization failure occurred.")
}
let johnny = try? Astronaut(name: "Johnny Cosmoseed", age: 17)
|
mit
|
082f59b0b77d4c34eb48194c277e74a6
| 30.219697 | 100 | 0.716262 | 4.401709 | false | false | false | false |
MisterZhouZhou/swift-demo
|
swift-demo/swift-demo/classes/details/动画效果/AnimationListViewController.swift
|
1
|
2486
|
//
// AnimationListViewController.swift
// swift-demo
//
// Created by rayootech on 16/4/12.
// Copyright © 2016年 rayootech. All rights reserved.
//
import UIKit
class AnimationListViewController: UIViewController ,UITableViewDelegate,UITableViewDataSource{
var listArray :NSArray = NSArray()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "动画列表"
let tableView = UITableView(frame: UIScreen.mainScreen().applicationFrame)
tableView.delegate = self
tableView.dataSource = self
tableView.tableFooterView = UIView()
self.view.addSubview(tableView)
listArray = ["画基本图形","CAShapeLayer&UIBezierPath"]
}
/**
UITableViewDelegate
*/
func numberOfSectionsInTableView(tableView: UITableView) -> Int{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
return listArray.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell{
let ID = "cell"
var cell = tableView.dequeueReusableCellWithIdentifier(ID)
if cell == nil{
cell = UITableViewCell(style: .Default, reuseIdentifier: ID)
}
cell?.accessoryType = .DisclosureIndicator
cell?.textLabel?.text = "\(listArray[indexPath.row])"
cell?.selectionStyle = .None
return cell!
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
switch indexPath.row{
case 0:
self.navigationController?.pushViewController(DrawCircleViewController(), animated: true)
break
case 1:
self.navigationController?.pushViewController(ShapeAndBezierPathViewController(), animated: true)
break
default:
break
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
/*
// MARK: - Navigation
// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
// Get the new view controller using segue.destinationViewController.
// Pass the selected object to the new view controller.
}
*/
}
|
apache-2.0
|
fd6a6d2c2cc481d9ebc6cda7b4e1d285
| 31.012987 | 109 | 0.655984 | 5.417582 | false | false | false | false |
zpz1237/NirZhihuNews
|
zhihuNews/AppDelegate.swift
|
1
|
6222
|
//
// AppDelegate.swift
// zhihuNews
//
// Created by Nirvana on 8/13/15.
// Copyright © 2015 NSNirvana. All rights reserved.
//
import UIKit
import CoreData
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
var topItems: [(image: String, id: String, label: String)] = []
var detailItems: [(images: String, id: String, label: String)] = []
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Override point for customization after application launch.
return true
}
func applicationWillResignActive(application: UIApplication) {
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
func applicationDidEnterBackground(application: UIApplication) {
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
func applicationWillEnterForeground(application: UIApplication) {
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
func applicationDidBecomeActive(application: UIApplication) {
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}
func applicationWillTerminate(application: UIApplication) {
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
// Saves changes in the application's managed object context before the application terminates.
self.saveContext()
}
// MARK: - Core Data stack
lazy var applicationDocumentsDirectory: NSURL = {
// The directory the application uses to store the Core Data store file. This code uses a directory named "Azure.zhihuNews" in the application's documents Application Support directory.
let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
return urls[urls.count-1]
}()
lazy var managedObjectModel: NSManagedObjectModel = {
// The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
let modelURL = NSBundle.mainBundle().URLForResource("zhihuNews", withExtension: "momd")!
return NSManagedObjectModel(contentsOfURL: modelURL)!
}()
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
// The persistent store coordinator for the application. This implementation creates and returns a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
var failureReason = "There was an error creating or loading the application's saved data."
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
return coordinator
}()
lazy var managedObjectContext: NSManagedObjectContext = {
// Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()
// MARK: - Core Data Saving support
func saveContext () {
if managedObjectContext.hasChanges {
do {
try managedObjectContext.save()
} catch {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
let nserror = error as NSError
NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
}
|
mit
|
ff379622e02179d73af68e7de3f55fc7
| 54.053097 | 291 | 0.717087 | 5.797763 | false | false | false | false |
pennlabs/penn-mobile-ios
|
PennMobile/GSR-Booking/Model/GSRGroup.swift
|
1
|
7103
|
//
// GSRGroup.swift
// PennMobile
//
// Created by Josh Doman on 4/6/19.
// Copyright © 2019 PennLabs. All rights reserved.
//
import Foundation
struct GSRGroup: Decodable, Comparable {
let id: Int
let name: String
let color: UIColor
let owner: String?
let members: [GSRGroupMember]?
var userSettings: GSRGroupIndividualSettings?
// not used right now
var reservations: [String]? // array of reservationID's
var groupSettings: GSRGroupAccessSettings?
static let groupColors: [String: UIColor] = [
"Labs Blue": UIColor.baseLabsBlue,
"College Green": UIColor.baseGreen,
"Locust Yellow": UIColor.baseYellow,
"Cheeto Orange": UIColor.baseOrange,
"Gritty Orange": UIColor.baseOrange,
"Red-ing Terminal": UIColor.baseRed,
"Baltimore Blue": UIColor.baseDarkBlue,
"Pottruck Purple": UIColor.basePurple
]
static func parseColor(color: String) -> UIColor? {
return GSRGroup.groupColors[color]
}
enum CodingKeys: String, CodingKey {
case id, name, color, owner
case members = "memberships"
case pennkeyAllow = "pennkey_allow"
case notifications
}
fileprivate mutating func parseIndividualSettings(for pennkey: String) {
// initializes the user settings based on the member data
// call this method after initially decoding json data, and BEFORE
// displaying groups in ManageGroupVC
guard let members = members else { return }
for member in members where member.pennKey == pennkey {
let pennKeyActive = member.pennKeyActive
let notificationsOn = member.notificationsOn
let pennKeyActiveSetting = GSRGroupIndividualSetting(type: .pennkeyActive, isEnabled: pennKeyActive)
let notificationsOnSetting = GSRGroupIndividualSetting(type: .notificationsOn, isEnabled: notificationsOn)
userSettings = GSRGroupIndividualSettings(pennKeyActive: pennKeyActiveSetting, notificationsOn: notificationsOnSetting)
}
}
public init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
let id: Int = try keyedContainer.decode(Int.self, forKey: .id)
let name: String = try keyedContainer.decode(String.self, forKey: .name)
let colorString: String = try keyedContainer.decode(String.self, forKey: .color)
let owner: String? = try keyedContainer.decodeIfPresent(String.self, forKey: .owner)
self.id = id
self.name = name
self.color = GSRGroup.parseColor(color: colorString) ?? UIColor.baseBlue
self.owner = owner
if let members: [GSRGroupMember] = try keyedContainer.decodeIfPresent([GSRGroupMember].self, forKey: .members) {
self.members = members
guard let pennkey = Account.getAccount()?.username else { // this feels wrong :(
print("user not signed in")
return
}
parseIndividualSettings(for: pennkey)
} else {
self.members = nil
let pennKeyActive = try keyedContainer.decode(Bool.self, forKey: .pennkeyAllow)
let notifications = try keyedContainer.decode(Bool.self, forKey: .notifications)
self.userSettings = GSRGroupIndividualSettings(pennKeyActive: GSRGroupIndividualSetting(type: .pennkeyActive, isEnabled: pennKeyActive), notificationsOn: GSRGroupIndividualSetting(type: .notificationsOn, isEnabled: notifications))
}
}
static func < (lhs: GSRGroup, rhs: GSRGroup) -> Bool {
return lhs.name.lowercased() < rhs.name.lowercased()
}
static func == (lhs: GSRGroup, rhs: GSRGroup) -> Bool {
return lhs.id == rhs.id
}
}
typealias GSRGroups = [GSRGroup]
enum GSRGroupIndividualSettingType: Int, Codable {
case pennkeyActive
case notificationsOn
}
struct GSRGroupIndividualSetting: Codable {
var title: String {
switch type {
case .pennkeyActive:
return "PennKey Permission"
case .notificationsOn:
return "Notifications"
}
}
var type: GSRGroupIndividualSettingType
var descr: String {
switch type {
case .notificationsOn:
return "You’ll receive a notification any time a room is booked by this group."
case .pennkeyActive:
return "Anyone in this group can book a study room block using your PennKey."
}
}
var isEnabled: Bool
}
struct GSRGroupIndividualSettings: Codable { // specific to a user within a group
var pennKeyActive: GSRGroupIndividualSetting
var notificationsOn: GSRGroupIndividualSetting
}
struct GSRGroupAccessSettings: Codable { // general to all users within a group
var booking: GSRGroupAccessPermissions
var invitation: GSRGroupAccessPermissions
}
enum GSRGroupAccessPermissions: String, Codable { // who has access
case everyone
case owner
}
struct GSRGroupMember: Codable {
let pennKey: String
let first: String
let last: String
let pennKeyActive: Bool
let notificationsOn: Bool
let isAdmin: Bool
enum CodingKeys: String, CodingKey {
case pennKey = "user"
case first, last // this doesn't get used
case pennKeyActive = "pennkey_allow"
case notificationsOn = "notifications"
case isAdmin = "type"
}
public init(from decoder: Decoder) throws {
let keyedContainer = try decoder.container(keyedBy: CodingKeys.self)
let memberType = try keyedContainer.decode(String.self, forKey: .isAdmin)
let pennKeyActive = try keyedContainer.decode(Bool.self, forKey: .pennKeyActive)
let notificationsOn = try keyedContainer.decode(Bool.self, forKey: .notificationsOn)
self.isAdmin = (memberType == "A")
self.pennKeyActive = pennKeyActive
self.notificationsOn = notificationsOn
let user = try keyedContainer.decode(GSRGroupMemberUser.self, forKey: .pennKey)
self.pennKey = user.pennKey
self.first = user.first
self.last = user.last
}
}
struct GSRGroupMemberUser: Codable {
let pennKey: String
let first: String
let last: String
enum CodingKeys: String, CodingKey {
case pennKey = "username"
case first = "first_name"
case last = "last_name"
}
}
struct GSRGroupInvite: Codable {
let user: GSRInviteUser
let group: String
let type: String
let pennkeyAllow: Bool
let notifications: Bool
let id: Int
let color: String
enum CodingKeys: String, CodingKey {
case user, type, group
case pennkeyAllow = "pennkey_allow"
case notifications, id
case color
}
}
struct GSRInviteUser: Codable {
let pennkey: String
let firstName: String
let lastName: String
enum CodingKeys: String, CodingKey {
case pennkey = "username"
case firstName = "first_name"
case lastName = "last_name"
}
}
typealias GSRGroupInvites = [GSRGroupInvite]
|
mit
|
cfb1fe16fab98a35c850c9914b825422
| 32.649289 | 242 | 0.668873 | 4.271961 | false | false | false | false |
MengQuietly/MQDouYuTV
|
MQDouYuTV/MQDouYuTV/AppDelegate.swift
|
1
|
3649
|
//
// AppDelegate.swift
// MQDouYuTV
//
// Created by mengmeng on 16/9/21.
// Copyright © 2016年 mengQuietly. All rights reserved.
//
import UIKit
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UITabBar.appearance().tintColor = UIColor.orange
let userDefault = UserDefaults.standard
if userDefault.bool(forKey: "everLaunched") == false {
// 第一次启动
userDefault.set(true, forKey: "everLaunched")
userDefault.set(true, forKey: "firstLaunch")
}else{
userDefault.set(false, forKey: "firstLaunch")
}
userDefault.synchronize()
return true
}
// // MARK: 获取首页 子标题
// func getHomeSubTitle(){
// let homeSubTitleUrl = HOST_URL.appending(HOME_GET_SUBTITLE_LIST)
// MQNetworkingTool.sendRequest(url: homeSubTitleUrl, succeed: { (responseObject, isBadNet) in
// // MQLog("responseObject=\(responseObject),isBadNet=\(isBadNet)")
// guard let resultDict = responseObject as? [String:NSObject] else {return}
// guard let dataArray = resultDict["data"] as? [[String:NSObject]] else {return}
// let userDefault = UserDefaults.standard
// for dict in dataArray {
// let subTitleModel = MQHomeSubTitleModel(dict: dict)
// userDefault.set(subTitleModel.identification, forKey: subTitleModel.title)
// }
//
// userDefault.set(true, forKey: "firstLaunch")
// print("path = \(NSHomeDirectory())")
// userDefault.synchronize()
//
// }) { (error, isBadNet) in
// MQLog("error=\(error),isBadNet=\(isBadNet)")
// }
// }
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:.
}
}
|
mit
|
badf7bd800d65370cf800d4b0234bc67
| 44.848101 | 285 | 0.675041 | 5.101408 | false | false | false | false |
ABTSoftware/SciChartiOSTutorial
|
v2.x/Showcase/SciChartShowcase/SciChartShowcaseDemo/AudioAnalyzerExample/Controller/SpectrogramSurfaceController.swift
|
1
|
4138
|
//
// SpectrogramSurfaceController.swift
// SciChartShowcaseDemo
//
// Created by Yaroslav Pelyukh on 2/27/17.
// Copyright © 2017 SciChart Ltd. All rights reserved.
//
import Foundation
import SciChart
import Accelerate
struct HeatmapSettings {
static let xSize: Int32 = 250
static let ySize: Int32 = 1024
}
class SpectogramSurfaceController: BaseChartSurfaceController {
let audioWaveformRenderableSeries: SCIFastUniformHeatmapRenderableSeries = SCIFastUniformHeatmapRenderableSeries()
var audioDataSeries: SCIUniformHeatmapDataSeries = SCIUniformHeatmapDataSeries(typeX: .int32,
y: .int32,
z: .float,
sizeX: 1024,
y: 250,
startX: SCIGeneric(0), stepX: SCIGeneric(1),
startY: SCIGeneric(0), stepY: SCIGeneric(1))
var updateDataSeries: samplesToEngineFloat!
var dataArrays = UnsafeMutablePointer<Float>.allocate(capacity: Int(HeatmapSettings.xSize*HeatmapSettings.ySize))
var isNewData = false
public func updateData(displayLink: CADisplayLink) {
if isNewData {
isNewData = false;
audioDataSeries.updateZValues(SCIGeneric(dataArrays), size: HeatmapSettings.xSize*HeatmapSettings.ySize)
chartSurface.invalidateElement()
}
}
override init(_ view: SCIChartSurface) {
super.init(view)
chartSurface.bottomAxisAreaSize = 0.0
chartSurface.topAxisAreaSize = 0.0
chartSurface.leftAxisAreaSize = 0.0
chartSurface.rightAxisAreaSize = 0.0
dataArrays.initialize(to: Float(0), count: Int(HeatmapSettings.ySize*HeatmapSettings.xSize))
updateDataSeries = {[unowned self] dataSeries in
if let pointerInt32 = dataSeries {
memmove(self.dataArrays,
self.dataArrays.advanced(by: Int(HeatmapSettings.ySize)),
Int((HeatmapSettings.xSize-1)*HeatmapSettings.ySize)*MemoryLayout<Float>.size)
memcpy(self.dataArrays.advanced(by: Int(HeatmapSettings.ySize*(HeatmapSettings.xSize-1))),
pointerInt32, Int(HeatmapSettings.ySize)*MemoryLayout<Float>.size)
self.isNewData = true
}
}
audioWaveformRenderableSeries.dataSeries = audioDataSeries
audioWaveformRenderableSeries.style.minimum = SCIGeneric(Float(0.0))
audioWaveformRenderableSeries.style.maximum = SCIGeneric(Float(60.0))
var grad: Array<Float> = [0.0, 0.3, 0.5, 0.7, 0.9, 1.0]
var colors: Array<UInt32> = [0xFF000000, 0xFF520306, 0xFF8F2325, 0xFF68E615, 0xFF6FB9CC, 0xFF1128e6]
audioWaveformRenderableSeries.style.colorMap = SCITextureOpenGL.init(gradientCoords: &grad, colors: &colors, count: 6)
chartSurface.renderableSeries.add(audioWaveformRenderableSeries)
let axisStyle = SCIAxisStyle()
axisStyle.drawLabels = false
axisStyle.drawMajorBands = false
axisStyle.drawMinorTicks = false
axisStyle.drawMajorTicks = false
axisStyle.drawMajorGridLines = false
axisStyle.drawMinorGridLines = false
let xAxis = SCINumericAxis()
xAxis.style = axisStyle
xAxis.axisAlignment = .right
xAxis.autoRange = .always
let yAxis = SCINumericAxis()
yAxis.style = axisStyle
yAxis.autoRange = .always
yAxis.flipCoordinates = true
yAxis.axisAlignment = .bottom
chartSurface.yAxes.add(yAxis)
chartSurface.xAxes.add(xAxis)
chartSurface.invalidateElement()
}
}
|
mit
|
557b9713b3d34ef3e58041c1bdca9ecb
| 40.787879 | 127 | 0.582789 | 4.919144 | false | false | false | false |
chernyog/CYWeibo
|
CYWeibo/CYWeibo/CYWeibo/Classes/UI/Compose/Emoticons.swift
|
1
|
5404
|
//
// Emoticons.swift
// CYWeibo
//
// Created by 陈勇 on 15/3/13.
// Copyright (c) 2015年 zhssit. All rights reserved.
//
import Foundation
/// 表情集合类 存储所有的表情
class EmoticonList {
private static let instance = EmoticonList()
/// 单例
class var sharedInstance: EmoticonList{
return instance
}
var emoticons: [Emoticon]
init(){
emoticons = [Emoticon]()
let sections = EmoticonsSection.loadEmoticons()
for section in sections
{
// println("===========> name=\(section.name)")
if !(section.name == "Emoji")
{
emoticons += section.emoticons
}
}
}
}
class EmoticonsSection {
/// 平时定义对象属性的时候,都是使用可选类型 ?
/// 原因:没有构造函数给对象属性设置初始数值
/// 分组名称
var name: String
/// 类型
var type: String
/// 路径
var path: String
/// 表情符号的数组(每一个 section中应该包含21个表情符号,界面处理是最方便的)
/// 其中21个表情符号中,最后一个删除(就不能使用plist中的数据)
var emoticons: [Emoticon]
/// 使用字典实例化对象
/// 构造函数,能够给对象直接设置初始数值,凡事设置过的属性,都可以是必选项
/// 在构造函数中,不需要 super,直接给属性分配空间&初始化
init(dict: NSDictionary) {
name = dict["emoticon_group_name"] as! String
type = dict["emoticon_group_type"] as! String
path = dict["emoticon_group_path"] as! String
emoticons = [Emoticon]()
}
class func loadEmoticons() -> [EmoticonsSection]
{
let path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/emoticons.plist")
var array = NSArray(contentsOfFile: path)!
// println("\(array)")
// 按照type字段对数组进行排序
array = array.sortedArrayUsingComparator({ (dict1, dict2) -> NSComparisonResult in
let type1 = dict1["emoticon_group_type"] as! String
let type2 = dict2["emoticon_group_type"] as! String
return type1.compare(type2)
})
var result = [EmoticonsSection]()
for dict in array as! [NSDictionary]
{
result += loadEmoticons(dict)
}
return result
}
private class func loadEmoticons(dict: NSDictionary) -> [EmoticonsSection]
{
let emoticon_group_path = dict["emoticon_group_path"] as! String
// 加载不同分组下的表情
let group_path = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/\(emoticon_group_path)/info.plist")
let infoDict = NSDictionary(contentsOfFile: group_path)!
let array = infoDict["emoticon_group_emoticons"] as! NSArray
// println("\(array)")
return loadEmoticons(dict, array: array)
}
private class func loadEmoticons(dict: NSDictionary, array: NSArray) -> [EmoticonsSection]
{
var result = [EmoticonsSection]()
// 每个分组20个常规表情 1个“删除”表情
let baseCount = 20
// 每个类别下表情个数
let objCount = ceil(CGFloat(array.count) / CGFloat(baseCount)) // 天花板函数 向上取整
for i in 0..<Int(objCount)
{
var emotionSection = EmoticonsSection(dict: dict)
// 内部表情
for j in 0..<20
{
let index = j + i * baseCount
var dict: NSDictionary? = nil
if index < array.count
{
dict = array[index] as? NSDictionary
}
let em = Emoticon(dict: dict, path: emotionSection.path)
em.isDeleteButton = false
emotionSection.emoticons.append(em)
}
// 删除按钮
let em = Emoticon(dict: nil, path: nil)
em.isDeleteButton = true
emotionSection.emoticons.append(em)
result.append(emotionSection)
}
return result
}
}
/// 表情符号类
class Emoticon {
/// emoji 的16进制字符串
var code: String?
/// emoji 字符串
var emoji: String?
/// 类型
var type: String?
/// 表情符号的文本 - 发送给服务器的文本
var chs: String?
/// 表情符号的图片 - 本地做图文混排使用的图片
var png: String?
/// 图像的完整路径
var imagePath: String?
/// 标记 是否是删除按钮
var isDeleteButton = false
init(dict: NSDictionary?, path: String?) {
code = dict?["code"] as? String
type = dict?["type"] as? String
chs = dict?["chs"] as? String
png = dict?["png"] as? String
if path != nil && png != nil {
imagePath = NSBundle.mainBundle().bundlePath.stringByAppendingPathComponent("Emoticons/\(path!)/\(png!)")
}
// 计算 emoji
if code != nil {
let scanner = NSScanner(string: code!)
// 提示:如果要传递指针,不能使用 let,var 才能修改数值
var value: UInt32 = 0
scanner.scanHexInt(&value)
emoji = "\(Character(UnicodeScalar(value)))"
}
}
}
|
mit
|
5996201dd1ed33a6e3fe8845de8e493f
| 28.347826 | 135 | 0.567316 | 4.11857 | false | false | false | false |
developerY/Swift2_Playgrounds
|
Swift2LangRef.playground/Pages/Closures.xcplaygroundpage/Contents.swift
|
1
|
8353
|
//: [Previous](@previous)
//: ------------------------------------------------------------------------------------------------
//: Things to know:
//:
//: * Closures are blocks of code.
//:
//: * The can be passed as parameters to functions much like Function Types. In fact, functions
//: are a special case of closures.
//:
//: * Closures of all types (including nested functions) employ a method of capturing the surrounding
//: context in which is is defined, allowing it to access constants and variables from that
//: context.
//: ------------------------------------------------------------------------------------------------
//: Closures can use constant, variable, inout, variadics, tuples for their parameters. They can
//: return any value, including Tuples. They cannot, however, have default parameters.
//:
//: The basic syntax is:
//:
//: { (parameters) -> return_type in
//: ... statements ...
//: }
//:
//: Here's an example of a simple String comparison closure that might be used for sorting Strings:
//:
//: { (s1: String, s2: String) -> Bool in
//: return s1 < s2
//: }
//:
//: Here's an example using Swift's 'sorted' member function. It's important to note that this
//: function receives a single closure.
//:
//: These can be a little tricky to read if you're not used to them. To understand the syntax, pay
//: special attention to the curly braces that encapsulate the closure and the parenthesis just
//: outside of those curly braces:
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
var reversed = [String]()
reversed = names.sort({
(s1: String, s2: String) -> Bool in
return s1 > s2
})
//: ------------------------------------------------------------------------------------------------
//: Inferring Type from Context
//:
//: Like functions, closures have a type.
//:
//: If the type is known (as is always the case when passing a closure as a parameter to a function)
//: then the return type of the closure can be inferred, allowing us to simplify the syntax of our
//: call to sort.
//:
//: The following call is identical to the one above with the exception that "-> Bool" was removed:
reversed = names.sort({
(s1: String, s2: String) in
return s1 > s2
})
//: Just as the return type can be inferred, so can the parameter types. This allows us to simplify
//: the syntax a bit further by removing the type annotations from the closure's parameters.
//:
//: The following call is identical to the one above with the exception that the parameter type
//: annotations (": String") have been removed:
reversed = names.sort({
(s1, s2) in
return s1 > s2
})
//: Since all types can be inferred and we're not using any type annotation on the parameters,
//: we can simplify a bit further by removing the paranthesis around the parameters. We'll also put
//: it all on a single line, since it's a bit more clear now:
reversed = names.sort({ s1, s2 in return s1 > s2 })
//: If the closuere has only a single expression, then the return statement is also inferred. When
//: this is the case, the closure returns the value of the single expression:
reversed = names.sort({ s1, s2 in s1 > s2 })
//: We're not done simplifying yet. It turns out we can get rid of the parameters as well. If we
//: remove the parameters, we can still access them because Swift provides shorthand names to
//: parameters passed to inline closures. To access the first parameter, use $0. The second
//: parameter would be $1 and so on.
//:
//: Here's what that would might like (this will not compile - yet):
//:
//: reversed = names.sorted({ s1, s2 in $0 > $1 })
//:
//: This won't compile because you're not allowed to use shorthand names if you specify the
//: parameter list. Therefore, we need to remove those in order to get it to compile. This makes
//: for a very short inline closure:
reversed = names.sort({ $0 > $1 })
//: Interestingly enough, the operator < for String types is defined as:
//:
//: (String, String) -> Bool
//:
//: Notice how this is the same as the closure's type for the sorted() routine? Wouldn't it be
//: nice if we could just pass in this operator? It turns out that for inline closures, Swift allows
//: exactly this.
//:
//: Here's what that looks like:
reversed = names.sort(>)
//: If you want to just sort a mutable copy of an array (in place) you can use the sort() method
var mutableCopyOfNames = names
mutableCopyOfNames.sort(>)
mutableCopyOfNames
//: ------------------------------------------------------------------------------------------------
//: Trailing Closures
//:
//: Trailing Closures refer to closures that are the last parameter to a function. This special-case
//: syntax allows a few other syntactic simplifications. In essence, you can move trailing closures
//: just outside of the parameter list. Swift's sorted() member function uses a trailing closure for
//: just this reason.
//:
//: Let's go back to our original call to sort with a fully-formed closure and move the closure
//: outside of the parameter list. This resembles a function definition, but it's a function call.
reversed = names.sort {
(s1: String, s2: String) -> Bool in
return s1 > s2
}
//: Note that the opening brace for the closure must be on the same line as the function call's
//: ending paranthesis. This is the same functinon call with the starting brace for the closure
//: moved to the next line. This will not compile:
//:
//: reversed = sort(names)
//: {
//: (s1: String, s2: String) -> Bool in
//: return s1 > s2
//: }
//: Let's jump back to our simplified closure ({$0 > $1}) and apply the trailing closure principle:
reversed = names.sort {$0 > $1}
//: Another simplification: if a function receives just one closure as the only parameter, you can
//: remove the () from the function call. First, we'll need a function that receives just one
//: parameter, a closure:
func returnValue(f: () -> Int) -> Int
{
//: Simply return the value that the closure 'f' returns
return f()
}
//: Now let's call the function with the parenthesis removed and a trailing closure:
returnValue {return 6}
//: And if we apply the simplification described earlier that implies the return statement for
//: single-expresssion closures, it simplifies to this oddly-looking line of code:
returnValue {6}
//: ------------------------------------------------------------------------------------------------
//: Capturing Values
//:
//: The idea of capturing is to allow a closure to access the variables and constants in their
//: surrounding context.
//:
//: For example, a nested function can access contstans and variables from the function in which
//: it is defined. If this nested function is returned, each time it is called, it will work within
//: that "captured" context.
//:
//: Here's an example that should help clear this up:
func makeIncrementor(forIncrement amount: Int) -> () -> Int
{
var runningTotal = 0
//: runningTotal and amount are 'captured' for the nested function incrementor()
func incrementor() -> Int
{
runningTotal += amount
return runningTotal
}
//: We return the nested function, which has captured it's environment
return incrementor
}
//: Let's get a copy of the incrementor:
var incrementBy10 = makeIncrementor(forIncrement: 10)
//: Whenever we call this function, it will return a value incremented by 10:
incrementBy10() //: returns 10
incrementBy10() //: returns 20
//: We can get another copy of incrementor that works on increments of 3.
var incrementBy3 = makeIncrementor(forIncrement: 3)
incrementBy3() //: returns 3
incrementBy3() //: returns 6
//: 'incrementBy10' and 'incrementBy3' each has its own captured context, so they work independently
//: of each other.
incrementBy10() //: returns 30
//: Closures are reference types, which allows us to assign them to a variable. When this happens,
//: the captured context comes along for the ride.
var copyIncrementBy10 = incrementBy10
copyIncrementBy10() //: returns 40
//: If we request a new incremntor that increments by 10, it will have a separate and unique captured
//: context:
var anotherIncrementBy10 = makeIncrementor(forIncrement: 10)
anotherIncrementBy10() //: returns 10
//: Our first incrementor is still using its own context:
incrementBy10() //: returns 50
//: [Next](@next)
|
mit
|
269b1bcf1b50a835ab9bf78935cf683c
| 39.158654 | 101 | 0.667066 | 4.261735 | false | false | false | false |
cpuu/OTT
|
OTT/Configure/ConfigureScanModeViewController.swift
|
1
|
1676
|
//
// ConfigureScanModeViewController.swift
// BlueCap
//
// Created by Troy Stribling on 8/29/14.
// Copyright (c) 2014 Troy Stribling. The MIT License (MIT).
//
import UIKit
import BlueCapKit
class ConfigureScanModeViewController: UITableViewController {
let scanModes = ["Promiscuous", "Service"]
struct MainStoryboard {
static let configureScanModeCell = "ConfigureScanModeCell"
}
// UITableViewDataSource
override func numberOfSectionsInTableView(tableView: UITableView) -> Int {
return 1
}
override func tableView(_: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.scanModes.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier(MainStoryboard.configureScanModeCell, forIndexPath: indexPath) as UITableViewCell
let scanModeString = scanModes[indexPath.row]
cell.textLabel?.text = scanModeString
if let scanMode = ServiceScanMode(scanModeString) where scanMode == ConfigStore.getScanMode() {
cell.accessoryType = UITableViewCellAccessoryType.Checkmark
} else {
cell.accessoryType = UITableViewCellAccessoryType.None
}
return cell
}
// UITableViewDelegate
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
let scanMode = self.scanModes[indexPath.row]
ConfigStore.setScanMode(ServiceScanMode(scanMode)!)
self.navigationController?.popViewControllerAnimated(true)
}
}
|
mit
|
0948a0ff9512ee74d5c55031055d9e74
| 33.9375 | 144 | 0.715394 | 5.27044 | false | true | false | false |
apple/swift-syntax
|
EditorExtension/SwiftRefactorExtension/CommandDiscovery.swift
|
1
|
5163
|
//===----------------------------------------------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2022 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
import Darwin
import MachO
import Foundation
import SwiftRefactor
extension SourceEditorExtension {
static func forEachRefactoringProvider(_ action: (any RefactoringProvider.Type) -> Void) {
guard let header = _dyld_get_image_header(0) else {
return
}
var size: UInt = 0
let section = header.withMemoryRebound(to: mach_header_64.self, capacity: 1) { pointer in
getsectiondata(pointer, "__TEXT", "__swift5_proto", &size)
}
guard let section = section else {
return
}
let rawSection = UnsafeRawPointer(section)
for start in stride(from: rawSection, to: rawSection + Int(size), by: MemoryLayout<Int32>.stride) {
let address = start.load(as: RelativeDirectPointer<ConformanceDescriptor>.self).address(from: start)
let conformance = Conformance(raw: address)
guard let context = conformance.context, context.moduleDescriptor.isSwiftRefactorModule else {
continue
}
guard let typeMetadata = context.metadata(), let provider = typeMetadata as? any RefactoringProvider.Type else {
continue
}
action(provider)
}
}
}
struct Conformance {
enum Kind: UInt16 {
case direct = 0x0
case indirect = 0x1
}
var raw: UnsafeRawPointer
var `protocol`: Context {
let maybeProtocol = RelativeIndirectablePointer<ContextDescriptor>(offset: self.raw.load(as: ConformanceDescriptor.self).protocol)
return Context(raw: maybeProtocol.address(from: self.raw))
}
var context: Context? {
let start = self.raw + MemoryLayout<Int32>.size
let offset = start.load(as: Int32.self)
let addr = start + Int(offset)
let kind = UInt16(self.raw.load(as: ConformanceDescriptor.self).flags & (0x7 << 3)) >> 3
switch Conformance.Kind(rawValue: kind) {
case .direct:
return Context(raw: addr)
case .indirect:
return addr.load(as: Context.self)
case nil:
return nil
}
}
}
struct Context: Hashable {
struct Flags: OptionSet {
var rawValue: UInt32
var kind: Context.Kind? {
return Context.Kind(rawValue: UInt8(self.rawValue & 0x1F))
}
}
enum Kind: UInt8 {
case `class` = 0x11
case `struct` = 0x12
case `enum` = 0x13
}
var raw: UnsafeRawPointer
var parent: Context? {
let parent = RelativeIndirectablePointer<ContextDescriptor>(offset: self.raw.load(as: ContextDescriptor.self).parent)
guard parent.offset != 0 else {
return nil
}
let start = self.raw + MemoryLayout<Int32>.size
return Context(raw: parent.address(from: start))
}
var moduleDescriptor: ModuleContext {
var result = self
while let parent = result.parent {
result = parent
}
return ModuleContext(raw: result.raw)
}
func metadata() -> Any.Type? {
guard Context.Flags(rawValue: self.raw.load(as: ContextDescriptor.self).flags).kind != nil else {
return nil
}
let typeDescriptor = self.raw.load(as: TypeContextDescriptor.self)
let start = self.raw + MemoryLayout<TypeContextDescriptor>.offset(of: \.accessor)!
let accessor = RelativeDirectPointer<Void>(offset: typeDescriptor.accessor)
let access = MetadataAccessor(raw: accessor.address(from: start))
let fn = unsafeBitCast(access.raw, to: (@convention(thin) (Int) -> MetadataResponse).self)
return fn(0).type
}
}
struct MetadataAccessor {
var raw: UnsafeRawPointer
}
struct MetadataResponse {
let type: Any.Type
let state: Int
}
struct ModuleContext {
var raw: UnsafeRawPointer
var name: String {
let typeDescriptor = self.raw.load(as: ModuleContextDescriptor.self)
let start = self.raw + MemoryLayout<ModuleContextDescriptor>.offset(of: \.name)!
let name = RelativeDirectPointer<CChar>(offset: typeDescriptor.name)
return name
.address(from: start)
.withMemoryRebound(to: CChar.self, capacity: 1) { pointer in
return String(cString: pointer)
}
}
}
extension ModuleContext {
var isSwiftRefactorModule: Bool {
return self.name == "SwiftRefactor"
}
}
struct RelativeDirectPointer<Pointee> {
var offset: Int32
func address(from pointer: UnsafeRawPointer) -> UnsafeRawPointer {
return pointer + UnsafeRawPointer.Stride(self.offset)
}
}
struct RelativeIndirectablePointer<Pointee> {
var offset: Int32
func address(from pointer: UnsafeRawPointer) -> UnsafeRawPointer {
let dest = pointer + Int(self.offset & ~1)
// If the low bit is set, then this is an indirect address. Otherwise,
// it's direct.
if Int(offset) & 1 == 1 {
return dest.load(as: UnsafeRawPointer.self)
} else {
return dest
}
}
}
|
apache-2.0
|
b53338a67407fd58bd2297f5e2d98c23
| 27.059783 | 134 | 0.666473 | 4.05259 | false | false | false | false |
blockchain/My-Wallet-V3-iOS
|
Modules/FeatureAuthentication/Sources/FeatureAuthenticationDomain/WalletAuthentication/Services/WalletPairing/AutoWalletPairingService.swift
|
1
|
4528
|
// Copyright © Blockchain Luxembourg S.A. All rights reserved.
import Combine
import DIKit
import Errors
import ToolKit
import WalletPayloadKit
public enum AutoWalletPairingServiceError: Error {
case networkError(NetworkError)
case walletCryptoServiceError(Error)
case parsingError(SharedKeyParsingServiceError)
case walletPayloadServiceError(WalletPayloadServiceError)
}
/// A service API for auto pairing
public protocol AutoWalletPairingServiceAPI: AnyObject {
/// Maps a QR pairing code of a wallet into its password, retrieve and cache the wallet data.
/// Finally returns the password of the wallet
/// 1. Receives a pairing code (guid, encrypted shared-key)
/// 2. Sends the wallet `guid` -> receives a passphrase that can be used to decrypt the shared key.
/// 3. Decrypt the shared key
/// 4. Parse the shared key and the password
/// 5. Request the wallet payload using the wallet GUID and the shared key
/// 6. Returns the password.
/// - Parameter pairingData: A pairing code comprises GUID and an encrypted shared key.
/// - Returns: The wallet password - decrypted and ready for usage.
func pair(using pairingData: PairingData) -> AnyPublisher<String, AutoWalletPairingServiceError>
/// Gets encryptionPhrase
func encryptionPhrase(using guid: String) -> AnyPublisher<String, AutoWalletPairingServiceError>
}
/// A service that is responsible for the auto pairing process
public final class AutoWalletPairingService: AutoWalletPairingServiceAPI {
// MARK: - Type
public typealias WalletRepositoryAPI = GuidRepositoryAPI &
SessionTokenRepositoryAPI &
SharedKeyRepositoryAPI &
LanguageRepositoryAPI &
SyncPubKeysRepositoryAPI &
AuthenticatorRepositoryAPI &
PayloadRepositoryAPI
// MARK: - Properties
private let walletPairingRepository: AutoWalletPairingRepositoryAPI
private let walletCryptoService: WalletCryptoServiceAPI
private let walletPayloadService: WalletPayloadServiceAPI
private let parsingService: SharedKeyParsingService
// MARK: - Setup
public init(
walletPayloadService: WalletPayloadServiceAPI,
walletPairingRepository: AutoWalletPairingRepositoryAPI,
walletCryptoService: WalletCryptoServiceAPI,
parsingService: SharedKeyParsingService
) {
self.walletPayloadService = walletPayloadService
self.walletPairingRepository = walletPairingRepository
self.walletCryptoService = walletCryptoService
self.parsingService = parsingService
}
public func pair(using pairingData: PairingData) -> AnyPublisher<String, AutoWalletPairingServiceError> {
walletPairingRepository
.pair(using: pairingData)
.map {
KeyDataPair<String, String>(
key: $0,
data: pairingData.encryptedSharedKey
)
}
.flatMap { [walletCryptoService] keyDataPair -> AnyPublisher<String, AutoWalletPairingServiceError> in
walletCryptoService.decrypt(pair: keyDataPair, pbkdf2Iterations: WalletCryptoPBKDF2Iterations.autoPair)
.mapError(AutoWalletPairingServiceError.walletCryptoServiceError)
.eraseToAnyPublisher()
}
.map { [parsingService] pairingCode
-> Result<KeyDataPair<String, String>, AutoWalletPairingServiceError> in
parsingService.parse(pairingCode: pairingCode)
.mapError(AutoWalletPairingServiceError.parsingError)
}
.flatMap { [walletPayloadService] pairResult
-> AnyPublisher<String, AutoWalletPairingServiceError> in
switch pairResult {
case .success(let pair):
return walletPayloadService.request(
guid: pairingData.guid,
sharedKey: pair.data
)
.map { _ in pair.key }
.mapError(AutoWalletPairingServiceError.walletCryptoServiceError)
.eraseToAnyPublisher()
case .failure(let error):
return .failure(error)
}
}
.eraseToAnyPublisher()
}
public func encryptionPhrase(
using guid: String
) -> AnyPublisher<String, AutoWalletPairingServiceError> {
walletPairingRepository.encryptionPhrase(using: guid)
}
}
|
lgpl-3.0
|
a7bad5799152bb1e970c15cc59604124
| 40.154545 | 119 | 0.674619 | 5.454217 | false | false | false | false |
cubixlabs/GIST-Framework
|
GISTFramework/Classes/Controls/PopoverController.swift
|
1
|
14633
|
//
// BaseUICustomPopover.swift
// GISTFramework
//
// Created by Shoaib Abdul on 14/06/2016.
// Copyright © 2016 Social Cubix. All rights reserved.
//
import UIKit
/**
PopoverController is a subclass of UIViewController. It is a custom implementation of native UIPopoverController with some extra features.
It is taking UIViewController as a content view.
*/
open class PopoverController: BaseUIViewController {
//MARK: - Properties
private var _fromRect:CGRect = CGRect.zero;
private var _parentViewController:UIViewController!;
private var _containerView:BaseUIView!
private var _contentViewController:UIViewController?;
open var contentViewController:UIViewController? {
get {
return _contentViewController;
}
} //P.E.
private var _contentView:UIView?;
open var contentView:UIView? {
get {
return _contentView;
}
} //P.E.
private var _roundedCorner:Bool = true;
open var popoverContentRoundedCorner:Bool
{
set {
if (_roundedCorner != newValue) {
_roundedCorner = newValue;
_containerView.addRoundedCorners(_roundedCorner ?6:0);
}
}
get {
return _roundedCorner;
}
} //P.E.
private var _position:CGPoint?
open var popoverContentPosition:CGPoint?
{
set {
_position = newValue;
}
get {
return _position;
}
} //P.E.
private var _popoverContentSize:CGSize = CGSize(width: 320, height: 480);
/// Holds size of content view - Default value is CGSize(width: 320, height: 480).
open var popoverContentSize:CGSize {
set {
_popoverContentSize = newValue;
}
get {
return _popoverContentSize;
}
} //P.E.
private var popoverContentRect:CGRect {
get {
if (_position != nil)
{return CGRect(origin: _position!, size: _popoverContentSize);}
var rect:CGRect!
let offSet:CGFloat = 20;
switch (_arrowDirection) {
case UIPopoverArrowDirection.up:
rect = CGRect(x: _fromRect.origin.x + ((_fromRect.size.width - _popoverContentSize.width) / 2.0), y: _fromRect.origin.y + _fromRect.height + offSet, width: _popoverContentSize.width, height: _popoverContentSize.height);
break;
case UIPopoverArrowDirection.left:
rect = CGRect(x: _fromRect.origin.x + _fromRect.width + offSet, y: _fromRect.origin.y + ((_fromRect.size.height - _popoverContentSize.height) / 2.0), width: _popoverContentSize.width, height: _popoverContentSize.height);
break;
case UIPopoverArrowDirection.right:
rect = CGRect(x: _fromRect.origin.x - _popoverContentSize.width - offSet, y: _fromRect.origin.y + ((_fromRect.size.height - _popoverContentSize.height) / 2.0), width: _popoverContentSize.width, height: _popoverContentSize.height);
break;
case UIPopoverArrowDirection.down:
rect = CGRect(x: _fromRect.origin.x + ((_fromRect.size.width - _popoverContentSize.width) / 2.0), y: _fromRect.origin.y - _popoverContentSize.height - offSet, width: _popoverContentSize.width, height: _popoverContentSize.height);
break;
default:
rect = CGRect(x: (UIScreen.main.bounds.width - _popoverContentSize.width) / 2.0, y: (UIScreen.main.bounds.height - _popoverContentSize.height) / 2.0, width: _popoverContentSize.width, height: _popoverContentSize.height);
break;
}
rect.origin.x = min(max(offSet, rect.origin.x), UIScreen.main.bounds.width - rect.size.width - 15);
rect.origin.y = min(max(offSet, rect.origin.y), UIScreen.main.bounds.height - rect.size.height - 15);
return rect;
}
} //F.E.
private var _backgroundView:BaseUIView!;
private var _backgroundColor:UIColor = UIColor.black.withAlphaComponent(0.5);
open var backgroundColor:UIColor {
get {
return _backgroundColor;
}
set {
if (_backgroundColor != newValue) {
_backgroundColor = newValue;
_backgroundView.backgroundColor = _backgroundColor;
}
}
} //F.E.
open var arrowColor:UIColor {
get {
return self.arrowView.arrowColor;
}
set {
self.arrowView.arrowColor = newValue;
}
} //F.E.
private var _arrowView:ArrowView?;
private var arrowView:ArrowView {
get {
if (_arrowView == nil) {
_arrowView = ArrowView(frame: CGRect(x: 0, y: 0, width: 20, height: 20));
self.view.addSubview(_arrowView!);
}
return _arrowView!;
}
} //P.E.
private var _arrowDirection:UIPopoverArrowDirection = UIPopoverArrowDirection.unknown;
private var arrowDirection:UIPopoverArrowDirection {
get {
return _arrowDirection;
}
set {
_arrowDirection = newValue;
}
} //P.E.
public init(contentViewController:UIViewController) {
super.init(nibName: nil, bundle: nil);
self.modalPresentationStyle = UIModalPresentationStyle.custom;
self.view.backgroundColor = UIColor.clear;
self.setupPopoverController(contentViewController);
} //F.E.
/// Required constructor implemented.
required public init?(coder aDecoder: NSCoder) {
super.init(coder: aDecoder)
} //F.E
override open func viewDidLoad() {
super.viewDidLoad();
} //F.E.
override open func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
} //F.E.
private func setupPopoverController(_ contentViewController:UIViewController) {
_contentViewController = contentViewController;
self.addChild(_contentViewController!);
setupPopoverController(_contentViewController!.view);
} //F.E.
private func setupPopoverController(_ contentView:UIView) {
_contentView = contentView;
//Background View
_backgroundView = BaseUIView(frame: UIScreen.main.bounds);
_backgroundView.backgroundColor = _backgroundColor;
self.view.addSubview(_backgroundView);
_backgroundView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(backgroundViewTapped)));
let containtViewRect = self.popoverContentRect;
//ContainerView
_containerView = BaseUIView(frame: containtViewRect);
_containerView.backgroundColor = UIColor.clear;
_containerView.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth];
_containerView.addRoundedCorners(6);
self.view.addSubview(_containerView);
_contentView!.frame = CGRect(x: 0, y: 0, width: containtViewRect.width, height: containtViewRect.height);
_contentView!.autoresizingMask = [UIView.AutoresizingMask.flexibleHeight, UIView.AutoresizingMask.flexibleWidth];
_containerView.addSubview(_contentView!);
//Arrow
if (_contentView!.backgroundColor != nil)
{
self.arrowView.arrowColor = _contentView!.backgroundColor!;
}
} //F.E.
open func presentPopoverFromRect(_ rect:CGRect, inViewController viewController:UIViewController, permittedArrowDirection:UIPopoverArrowDirection, animated:Bool) {
updatePopoverFrame(fromRect:rect, permittedArrowDirection:permittedArrowDirection);
_parentViewController = viewController;
_parentViewController.present(self, animated: false, completion: nil);
if (animated)
{
self.view.alpha = 0.0;
afterDelay(0.1, closure: { () -> Void in
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.alpha=1.0
})
})
}
} //F.E.
@objc func backgroundViewTapped(_ gestureRecognizer:UITapGestureRecognizer) {
self.dismissPopoverAnimated(true);
} //F.E.
open func dismissPopoverAnimated(_ animated: Bool, completion:((Bool)->Void)? = nil) {
if (animated == true) {
UIView.animate(withDuration: 0.5, animations: { () -> Void in
self.view.alpha = 0.0;
}, completion: { (Bool) -> Void in
self.cleanup();
if (completion != nil)
{completion!(true);}
})
} else {
cleanup();
if (completion != nil)
{completion!(true);}
}
} //F.E.
private func cleanup() {
if (_contentView != nil)
{_contentView!.removeFromSuperview();}
if (_contentViewController != nil)
{_contentViewController!.removeFromParent();}
_containerView.removeFromSuperview();
_backgroundView.removeFromSuperview();
_parentViewController.dismiss(animated: false, completion: nil);
} //F.E.
private func updatePopoverFrame(fromRect rect:CGRect, permittedArrowDirection:UIPopoverArrowDirection) {
_fromRect = rect;
_arrowDirection = permittedArrowDirection;
let containtViewRect = self.popoverContentRect;
_containerView.frame = containtViewRect;
_contentView!.frame = CGRect(x: 0, y: 0, width: containtViewRect.width, height: containtViewRect.height);
//Arrow Update
updateArrow();
} //F.E.
//MARK: - ArrowView
private func updateArrow() {
switch (_arrowDirection) {
case UIPopoverArrowDirection.up:
self.arrowView.isHidden = false;
self.arrowView.frame = CGRect(x: _fromRect.origin.x + (_fromRect.width - self.arrowView.frame.width)/2.0, y: _containerView.frame.origin.y - self.arrowView.frame.size.height, width: self.arrowView.frame.size.width, height: self.arrowView.frame.size.height);
self.arrowView.transform = CGAffineTransform(rotationAngle: radianFromDegree(180));
break;
case UIPopoverArrowDirection.left:
self.arrowView.isHidden = false;
self.arrowView.frame = CGRect(x: _containerView.frame.origin.x - self.arrowView.frame.size.width, y: _fromRect.origin.y + (_fromRect.height - self.arrowView.frame.height)/2.0, width: self.arrowView.frame.size.width, height: self.arrowView.frame.size.height);
self.arrowView.transform = CGAffineTransform(rotationAngle: radianFromDegree(90));
break;
case UIPopoverArrowDirection.right:
self.arrowView.isHidden = false;
self.arrowView.frame = CGRect(x: _containerView.frame.origin.x + _containerView.frame.size.width, y: _fromRect.origin.y + (_fromRect.height - self.arrowView.frame.height)/2.0, width: self.arrowView.frame.size.width, height: self.arrowView.frame.size.height);
self.arrowView.transform = CGAffineTransform(rotationAngle: radianFromDegree(-90));
break;
case UIPopoverArrowDirection.down:
self.arrowView.isHidden = false;
self.arrowView.frame = CGRect(x: _fromRect.origin.x + (_fromRect.width - self.arrowView.frame.width)/2.0, y: _containerView.frame.origin.y + _containerView.frame.size.height, width: self.arrowView.frame.size.width, height: self.arrowView.frame.size.height);
break;
default:
self.arrowView.isHidden = true;
break;
}
} //F.E.
private func radianFromDegree(_ a:Double) -> CGFloat {
return CGFloat(.pi * a / 180.0);
} //F.E.
//Defining here in the class privately, so that the class be independent - It may be improved
private func afterDelay(_ delay:Double, closure:@escaping () -> Void) {
DispatchQueue.main.asyncAfter(
deadline: DispatchTime.now() + Double(Int64(delay * Double(NSEC_PER_SEC))) / Double(NSEC_PER_SEC), execute: closure)
} //F.E.
} //CLS END
private class ArrowView:BaseUIView {
private var _arrowColor:UIColor = UIColor.black;
var arrowColor:UIColor {
set {
_arrowColor = newValue;
}
get {
return _arrowColor;
}
} //P.E.
/// Overridden constructor to setup/ initialize components.
///
/// - Parameter frame: View frame
override init(frame: CGRect) {
super.init(frame: frame);
self.isOpaque = false;
} //C.E.
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
} //C.E.
override func draw(_ rect: CGRect) {
super.draw(rect);
// Drawing code
let currentContext:CGContext = UIGraphicsGetCurrentContext()!;
currentContext.setFillColor(_arrowColor.cgColor);
let arrowLocation:CGPoint = CGPoint(x: rect.midX, y: self.bounds.midY);
let arrowSize:CGSize = self.frame.size;
let arrowTip:CGPoint = CGPoint(x: arrowLocation.x, y: arrowLocation.y + (arrowSize.height / 2));
let arrowLeftFoot:CGPoint = CGPoint(x: arrowLocation.x - (arrowSize.width / 2), y: arrowLocation.y - (arrowSize.height / 2));
let arrowRightFoot:CGPoint = CGPoint(x: arrowLocation.x + (arrowSize.width / 2), y: arrowLocation.y - (arrowSize.height / 2));
// now we draw the triangle
currentContext.move(to: CGPoint(x: arrowTip.x, y: arrowTip.y));
currentContext.addLine(to: CGPoint(x: arrowLeftFoot.x, y: arrowLeftFoot.y));
currentContext.addLine(to: CGPoint(x: arrowRightFoot.x, y: arrowRightFoot.y));
currentContext.closePath();
currentContext.drawPath(using: CGPathDrawingMode.fill);
} //F.E.
} //CLS END
|
agpl-3.0
|
3154bbd7fdbea482c17a2b3f06606373
| 35.856423 | 270 | 0.595066 | 4.697271 | false | false | false | false |
gouyz/GYZBaking
|
baking/Classes/Tool/3rdLib/ScrollPageView/ContentView.swift
|
1
|
15545
|
//
// ContentView.swift
// ScrollViewController
//
// Created by jasnig on 16/4/13.
// Copyright © 2016年 ZeroJ. All rights reserved.
// github: https://github.com/jasnig
// 简书: http://www.jianshu.com/users/fb31a3d1ec30/latest_articles
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
open class CustomGestureCollectionView: UICollectionView {
var panGestureShouldBeginClosure: ((_ panGesture: UIPanGestureRecognizer, _ collectionView: CustomGestureCollectionView) -> Bool)?
func setupPanGestureShouldBeginClosure(_ closure: @escaping (_ panGesture: UIPanGestureRecognizer, _ collectionView: CustomGestureCollectionView) -> Bool) {
panGestureShouldBeginClosure = closure
}
override open func gestureRecognizerShouldBegin(_ gestureRecognizer: UIGestureRecognizer) -> Bool {
if let panGestureShouldBeginClosure = panGestureShouldBeginClosure, let panGesture = gestureRecognizer as? UIPanGestureRecognizer {
return panGestureShouldBeginClosure(panGesture, self)
}
else {
return super.gestureRecognizerShouldBegin(gestureRecognizer)
}
}
}
open class ContentView: UIView {
static let cellId = "cellId"
/// 所有的子控制器
fileprivate var childVcs: [UIViewController] = []
/// 用来判断是否是点击了title, 点击了就不要调用scrollview的代理来进行相关的计算
fileprivate var forbidTouchToAdjustPosition = false
/// 用来记录开始滚动的offSetX
fileprivate var beginOffSetX:CGFloat = 0.0
fileprivate var oldIndex = 0
fileprivate var currentIndex = 1
// 这里使用weak 避免循环引用
fileprivate weak var parentViewController: UIViewController?
open weak var delegate: ContentViewDelegate?
fileprivate(set) lazy var collectionView: CustomGestureCollectionView = {
let flowLayout = UICollectionViewFlowLayout()
let collection = CustomGestureCollectionView(frame: CGRect.zero, collectionViewLayout: flowLayout)
flowLayout.itemSize = self.bounds.size
flowLayout.scrollDirection = .horizontal
flowLayout.minimumLineSpacing = 0
flowLayout.minimumInteritemSpacing = 0
collection.scrollsToTop = false
collection.bounces = false
collection.showsHorizontalScrollIndicator = false
collection.frame = self.bounds
collection.collectionViewLayout = flowLayout
collection.isPagingEnabled = true
// 如果不设置代理, 将不会调用scrollView的delegate方法
collection.delegate = self
collection.dataSource = self
collection.register(UICollectionViewCell.self, forCellWithReuseIdentifier: ContentView.cellId)
return collection
}()
//MARK:- life cycle
public init(frame:CGRect, childVcs:[UIViewController], parentViewController: UIViewController) {
self.parentViewController = parentViewController
self.childVcs = childVcs
super.init(frame: frame)
commonInit()
}
required public init?(coder aDecoder: NSCoder) {
fatalError("不要使用storyboard中的view为contentView")
}
fileprivate func commonInit() {
// 不要添加navigationController包装后的子控制器
for childVc in childVcs {
if childVc.isKind(of: UINavigationController.self) {
fatalError("不要添加UINavigationController包装后的子控制器")
}
parentViewController?.addChildViewController(childVc)
}
collectionView.backgroundColor = UIColor.clear
collectionView.frame = bounds
// 在这里调用了懒加载的collectionView, 那么之前设置的self.frame将会用于collectionView,如果在layoutsubviews()里面没有相关的处理frame的操作, 那么将导致内容显示不正常
addSubview(collectionView)
// 设置naviVVc手势代理, 处理pop手势 只在第一个页面的时候执行系统的滑动返回手势
if let naviParentViewController = self.parentViewController?.parent as? UINavigationController {
if naviParentViewController.viewControllers.count == 1 { return }
collectionView.setupPanGestureShouldBeginClosure({[weak self] (panGesture, collectionView) -> Bool in
let strongSelf = self
guard let `self` = strongSelf else { return false}
let transionX = panGesture.velocity(in: panGesture.view).x
if collectionView.contentOffset.x == 0 && transionX > 0 {
naviParentViewController.interactivePopGestureRecognizer?.isEnabled = true
}
else {
naviParentViewController.interactivePopGestureRecognizer?.isEnabled = false
}
return self.delegate?.contentViewShouldBeginPanGesture(panGesture, collectionView: collectionView) ?? true
})
}
}
// 发布通知
fileprivate func addCurrentShowIndexNotification(_ index: Int) {
NotificationCenter.default.post(name: Notification.Name(rawValue: ScrollPageViewDidShowThePageNotification), object: nil, userInfo: ["currentIndex": index])
}
override open func layoutSubviews() {
super.layoutSubviews()
collectionView.frame = bounds
let vc = childVcs[currentIndex]
vc.view.frame = bounds
}
deinit {
parentViewController = nil
print("\(self.debugDescription) --- 销毁")
}
}
//MARK: - public helper
extension ContentView {
// 给外界可以设置ContentOffSet的方法(public method to set contentOffSet)
public func setContentOffSet(_ offSet: CGPoint , animated: Bool) {
// 不要执行collectionView的scrollView的滚动代理方法
self.forbidTouchToAdjustPosition = true
//这里开始滚动
delegate?.contentViewDidBeginMove(collectionView)
self.collectionView.setContentOffset(offSet, animated: animated)
}
// 给外界刷新视图的方法(public method to reset childVcs)
public func reloadAllViewsWithNewChildVcs(_ newChildVcs: [UIViewController] ) {
// removing the old childVcs
childVcs.forEach { (childVc) in
childVc.willMove(toParentViewController: nil)
childVc.view.removeFromSuperview()
childVc.removeFromParentViewController()
}
childVcs.removeAll()
// setting the new childVcs
childVcs = newChildVcs
// don't add the childVc that wrapped by the navigationController
// 不要添加navigationController包装后的子控制器
for childVc in childVcs {
if childVc.isKind(of: UINavigationController.self) {
fatalError("不要添加UINavigationController包装后的子控制器")
}
// add childVc
parentViewController?.addChildViewController(childVc)
}
// refreshing
collectionView.reloadData()
}
}
//MARK:- UICollectionViewDelegate, UICollectionViewDataSource
extension ContentView: UICollectionViewDelegate, UICollectionViewDataSource {
final public func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return childVcs.count
}
final public func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: ContentView.cellId, for: indexPath)
// 避免出现重用显示内容出错 ---- 也可以直接给每个cell用不同的reuseIdentifier实现
// avoid to the case that shows the wrong thing due to the collectionViewCell's reuse
for subview in cell.contentView.subviews {
subview.removeFromSuperview()
}
let vc = childVcs[indexPath.row]
vc.view.frame = bounds
cell.contentView.addSubview(vc.view)
// finish buildding the parent-child relationship
vc.didMove(toParentViewController: parentViewController)
// 发布将要显示的index
addCurrentShowIndexNotification(indexPath.row)
return cell
}
}
// MARK: - UIScrollViewDelegate
extension ContentView: UIScrollViewDelegate {
// update UI
final public func scrollViewDidEndDecelerating(_ scrollView: UIScrollView) {
let currentIndex = Int(floor(scrollView.contentOffset.x / bounds.size.width))
// print("减速完成")
// if self.currentIndex == currentIndex {// finish scrolling to next page
//
// addCurrentShowIndexNotification(currentIndex)
//
// }
delegate?.contentViewDidEndDisPlay(collectionView)
// 保证如果滚动没有到下一页就返回了上一页
// 通过这种方式再次正确设置 index(still at oldPage )
delegate?.contentViewDidEndMoveToIndex(self.currentIndex, toIndex: currentIndex)
}
// 代码调整contentOffSet但是没有动画的时候不会调用这个
final public func scrollViewDidEndScrollingAnimation(_ scrollView: UIScrollView) {
delegate?.contentViewDidEndDisPlay(collectionView)
}
final public func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) {
let currentIndex = Int(floor(scrollView.contentOffset.x / bounds.size.width))
if let naviParentViewController = self.parentViewController?.parent as? UINavigationController {
naviParentViewController.interactivePopGestureRecognizer?.isEnabled = true
}
delegate?.contentViewDidEndDrag(scrollView)
print(scrollView.contentOffset.x)
//快速滚动的时候第一页和最后一页(scroll too fast will not call 'scrollViewDidEndDecelerating')
if scrollView.contentOffset.x == 0 || scrollView.contentOffset.x == scrollView.contentSize.width - scrollView.bounds.width{
if self.currentIndex != currentIndex {
delegate?.contentViewDidEndMoveToIndex(self.currentIndex, toIndex: currentIndex)
}
}
}
// 手指开始拖的时候, 记录此时的offSetX, 并且表示不是点击title切换的内容(remenber the begin offsetX)
final public func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
/// 用来判断方向
beginOffSetX = scrollView.contentOffset.x
delegate?.contentViewDidBeginMove(collectionView)
forbidTouchToAdjustPosition = false
}
// 需要实时更新滚动的进度和移动的方向及下标 以便于外部使用 (compute the index and progress)
final public func scrollViewDidScroll(_ scrollView: UIScrollView) {
let offSetX = scrollView.contentOffset.x
// 如果是点击了title, 就不要计算了, 直接在点击相应的方法里就已经处理了滚动
if forbidTouchToAdjustPosition {
return
}
let temp = offSetX / bounds.size.width
// 滚动的进度 -- 取小数位
var progress = temp - floor(temp)
// 根据滚动的方向
if offSetX - beginOffSetX >= 0 {// 手指左滑, 滑块右移
oldIndex = Int(floor(offSetX / bounds.size.width))
currentIndex = oldIndex + 1
if currentIndex >= childVcs.count {
currentIndex = oldIndex - 1
}
if offSetX - beginOffSetX == scrollView.bounds.size.width {// 滚动完成
progress = 1.0;
currentIndex = oldIndex;
}
} else {// 手指右滑, 滑块左移
currentIndex = Int(floor(offSetX / bounds.size.width))
oldIndex = currentIndex + 1
progress = 1.0 - progress
}
// print("\(progress)------\(oldIndex)----\(currentIndex)")
delegate?.contentViewMoveToIndex(oldIndex, toIndex: currentIndex, progress: progress)
}
}
public protocol ContentViewDelegate: class {
/// 有默认实现, 不推荐重写(override is not recommoned)
func contentViewMoveToIndex(_ fromIndex: Int, toIndex: Int, progress: CGFloat)
/// 有默认实现, 不推荐重写(override is not recommoned)
func contentViewDidEndMoveToIndex(_ fromIndex: Int , toIndex: Int)
func contentViewShouldBeginPanGesture(_ panGesture: UIPanGestureRecognizer , collectionView: CustomGestureCollectionView) -> Bool;
func contentViewDidBeginMove(_ scrollView: UIScrollView)
func contentViewIsScrolling(_ scrollView: UIScrollView)
func contentViewDidEndDisPlay(_ scrollView: UIScrollView)
func contentViewDidEndDrag(_ scrollView: UIScrollView)
/// 必须提供的属性
var segmentView: ScrollSegmentView { get }
}
// 由于每个遵守这个协议的都需要执行些相同的操作, 所以直接使用协议扩展统一完成,协议遵守者只需要提供segmentView即可
extension ContentViewDelegate {
public func contentViewDidEndDrag(_ scrollView: UIScrollView) {
}
public func contentViewDidEndDisPlay(_ scrollView: UIScrollView) {
}
public func contentViewIsScrolling(_ scrollView: UIScrollView) {
}
// 默认什么都不做
public func contentViewDidBeginMove(_ scrollView: UIScrollView) {
}
public func contentViewShouldBeginPanGesture(_ panGesture: UIPanGestureRecognizer , collectionView: CustomGestureCollectionView) -> Bool {
return true
}
// 内容每次滚动完成时调用, 确定title和其他的控件的位置
public func contentViewDidEndMoveToIndex(_ fromIndex: Int , toIndex: Int) {
segmentView.adjustTitleOffSetToCurrentIndex(toIndex)
segmentView.adjustUIWithProgress(1.0, oldIndex: fromIndex, currentIndex: toIndex)
}
// 内容正在滚动的时候,同步滚动滑块的控件
public func contentViewMoveToIndex(_ fromIndex: Int, toIndex: Int, progress: CGFloat) {
segmentView.adjustUIWithProgress(progress, oldIndex: fromIndex, currentIndex: toIndex)
}
}
|
mit
|
476be3c06d2bdc4b4d3a14932462e9ff
| 37.347594 | 164 | 0.677451 | 5.265051 | false | false | false | false |
tjw/swift
|
validation-test/Reflection/functions_objc.swift
|
5
|
2215
|
// RUN: %empty-directory(%t)
// RUN: %target-build-swift -lswiftSwiftReflectionTest %s -o %t/functions
// RUN: %target-run %target-swift-reflection-test %t/functions | %FileCheck %s --check-prefix=CHECK --check-prefix=CHECK-%target-ptrsize
// REQUIRES: objc_interop
// REQUIRES: executable_test
import SwiftReflectionTest
import Foundation
import CoreGraphics
func capturesImportedTypes(x: Int, n: NSURL, r: CGRect, c: NSCoding) {
reflect(function: {print(x); print(n); print(r); print(c)})
// CHECK-32: Type reference:
// CHECK-32-NEXT: (builtin Builtin.NativeObject)
// CHECK-32: Type info:
// CHECK-32-NEXT: (closure_context size=36 alignment=4 stride=36 num_extra_inhabitants=0
// CHECK-32-NEXT: (field offset=8
// CHECK-32-NEXT: (struct size=4 alignment=4 stride=4 num_extra_inhabitants=0
// CHECK-32-NEXT: (field name=_value offset=0
// CHECK-32-NEXT: (builtin size=4 alignment=4 stride=4 num_extra_inhabitants=0))))
// CHECK-32-NEXT: (field offset=12
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-32-NEXT: (field offset=16
// CHECK-32-NEXT: (builtin size=16 alignment=4 stride=16 num_extra_inhabitants=0))
// CHECK-32-NEXT: (field offset=32
// CHECK-32-NEXT: (reference kind=strong refcounting=unknown)))
// CHECK-64: Type reference:
// CHECK-64-NEXT: (builtin Builtin.NativeObject)
// CHECK-64: Type info:
// CHECK-64-NEXT: (closure_context size=72 alignment=8 stride=72 num_extra_inhabitants=0
// CHECK-64-NEXT: (field offset=16
// CHECK-64-NEXT: (struct size=8 alignment=8 stride=8 num_extra_inhabitants=0
// CHECK-64-NEXT: (field name=_value offset=0
// CHECK-64-NEXT: (builtin size=8 alignment=8 stride=8 num_extra_inhabitants=0))))
// CHECK-64-NEXT: (field offset=24
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown))
// CHECK-64-NEXT: (field offset=32
// CHECK-64-NEXT: (builtin size=32 alignment=8 stride=32 num_extra_inhabitants=0))
// CHECK-64-NEXT: (field offset=64
// CHECK-64-NEXT: (reference kind=strong refcounting=unknown)))
}
capturesImportedTypes(x: 10, n: NSURL(), r: CGRect(x: 1, y: 2, width: 3, height: 4), c: "" as NSString)
doneReflecting()
|
apache-2.0
|
ec06088f90b36824a292e1b4ac2f19a7
| 44.204082 | 136 | 0.693454 | 3.164286 | false | true | false | false |
yonat/MultiSelectSegmentedControl
|
Example/MultiSegmentDemo/ViewController.swift
|
1
|
3384
|
//
// ViewController.swift
// MultiSegmentDemo
//
// Created by Yonat Sharon on 19/08/2019.
// Copyright © 2019 Yonat Sharon. All rights reserved.
//
import MultiSelectSegmentedControl
import UIKit
#if canImport(SwiftUI)
import SwiftUI
#endif
class ViewController: UIViewController {
@IBOutlet var weekControl: MultiSelectSegmentedControl!
@IBOutlet var verticalTextControl: MultiSelectSegmentedControl!
@IBOutlet var imagesControl: MultiSelectSegmentedControl!
@IBOutlet var mixedControl: MultiSelectSegmentedControl!
@IBOutlet var segmentIndexField: UITextField!
@IBOutlet var showSwiftUIButton: UIButton!
override func viewDidLoad() {
super.viewDidLoad()
weekControl.items = ["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"]
verticalTextControl.items = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten"]
imagesControl.items = [#imageLiteral(resourceName: "dove.png"), #imageLiteral(resourceName: "flamingo.png"), #imageLiteral(resourceName: "flying-duck.png"), #imageLiteral(resourceName: "hummingbird.png"), #imageLiteral(resourceName: "owl.png")].map { $0.withRenderingMode(.alwaysTemplate) }
mixedControl.items = [#imageLiteral(resourceName: "european-dragon.png"), #imageLiteral(resourceName: "fenix.png"), #imageLiteral(resourceName: "swan.png"), #imageLiteral(resourceName: "budgie.png"), #imageLiteral(resourceName: "butterfly.png")].enumerated().map { [$1, $0] }
weekControl.selectedSegmentIndexes = [4, 5, 6]
imagesControl.selectedSegmentIndex = 3
imagesControl.delegate = self
mixedControl.addTarget(self, action: #selector(mixedChanged), for: .valueChanged)
verticalTextControl.setTitleTextAttributes([.foregroundColor: UIColor.yellow], for: .selected)
verticalTextControl.setTitleTextAttributes([.obliqueness: 0.25], for: .normal)
}
override func viewDidAppear(_ animated: Bool) {
super.viewDidAppear(animated)
if #available(iOS 13.0, *) {
showSwiftUIButton.isHidden = false
showSwiftUIButton.layer.borderWidth = 1
showSwiftUIButton.layer.cornerRadius = showSwiftUIButton.frame.height / 2
showSwiftUIButton.layer.borderColor = view.actualTintColor.cgColor
}
}
@IBAction func addSegment() {
guard let indexText = segmentIndexField.text, let index = Int(indexText) else { return }
verticalTextControl.insertSegment(withTitle: indexText, at: index, animated: true)
}
@IBAction func removeSegment() {
guard let indexText = segmentIndexField.text, let index = Int(indexText) else { return }
verticalTextControl.removeSegment(at: index, animated: true)
}
@objc func mixedChanged(multiSelectSegmentedControl: MultiSelectSegmentedControl) {
print(multiSelectSegmentedControl.selectedSegmentTitles)
}
@IBAction func showSwiftUIDemo() {
#if canImport(SwiftUI)
if #available(iOS 13.0, *) {
present(UIHostingController(rootView: MultiSegmentPickerDemo()), animated: true)
}
#endif
}
}
extension ViewController: MultiSelectSegmentedControlDelegate {
func multiSelect(_ multiSelectSegmentedControl: MultiSelectSegmentedControl, didChange value: Bool, at index: Int) {
print("\(value) at \(index)")
}
}
|
mit
|
6c6dc13aece435827b751a4f068e5e4e
| 41.2875 | 298 | 0.703222 | 4.404948 | false | false | false | false |
baodvu/MagicSpell
|
MagicSpellKeyboard/KeyboardViewController.swift
|
1
|
10801
|
import Foundation
import AVFoundation
import UIKit
class KeyboardViewController: UIInputViewController {
// MARK: UI Components
@IBOutlet weak var leftPinkyFingerButton: UIButton!
@IBOutlet weak var leftRingFingerButton: UIButton!
@IBOutlet weak var leftMiddleFingerButton: UIButton!
@IBOutlet weak var leftIndexFingerButton: UIButton!
@IBOutlet weak var leftThumbFingerButton: UIButton!
@IBOutlet weak var rightIndexFingerButton: UIButton!
@IBOutlet weak var rightMiddleFingerButton: UIButton!
@IBOutlet weak var rightRingFingerButton: UIButton!
@IBOutlet weak var rightPinkyFingerButton: UIButton!
@IBOutlet weak var rightThumbFingerButton: UIButton!
@IBOutlet weak var shiftButton: UIButton!
@IBOutlet weak var bwColor: UIButton!
@IBOutlet weak var greenColor: UIButton!
@IBOutlet weak var rainbowColor: UIButton!
@IBOutlet weak var keyboardSizeStepper: UIStepper!
@IBOutlet weak var settingsOverlay: UIView!
@IBOutlet weak var settingsSlideIn: UIView!
var player: AVAudioPlayer?
let appGroup = "group.pentagon.magicspell"
var sharedDefaults : UserDefaults?
var keyboardSize : Int {
get {
if let s = sharedDefaults?.object(forKey: "keyboardSize") {
return s as! Int
}
sharedDefaults?.set(2, forKey: "keyboardSize")
sharedDefaults?.synchronize()
return 2 // Default keyboard size
}
set {
sharedDefaults?.set(newValue, forKey: "keyboardSize")
sharedDefaults?.synchronize()
}
}
var customInterface: UIView!
var proxy: UITextDocumentProxy {
get { return textDocumentProxy as UITextDocumentProxy }
}
var heightConstraint: NSLayoutConstraint!
var keyboardHeight:CGFloat = 400
var buttonToFinger = [UIButton: Finger]()
var colorScheme = ColorScheme.green
// MARK: Keyboard states
var shiftKeyActive = false {
didSet {
shiftButton.setImage(UIImage(named: shiftKeyActive ? "Shift - filled" : "Shift"), for: UIControlState())
}
}
var fingersPressed = Set<Finger>()
override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) {
super.init(nibName: nibNameOrNil, bundle: nibBundleOrNil)
let nib = UINib(nibName: "CustomKeyboardInterface", bundle: nil)
let objects = nib.instantiate(withOwner: self, options: nil)
customInterface = objects[0] as! UIView
customInterface.frame = view.frame
sharedDefaults = UserDefaults(suiteName: appGroup)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func viewDidLoad() {
super.viewDidLoad()
sendKeyboardNotification()
view.addSubview(customInterface)
buttonToFinger[leftPinkyFingerButton!] = Finger(side: .left, name: .pinky)
buttonToFinger[leftRingFingerButton!] = Finger(side: .left, name: .ring)
buttonToFinger[leftMiddleFingerButton!] = Finger(side: .left, name: .middle)
buttonToFinger[leftIndexFingerButton!] = Finger(side: .left, name: .index)
buttonToFinger[leftThumbFingerButton!] = Finger(side: .left, name: .thumb)
buttonToFinger[rightPinkyFingerButton!] = Finger(side: .right, name: .pinky)
buttonToFinger[rightRingFingerButton!] = Finger(side: .right, name: .ring)
buttonToFinger[rightMiddleFingerButton!] = Finger(side: .right, name: .middle)
buttonToFinger[rightIndexFingerButton!] = Finger(side: .right, name: .index)
buttonToFinger[rightThumbFingerButton!] = Finger(side: .right, name: .thumb)
updateKeyLabels()
updateKeyColor()
// Set up Settings Slide-in
settingsOverlay.isHidden = true
keyboardSizeStepper.maximumValue = 4
bwColor.applyGradient(colours: ColorScheme.defaultBW.colors)
bwColor.layer.borderWidth = 1.0
bwColor.layer.borderColor = UIColor.lightGray.cgColor
bwColor.layer.cornerRadius = 2.0
greenColor.applyGradient(colours: ColorScheme.green.colors)
greenColor.layer.borderWidth = 1.0
greenColor.layer.borderColor = UIColor.lightGray.cgColor
greenColor.layer.cornerRadius = 2.0
rainbowColor.applyGradient(colours: ColorScheme.rainbow.colors)
rainbowColor.layer.borderWidth = 1.0
rainbowColor.layer.borderColor = UIColor.lightGray.cgColor
rainbowColor.layer.cornerRadius = 2.0
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
setUpKeyboardSize()
}
func sendKeyboardNotification() {
CFNotificationCenterPostNotification(CFNotificationCenterGetDarwinNotifyCenter(),
CFNotificationName.init("cc.gatech.edu.pentagon.magicspell.switched" as CFString),
nil, nil, true)
}
func setUpHeightConstraint() {
let customHeight: CGFloat = keyboardHeight
if heightConstraint == nil {
heightConstraint = NSLayoutConstraint(
item: self.view,
attribute: .height,
relatedBy: .equal,
toItem: nil,
attribute: .notAnAttribute,
multiplier: 0.0,
constant: customHeight
)
heightConstraint.priority = UILayoutPriority(999)
view.addConstraint(heightConstraint)
} else {
heightConstraint.constant = customHeight
}
}
func updateKeyLabels() {
// Disabled key labels
/*
for key in buttonToFinger.keys {
let finger = buttonToFinger[key]
var potentialFingerCombination = fingersPressed
potentialFingerCombination.insert(finger!)
key.setTitle(LetterMapping.getLetter(potentialFingerCombination, isUpperCase: shiftKeyActive), for: UIControlState())
}*/
}
func toggleShift() {
shiftButton.setImage(UIImage(named: shiftKeyActive ? "Shift" : "Shift - filled"), for: UIControlState())
shiftKeyActive = !shiftKeyActive
}
// MARK: Key actions
@IBAction func didTapNextKeyboard() {
self.advanceToNextInputMode()
}
@IBAction func didTapComma() {
proxy.insertText(",")
}
@IBAction func didTapPeriod() {
proxy.insertText(".")
}
@IBAction func didTapExclamationMark() {
proxy.insertText("!")
}
@IBAction func didTapQuestionMark() {
proxy.insertText("?")
}
@IBAction func didTapSpaceBar() {
proxy.insertText(" ")
}
@IBAction func didTapBackspace() {
proxy.deleteBackward()
}
@IBAction func didTapEnter() {
proxy.insertText("\n")
}
@IBAction func didTapShift(_ sender: UIButton) {
shiftKeyActive = !shiftKeyActive
updateKeyLabels()
}
@IBAction func touchDownFinger(_ sender: UIButton) {
let finger = buttonToFinger[sender]!
fingersPressed.insert(finger)
sender.backgroundColor = colorScheme.getDarkerColor(buttonToFinger[sender]!)
// Update text field
if let letter = LetterMapping.getLetter(fingersPressed, isUpperCase: shiftKeyActive) {
if fingersPressed.count == 2 {
proxy.deleteBackward()
fingersPressed.removeAll()
}
proxy.insertText(letter)
// playSound(letter: letter)
} else {
// Invalid combination of keys, clear the stack
fingersPressed.removeAll()
}
updateKeyLabels()
}
@IBAction func touchUpFinger(_ sender: UIButton) {
sender.backgroundColor = colorScheme.getColor(buttonToFinger[sender]!)
fingersPressed.removeAll()
shiftKeyActive = false
updateKeyLabels()
}
@IBAction func openSettings() {
settingsSlideIn.center.x += self.settingsSlideIn.frame.width
settingsOverlay.backgroundColor = settingsOverlay.backgroundColor?.withAlphaComponent(0)
settingsOverlay.isHidden = false
UIView.animate(withDuration: 0.4, animations: {
self.settingsSlideIn.center.x -= self.settingsSlideIn.frame.width
self.settingsOverlay.backgroundColor = self.settingsOverlay.backgroundColor?.withAlphaComponent(0.25)
})
}
@IBAction func closeSettings() {
UIView.animate(withDuration: 0.4, animations: {
self.settingsSlideIn.center.x += self.settingsSlideIn.frame.width
self.settingsOverlay.backgroundColor = self.settingsOverlay.backgroundColor?.withAlphaComponent(0)
}, completion: {(_) -> Void in
self.settingsOverlay.isHidden = true
self.settingsSlideIn.center.x -= self.settingsSlideIn.frame.width})
}
@IBAction func changeKeyboardSize() {
keyboardHeight = CGFloat(320 + keyboardSizeStepper.value * 30)
keyboardSize = Int(keyboardSizeStepper.value)
setUpHeightConstraint()
}
@IBAction func changeColorTheme(_ sender: UIButton) {
switch sender {
case bwColor:
colorScheme = ColorScheme.defaultBW
case rainbowColor:
colorScheme = ColorScheme.rainbow
default:
colorScheme = ColorScheme.green
}
updateKeyColor()
}
func updateKeyColor() {
for (key, value) in buttonToFinger {
key.backgroundColor = colorScheme.getColor(value)
}
}
func setUpKeyboardSize() {
keyboardSizeStepper.value = Double(keyboardSize)
changeKeyboardSize()
}
func playSound(letter: String)
{
let url = Bundle.main.url(forResource: "/Sounds/\(letter.uppercased())", withExtension: "wav")!
do {
player = try AVAudioPlayer(contentsOf: url)
guard let player = player else { return }
player.prepareToPlay()
player.play()
} catch let error {
print(error.localizedDescription)
}
}
}
extension UIButton {
func applyGradient(colours: [UIColor]) -> Void {
let view = UIView(frame: CGRect(x: 0.0, y: 0.0, width: 30.0, height: 30.0))
let gradient: CAGradientLayer = CAGradientLayer()
gradient.frame = view.bounds
gradient.colors = colours.map { $0.cgColor }
self.layer.insertSublayer(gradient, at: 0)
}
}
|
mit
|
923940dc628c7a410dc34df240f7de22
| 34.297386 | 129 | 0.629571 | 5.00974 | false | false | false | false |
braintree/braintree_ios
|
UnitTests/BraintreePayPalNativeCheckoutTests/BTPayPalNativeHermesResponse_Tests.swift
|
1
|
875
|
import XCTest
@testable import BraintreePayPalNativeCheckout
@testable import BraintreeCore
class BTPayPalNativeHermesResponse_Tests: XCTestCase {
func testHermesResponseCreation() throws {
let expectedECToken = "EC-4RW94683SG8462403"
let jsonData = try XCTUnwrap("""
{
"paymentResource": {
"authenticateUrl": null,
"intent": "authorize",
"paymentToken": "PAYID-MK5WKWI5LX430173F5705007",
"redirectUrl": "https://www.sandbox.paypal.com/checkoutnow?nolegacy=1&token=\(expectedECToken)"
}
}
""".data(using: .utf8))
let json = BTJSON(data: jsonData)
let hermesResponse = BTPayPalNativeHermesResponse(json: json)
XCTAssertNotNil(hermesResponse)
XCTAssertEqual(hermesResponse?.orderID, expectedECToken)
}
}
|
mit
|
9351ea4e410f676e4be83d710c15ea40
| 31.407407 | 111 | 0.641143 | 4.268293 | false | true | false | false |
allbto/WayThere
|
ios/WayThere/WayThere/Classes/Controllers/Today/TodayViewController.swift
|
2
|
7229
|
//
// TodayViewController.swift
// WayThere
//
// Created by Allan BARBATO on 5/16/15.
// Copyright (c) 2015 Allan BARBATO. All rights reserved.
//
import UIKit
class TodayViewController: UIViewController
{
var index : Int = 0
@IBOutlet weak var backgroundImageView: UIImageView!
@IBOutlet weak var topImageView: UIImageView!
@IBOutlet weak var currentIconImageView: UIImageView!
@IBOutlet weak var locationLabel: UILabel!
@IBOutlet weak var conditionLabel: UILabel!
@IBOutlet weak var infoRainPercentLabel: UILabel!
@IBOutlet weak var infoRainQuantityLabel: UILabel!
@IBOutlet weak var infoRainPressureLabel: UILabel!
@IBOutlet weak var infoWindSpeedLabel: UILabel!
@IBOutlet weak var infoWindDirectionLabel: UILabel!
@IBOutlet weak var shareSmallScreenButton: UIButton!
@IBOutlet weak var shareBiggerScreenButton: UIButton!
var dataStore = TodayDataStore()
private func _setLabelsColor(#initial: Bool)
{
var color = initial ? UIColor(red:0.2, green:0.2, blue:0.2, alpha:1) /*#333333*/ : UIColor.whiteColor()
self.locationLabel.textColor = color
self.conditionLabel.textColor = initial ? UIColor(red:0.184, green:0.569, blue:1, alpha:1) /*#2f91ff*/ : color
self.infoRainPercentLabel.textColor = color
self.infoRainQuantityLabel.textColor = color
self.infoRainPressureLabel.textColor = color
self.infoWindSpeedLabel.textColor = color
self.infoWindDirectionLabel.textColor = color
}
private func _setWeatherLabels(#city: City)
{
if let weather = city.todayWeather {
if SettingsDataStore.settingValueForKey(.UnitOfTemperature) as? String == SettingUnitOfTemperature.Celcius.rawValue {
conditionLabel.text = "\(String(weather.tempCelcius as? Int))°C"
} else {
conditionLabel.text = "\(String(weather.tempFahrenheit as? Int))°F"
}
conditionLabel.text! += " | \(String(weather.title))"
infoRainPercentLabel.text = "\(weather.humidity ?? 0)%"
infoRainPressureLabel.text = "\(weather.pressure ?? 0) hPa"
infoRainQuantityLabel.text = "\(weather.rainAmount ?? 0) mm"
topImageView.image = weather.weatherImage()
}
}
private func _setWindLabels(#city: City)
{
if let wind = city.wind {
if SettingsDataStore.settingValueForKey(.UnitOfLenght) as? String == SettingUnitOfLenght.Meters.rawValue {
infoWindSpeedLabel.text = "\(String(wind.speedMetric)) \(Wind.metricUnit)"
} else {
var speed = String(format: "%.2f", wind.speedImperial?.floatValue ?? 0)
infoWindSpeedLabel.text = "\(speed) \(Wind.imperialUnit)"
}
infoWindDirectionLabel.text = wind.direction
}
}
var city : City? {
didSet
{
if let sCity = city {
// Check is allowed to display a backgroundImageView
if backgroundImageView.image == nil && (SettingsDataStore.settingValueForKey(SettingKey.ClassicMode) as! Bool) == false {
backgroundImageView.hidden = false
// Check city background image has already been downloaded
if let image = self.city?.backgroundImage {
self._setLabelsColor(initial: false)
self.backgroundImageView.image = image
} else {
dataStore.retrieveRandomImageUrlFromCity(sCity)
}
} else {
self._setLabelsColor(initial: true)
backgroundImageView.hidden = true
}
// Location
locationLabel.text = "\(String(sCity.name)), \(String(sCity.country))"
// Current location icon
if sCity.isCurrentLocation?.boolValue == true {
currentIconImageView.hidden = false
} else {
currentIconImageView.hidden = true
}
// Other labels
_setWeatherLabels(city: sCity)
_setWindLabels(city: sCity)
}
}
}
// MARK: - UIViewController
override func viewDidLoad()
{
super.viewDidLoad()
shareSmallScreenButton.hidden = !Device.IS_3_5_INCHES_OR_SMALLER()
shareBiggerScreenButton.hidden = !shareSmallScreenButton.hidden
// Reset label (I like to see them full when I edit the view)
locationLabel.text = ""
conditionLabel.text = ""
infoRainPercentLabel.text = ""
infoRainQuantityLabel.text = ""
infoRainPressureLabel.text = ""
infoWindSpeedLabel.text = ""
infoWindDirectionLabel.text = ""
// Config data store
dataStore.delegate = self
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - Actions
@IBAction func shareWeatherAction(sender: AnyObject)
{
let opening = "Check out today's weather in \(locationLabel.text!) !"
let weatherStatus = conditionLabel.text!
let activityVC = UIActivityViewController(activityItems: [opening, weatherStatus], applicationActivities: nil)
// New Excluded Activities Code
activityVC.excludedActivityTypes = [UIActivityTypeAddToReadingList]
self.presentViewController(activityVC, animated: true, completion: nil)
}
}
extension TodayViewController : TodayDataStoreDelegate
{
/**
DataStore delegate method to receive a random image url
- Checks if it's allowed to display a background image (Settings screen)
- Fetch the image online with UIImageView.setImageFromUrl()
- Once found dark effect is applied to image and is assinged to backgroundImageView
- It is also assign to the city model (not saved to core data of course), just as a way to get the image faster on next load (see top of this class)
- Labels are put to white to increase the beautyness
:param: imageUrl to download
*/
func foundRandomImageUrl(imageUrl: String)
{
if backgroundImageView.image == nil && (SettingsDataStore.settingValueForKey(SettingKey.ClassicMode) as! Bool) == false {
backgroundImageView.setImageFromUrl(imageUrl) { [unowned self] (image) in
self.backgroundImageView.image = image.applyDarkEffect()
self.city?.backgroundImage = self.backgroundImageView.image
self.backgroundImageView.alpha = 0
UIView.animateWithDuration(0.2) {
self._setLabelsColor(initial: false)
self.backgroundImageView.alpha = 1
}
}
}
}
func unableToFindRandomImageUrl(error: NSError?)
{
// Do nothing, it's ok to not have a background image
}
}
|
mit
|
6a2f059913d22f570579acebb36e6738
| 37.854839 | 156 | 0.611042 | 4.953393 | false | false | false | false |
alexaubry/BulletinBoard
|
Sources/Support/Views/Internal/ContinuousCorners/ContinuousMaskLayer.swift
|
2
|
1689
|
/**
* BulletinBoard
* Copyright (c) 2017 - present Alexis Aubry. Licensed under the MIT license.
*/
import UIKit
/**
* A shape layer that animates its path inside a block.
*/
private class AnimatingShapeLayer: CAShapeLayer {
override class func defaultAction(forKey event: String) -> CAAction? {
if event == "path" {
return CABasicAnimation(keyPath: event)
} else {
return super.defaultAction(forKey: event)
}
}
}
/**
* A layer whose corners are rounded with a continuous mask (“squircle“).
*/
class ContinuousMaskLayer: CALayer {
/// The corner radius.
var continuousCornerRadius: CGFloat = 0 {
didSet {
refreshMask()
}
}
/// The corners to round.
var roundedCorners: UIRectCorner = .allCorners {
didSet {
refreshMask()
}
}
// MARK: - Initialization
override init(layer: Any) {
super.init(layer: layer)
}
override init() {
super.init()
self.mask = AnimatingShapeLayer()
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
// MARK: - Layout
override func layoutSublayers() {
super.layoutSublayers()
refreshMask()
}
private func refreshMask() {
guard let mask = mask as? CAShapeLayer else {
return
}
let radii = CGSize(width: continuousCornerRadius, height: continuousCornerRadius)
let roundedPath = UIBezierPath(roundedRect: bounds, byRoundingCorners: roundedCorners, cornerRadii: radii)
mask.path = roundedPath.cgPath
}
}
|
mit
|
6ddcd91d8aedebf15ec72cc4e5828caf
| 19.802469 | 114 | 0.605935 | 4.693593 | false | false | false | false |
tjw/swift
|
test/SILGen/switch_var.swift
|
1
|
27920
|
// RUN: %target-swift-frontend -module-name switch_var -emit-silgen %s | %FileCheck %s
// TODO: Implement tuple equality in the library.
// BLOCKED: <rdar://problem/13822406>
func ~= (x: (Int, Int), y: (Int, Int)) -> Bool {
return x.0 == y.0 && x.1 == y.1
}
// Some fake predicates for pattern guards.
func runced() -> Bool { return true }
func funged() -> Bool { return true }
func ansed() -> Bool { return true }
func runced(x x: Int) -> Bool { return true }
func funged(x x: Int) -> Bool { return true }
func ansed(x x: Int) -> Bool { return true }
func foo() -> Int { return 0 }
func bar() -> Int { return 0 }
func foobar() -> (Int, Int) { return (0, 0) }
func foos() -> String { return "" }
func bars() -> String { return "" }
func a() {}
func b() {}
func c() {}
func d() {}
func e() {}
func f() {}
func g() {}
func a(x x: Int) {}
func b(x x: Int) {}
func c(x x: Int) {}
func d(x x: Int) {}
func a(x x: String) {}
func b(x x: String) {}
func aa(x x: (Int, Int)) {}
func bb(x x: (Int, Int)) {}
func cc(x x: (Int, Int)) {}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_1yyF
func test_var_1() {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK-NOT: br bb
case var x:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1byyF
b()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_2yyF
func test_var_2() {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch foo() {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
// -- TODO: Clean up these empty waypoint bbs.
case var x where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case var y where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: br [[CASE3:bb[0-9]+]]
case var z:
// CHECK: [[CASE3]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CONT]]
c(x: z)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1dyyF
d()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_3yyF
func test_var_3() {
// CHECK: function_ref @$S10switch_var3fooSiyF
// CHECK: function_ref @$S10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2aa1xySi_Sit_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[CONT:bb[0-9]+]]
aa(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: br [[NO_CASE1_TARGET:bb[0-9]+]]
// CHECK: [[NO_CASE1_TARGET]]:
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
a(x: y)
b(x: z)
// CHECK: [[NO_CASE2]]:
// CHECK: [[WADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 0
// CHECK: function_ref @$S10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case var w where ansed(x: w.0):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2bb1xySi_Sit_tF
// CHECK: br [[CONT]]
bb(x: w)
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case var v:
// CHECK: [[CASE4]]:
// CHECK: [[VADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%.*]] = project_box [[VADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[V]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var2cc1xySi_Sit_tF
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[CONT]]
cc(x: v)
}
// CHECK: [[CONT]]:
// CHECK: function_ref @$S10switch_var1dyyF
d()
}
protocol P { func p() }
struct X : P { func p() {} }
struct Y : P { func p() {} }
struct Z : P { func p() {} }
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_41pyAA1P_p_tF
func test_var_4(p p: P) {
// CHECK: function_ref @$S10switch_var3fooSiyF
switch (p, foo()) {
// CHECK: [[PAIR:%.*]] = alloc_stack $(P, Int)
// CHECK: store
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[T0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 1
// CHECK: [[PAIR_1:%.*]] = load [trivial] [[T0]] : $*Int
// CHECK: [[TMP:%.*]] = alloc_stack $X
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to X in [[TMP]] : $*X, [[IS_X:bb[0-9]+]], [[IS_NOT_X:bb[0-9]+]]
// CHECK: [[IS_X]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*X
// CHECK: [[XADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[X]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[X]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6runced1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case (is X, var x) where runced(x: x):
// CHECK: [[CASE1]]:
// CHECK: function_ref @$S10switch_var1a1xySi_tF
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[XADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_X]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[TMP:%.*]] = alloc_stack $Y
// CHECK: checked_cast_addr_br copy_on_success P in [[PAIR_0]] : $*P to Y in [[TMP]] : $*Y, [[IS_Y:bb[0-9]+]], [[IS_NOT_Y:bb[0-9]+]]
// CHECK: [[IS_Y]]:
// CHECK: [[T0:%.*]] = load [trivial] [[TMP]] : $*Y
// CHECK: [[YADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[Y:%.*]] = project_box [[YADDR]]
// CHECK: store [[PAIR_1]] to [trivial] [[Y]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var6funged1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (is Y, var y) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Y]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1b1xySi_tF
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[YADDR]]
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT:bb[0-9]+]]
// CHECK: [[IS_NOT_Y]]:
// CHECK: dealloc_stack [[TMP]]
// CHECK: br [[NEXT]]
// CHECK: [[NEXT]]:
// CHECK: [[ZADDR:%.*]] = alloc_box ${ var (P, Int) }
// CHECK: [[Z:%.*]] = project_box [[ZADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$S10switch_var5ansed1xSbSi_tF
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[DFLT_NO_CASE3:bb[0-9]+]]
case var z where ansed(x: z.1):
// CHECK: [[CASE3]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[Z]]
// CHECK: tuple_element_addr [[READ]] : {{.*}}, 1
// CHECK: function_ref @$S10switch_var1c1xySi_tF
// CHECK: destroy_value [[ZADDR]]
// CHECK-NEXT: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
c(x: z.1)
// CHECK: [[DFLT_NO_CASE3]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: br [[CASE4:bb[0-9]+]]
case (_, var w):
// CHECK: [[CASE4]]:
// CHECK: [[PAIR_0:%.*]] = tuple_element_addr [[PAIR]] : $*(P, Int), 0
// CHECK: [[WADDR:%.*]] = alloc_box ${ var Int }
// CHECK: [[W:%.*]] = project_box [[WADDR]]
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[W]]
// CHECK: load [trivial] [[READ]]
// CHECK: function_ref @$S10switch_var1d1xySi_tF
// CHECK: destroy_value [[WADDR]]
// CHECK: destroy_addr [[PAIR_0]] : $*P
// CHECK: dealloc_stack [[PAIR]]
// CHECK: br [[CONT]]
d(x: w)
}
e()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B2_5yyF : $@convention(thin) () -> () {
func test_var_5() {
// CHECK: function_ref @$S10switch_var3fooSiyF
// CHECK: function_ref @$S10switch_var3barSiyF
switch (foo(), bar()) {
// CHECK: [[XADDR:%.*]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%.*]] = project_box [[XADDR]]
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
case var x where runced(x: x.0):
// CHECK: [[CASE1]]:
// CHECK: br [[CONT:bb[0-9]+]]
a()
// CHECK: [[NO_CASE1]]:
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case (var y, var z) where funged(x: y):
// CHECK: [[CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[CONT]]
b()
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: cond_br {{%.*}}, [[CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
case (_, _) where runced():
// CHECK: [[CASE3]]:
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: br [[CASE4:bb[0-9]+]]
case _:
// CHECK: [[CASE4]]:
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
e()
}
// CHECK-LABEL: sil hidden @$S10switch_var05test_B7_returnyyF : $@convention(thin) () -> () {
func test_var_return() {
switch (foo(), bar()) {
case var x where runced():
// CHECK: [[XADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[X:%[0-9]+]] = project_box [[XADDR]]
// CHECK: function_ref @$S10switch_var1ayyF
// CHECK: destroy_value [[XADDR]]
// CHECK: br [[EPILOG:bb[0-9]+]]
a()
return
// CHECK: [[YADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Y:%[0-9]+]] = project_box [[YADDR]]
// CHECK: [[ZADDR:%[0-9]+]] = alloc_box ${ var Int }
// CHECK: [[Z:%[0-9]+]] = project_box [[ZADDR]]
case (var y, var z) where funged():
// CHECK: function_ref @$S10switch_var1byyF
// CHECK: destroy_value [[ZADDR]]
// CHECK: destroy_value [[YADDR]]
// CHECK: br [[EPILOG]]
b()
return
case var w where ansed():
// CHECK: [[WADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[W:%[0-9]+]] = project_box [[WADDR]]
// CHECK: function_ref @$S10switch_var1cyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[WADDR]]
// CHECK: br [[EPILOG]]
c()
return
case var v:
// CHECK: [[VADDR:%[0-9]+]] = alloc_box ${ var (Int, Int) }
// CHECK: [[V:%[0-9]+]] = project_box [[VADDR]]
// CHECK: function_ref @$S10switch_var1dyyF
// CHECK-NOT: destroy_value [[ZADDR]]
// CHECK-NOT: destroy_value [[YADDR]]
// CHECK: destroy_value [[VADDR]]
// CHECK: br [[EPILOG]]
d()
return
}
}
// When all of the bindings in a column are immutable, don't emit a mutable
// box. <rdar://problem/15873365>
// CHECK-LABEL: sil hidden @$S10switch_var8test_letyyF : $@convention(thin) () -> () {
func test_let() {
// CHECK: [[FOOS:%.*]] = function_ref @$S10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var6runcedSbyF
// CHECK: cond_br {{%.*}}, [[CASE1:bb[0-9]+]], [[NO_CASE1:bb[0-9]+]]
switch foos() {
case let x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[BORROWED_VAL_COPY]])
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NO_CASE1]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[TRY_CASE2:bb[0-9]+]]
// CHECK: [[TRY_CASE2]]:
// CHECK: [[VAL_COPY_2:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var6fungedSbyF
// CHECK: cond_br {{%.*}}, [[CASE2:bb[0-9]+]], [[NO_CASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY_2:%.*]] = begin_borrow [[VAL_COPY_2]]
// CHECK: [[B:%.*]] = function_ref @$S10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY_2]])
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NO_CASE2]]:
// CHECK: destroy_value [[VAL_COPY_2]]
// CHECK: br [[NEXT_CASE:bb6]]
// CHECK: [[NEXT_CASE]]:
// CHECK: [[VAL_COPY_3:%.*]] = copy_value [[VAL]]
// CHECK: function_ref @$S10switch_var4barsSSyF
// CHECK: [[BORROWED_VAL_COPY_3:%.*]] = begin_borrow [[VAL_COPY_3]]
// CHECK: store_borrow [[BORROWED_VAL_COPY_3]] to [[IN_ARG:%.*]] :
// CHECK: apply {{%.*}}<String>({{.*}}, [[IN_ARG]])
// CHECK: cond_br {{%.*}}, [[YES_CASE3:bb[0-9]+]], [[NO_CASE3:bb[0-9]+]]
// ExprPatterns implicitly contain a 'let' binding.
case bars():
// CHECK: [[YES_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @$S10switch_var1cyyF
// CHECK: br [[CONT]]
c()
// CHECK: [[NO_CASE3]]:
// CHECK: destroy_value [[VAL_COPY_3]]
// CHECK: br [[NEXT_CASE:bb9+]]
// CHECK: [[NEXT_CASE]]:
case _:
// CHECK: destroy_value [[VAL]]
// CHECK: function_ref @$S10switch_var1dyyF
// CHECK: br [[CONT]]
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$S10switch_var8test_letyyF'
// If one of the bindings is a "var", allocate a box for the column.
// CHECK-LABEL: sil hidden @$S10switch_var015test_mixed_let_B0yyF : $@convention(thin) () -> () {
func test_mixed_let_var() {
// CHECK: bb0:
// CHECK: [[FOOS:%.*]] = function_ref @$S10switch_var4foosSSyF
// CHECK: [[VAL:%.*]] = apply [[FOOS]]()
switch foos() {
// First pattern.
// CHECK: [[BOX:%.*]] = alloc_box ${ var String }, var, name "x"
// CHECK: [[PBOX:%.*]] = project_box [[BOX]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: store [[VAL_COPY]] to [init] [[PBOX]]
// CHECK: cond_br {{.*}}, [[CASE1:bb[0-9]+]], [[NOCASE1:bb[0-9]+]]
case var x where runced():
// CHECK: [[CASE1]]:
// CHECK: [[READ:%.*]] = begin_access [read] [unknown] [[PBOX]]
// CHECK: [[X:%.*]] = load [copy] [[READ]]
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySS_tF
// CHECK: apply [[A]]([[X]])
// CHECK: destroy_value [[BOX]]
// CHECK: br [[CONT:bb[0-9]+]]
a(x: x)
// CHECK: [[NOCASE1]]:
// CHECK: destroy_value [[BOX]]
// CHECK: br [[NEXT_PATTERN:bb[0-9]+]]
// CHECK: [[NEXT_PATTERN]]:
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: cond_br {{.*}}, [[CASE2:bb[0-9]+]], [[NOCASE2:bb[0-9]+]]
case let y where funged():
// CHECK: [[CASE2]]:
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: [[B:%.*]] = function_ref @$S10switch_var1b1xySS_tF
// CHECK: apply [[B]]([[BORROWED_VAL_COPY]])
// CHECK: end_borrow [[BORROWED_VAL_COPY]] from [[VAL_COPY]]
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: br [[CONT]]
b(x: y)
// CHECK: [[NOCASE2]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]
// CHECK: [[VAL_COPY:%.*]] = copy_value [[VAL]]
// CHECK: [[BORROWED_VAL_COPY:%.*]] = begin_borrow [[VAL_COPY]]
// CHECK: store_borrow [[BORROWED_VAL_COPY]] to [[TMP_VAL_COPY_ADDR:%.*]] :
// CHECK: apply {{.*}}<String>({{.*}}, [[TMP_VAL_COPY_ADDR]])
// CHECK: cond_br {{.*}}, [[CASE3:bb[0-9]+]], [[NOCASE3:bb[0-9]+]]
case bars():
// CHECK: [[CASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: destroy_value [[VAL]]
// CHECK: [[FUNC:%.*]] = function_ref @$S10switch_var1cyyF : $@convention(thin) () -> ()
// CHECK: apply [[FUNC]]()
// CHECK: br [[CONT]]
c()
// CHECK: [[NOCASE3]]:
// CHECK: destroy_value [[VAL_COPY]]
// CHECK: br [[NEXT_CASE:bb[0-9]+]]
// CHECK: [[NEXT_CASE]]:
// CHECK: destroy_value [[VAL]]
// CHECK: [[D_FUNC:%.*]] = function_ref @$S10switch_var1dyyF : $@convention(thin) () -> ()
// CHECK: apply [[D_FUNC]]()
// CHECK: br [[CONT]]
case _:
d()
}
// CHECK: [[CONT]]:
// CHECK: return
}
// CHECK: } // end sil function '$S10switch_var015test_mixed_let_B0yyF'
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns1yyF : $@convention(thin) () -> () {
func test_multiple_patterns1() {
// CHECK: function_ref @$S10switch_var6foobarSi_SityF
switch foobar() {
// CHECK-NOT: br bb
case (0, let x), (let x, 0):
// CHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// CHECK: [[FIRST_MATCH_CASE]]:
// CHECK: debug_value [[FIRST_X:%.*]] :
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// CHECK: [[FIRST_FAIL]]:
// CHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// CHECK: [[SECOND_MATCH_CASE]]:
// CHECK: debug_value [[SECOND_X:%.*]] :
// CHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// CHECK: [[A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// CHECK: [[SECOND_FAIL]]:
// CHECK: function_ref @$S10switch_var1byyF
b()
}
}
// FIXME(integers): the following checks should be updated for the new integer
// protocols. <rdar://problem/29939484>
// XCHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns2yyF : $@convention(thin) () -> () {
func test_multiple_patterns2() {
let t1 = 2
let t2 = 4
// XCHECK: debug_value [[T1:%.*]] :
// XCHECK: debug_value [[T2:%.*]] :
switch (0,0) {
// XCHECK-NOT: br bb
case (_, let x) where x > t1, (let x, _) where x > t2:
// XCHECK: [[FIRST_X:%.*]] = tuple_extract {{%.*}} : $(Int, Int), 1
// XCHECK: debug_value [[FIRST_X]] :
// XCHECK: apply {{%.*}}([[FIRST_X]], [[T1]])
// XCHECK: cond_br {{%.*}}, [[FIRST_MATCH_CASE:bb[0-9]+]], [[FIRST_FAIL:bb[0-9]+]]
// XCHECK: [[FIRST_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY:bb[0-9]+]]([[FIRST_X]] : $Int)
// XCHECK: [[FIRST_FAIL]]:
// XCHECK: debug_value [[SECOND_X:%.*]] :
// XCHECK: apply {{%.*}}([[SECOND_X]], [[T2]])
// XCHECK: cond_br {{%.*}}, [[SECOND_MATCH_CASE:bb[0-9]+]], [[SECOND_FAIL:bb[0-9]+]]
// XCHECK: [[SECOND_MATCH_CASE]]:
// XCHECK: br [[CASE_BODY]]([[SECOND_X]] : $Int)
// XCHECK: [[CASE_BODY]]([[BODY_VAR:%.*]] : $Int):
// XCHECK: [[A:%.*]] = function_ref @$S10switch_var1aySi1x_tF
// XCHECK: apply [[A]]([[BODY_VAR]])
a(x: x)
default:
// XCHECK: [[SECOND_FAIL]]:
// XCHECK: function_ref @$S10switch_var1byyF
b()
}
}
enum Foo {
case A(Int, Double)
case B(Double, Int)
case C(Int, Int, Double)
}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns3yyF : $@convention(thin) () -> () {
func test_multiple_patterns3() {
let f = Foo.C(0, 1, 2.0)
switch f {
// CHECK: switch_enum {{%.*}} : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
case .A(let x, let n), .B(let n, let x), .C(_, let x, let n):
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int, [[A_N]] : $Double)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int, [[B_N]] : $Double)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: [[C__:%.*]] = tuple_extract
// CHECK: [[C_X:%.*]] = tuple_extract
// CHECK: [[C_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[C_X]] : $Int, [[C_N]] : $Double)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int, [[BODY_N:%.*]] : $Double):
// CHECK: [[FUNC_A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
enum Bar {
case Y(Foo, Int)
case Z(Int, Foo)
}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns4yyF : $@convention(thin) () -> () {
func test_multiple_patterns4() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(let x, _), _), .Y(.B(_, let x), _), .Y(.C, let x), .Z(let x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: [[FUNC_A:%.*]] = function_ref @$S10switch_var1a1xySi_tF
// CHECK: apply [[FUNC_A]]([[BODY_X]])
a(x: x)
}
}
func aaa(x x: inout Int) {}
// CHECK-LABEL: sil hidden @$S10switch_var23test_multiple_patterns5yyF : $@convention(thin) () -> () {
func test_multiple_patterns5() {
let b = Bar.Y(.C(0, 1, 2.0), 3)
switch b {
// CHECK: switch_enum {{%.*}} : $Bar, case #Bar.Y!enumelt.1: [[Y:bb[0-9]+]], case #Bar.Z!enumelt.1: [[Z:bb[0-9]+]]
case .Y(.A(var x, _), _), .Y(.B(_, var x), _), .Y(.C, var x), .Z(var x, _):
// CHECK: [[Y]]({{%.*}} : $(Foo, Int)):
// CHECK: [[Y_F:%.*]] = tuple_extract
// CHECK: [[Y_X:%.*]] = tuple_extract
// CHECK: switch_enum [[Y_F]] : $Foo, case #Foo.A!enumelt.1: [[A:bb[0-9]+]], case #Foo.B!enumelt.1: [[B:bb[0-9]+]], case #Foo.C!enumelt.1: [[C:bb[0-9]+]]
// CHECK: [[A]]({{%.*}} : $(Int, Double)):
// CHECK: [[A_X:%.*]] = tuple_extract
// CHECK: [[A_N:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY:bb[0-9]+]]([[A_X]] : $Int)
// CHECK: [[B]]({{%.*}} : $(Double, Int)):
// CHECK: [[B_N:%.*]] = tuple_extract
// CHECK: [[B_X:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[B_X]] : $Int)
// CHECK: [[C]]({{%.*}} : $(Int, Int, Double)):
// CHECK: br [[CASE_BODY]]([[Y_X]] : $Int)
// CHECK: [[Z]]({{%.*}} : $(Int, Foo)):
// CHECK: [[Z_X:%.*]] = tuple_extract
// CHECK: [[Z_F:%.*]] = tuple_extract
// CHECK: br [[CASE_BODY]]([[Z_X]] : $Int)
// CHECK: [[CASE_BODY]]([[BODY_X:%.*]] : $Int):
// CHECK: store [[BODY_X]] to [trivial] [[BOX_X:%.*]] : $*Int
// CHECK: [[WRITE:%.*]] = begin_access [modify] [unknown] [[BOX_X]]
// CHECK: [[FUNC_AAA:%.*]] = function_ref @$S10switch_var3aaa1xySiz_tF
// CHECK: apply [[FUNC_AAA]]([[WRITE]])
aaa(x: &x)
}
}
// rdar://problem/29252758 -- local decls must not be reemitted.
func test_against_reemission(x: Bar) {
switch x {
case .Y(let a, _), .Z(_, let a):
let b = a
}
}
class C {}
class D: C {}
func f(_: D) -> Bool { return true }
// CHECK-LABEL: sil hidden @{{.*}}test_multiple_patterns_value_semantics
func test_multiple_patterns_value_semantics(_ y: C) {
switch y {
// CHECK: checked_cast_br {{%.*}} : $C to $D, [[AS_D:bb[0-9]+]], [[NOT_AS_D:bb[0-9]+]]
// CHECK: [[AS_D]]({{.*}}):
// CHECK: cond_br {{%.*}}, [[F_TRUE:bb[0-9]+]], [[F_FALSE:bb[0-9]+]]
// CHECK: [[F_TRUE]]:
// CHECK: [[BINDING:%.*]] = copy_value [[ORIG:%.*]] :
// CHECK: destroy_value [[ORIG]]
// CHECK: br {{bb[0-9]+}}([[BINDING]]
case let x as D where f(x), let x as D: break
default: break
}
}
|
apache-2.0
|
41d7908dc3593163430eeea3bf19dab2
| 36.226667 | 161 | 0.510172 | 2.860656 | false | false | false | false |
quran/quran-ios
|
Sources/Caching/Cache.swift
|
1
|
3098
|
//
// Cache.swift
// Quran
//
// Created by Mohamed Afifi on 11/1/16.
//
// Quran for iOS is a Quran reading application for iOS.
// Copyright (C) 2017 Quran.com
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
import Foundation
import UIKit
private class ObjectWrapper {
let value: Any
init(_ value: Any) {
self.value = value
}
}
private class KeyWrapper<KeyType: Hashable>: NSObject {
let key: KeyType
init(_ key: KeyType) {
self.key = key
}
override var hash: Int {
key.hashValue
}
override func isEqual(_ object: Any?) -> Bool {
guard let other = object as? KeyWrapper<KeyType> else {
return false
}
return key == other.key
}
}
open class Cache<KeyType: Hashable, ObjectType> {
private let cache: NSCache<KeyWrapper<KeyType>, ObjectWrapper> = NSCache()
public init(lowMemoryAware: Bool = true) {
guard lowMemoryAware else { return }
NotificationCenter.default.addObserver(
self,
selector: #selector(onLowMemory),
name: UIApplication.didReceiveMemoryWarningNotification,
object: nil
)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
@objc
private func onLowMemory() {
removeAllObjects()
}
open var name: String {
get { cache.name }
set { cache.name = newValue }
}
open weak var delegate: NSCacheDelegate? {
get { cache.delegate }
set { cache.delegate = newValue }
}
open func object(forKey key: KeyType) -> ObjectType? {
cache.object(forKey: KeyWrapper(key))?.value as? ObjectType
}
open func setObject(_ obj: ObjectType, forKey key: KeyType) { // 0 cost
cache.setObject(ObjectWrapper(obj), forKey: KeyWrapper(key))
}
open func setObject(_ obj: ObjectType, forKey key: KeyType, cost: Int) {
cache.setObject(ObjectWrapper(obj), forKey: KeyWrapper(key), cost: cost)
}
open func removeObject(forKey key: KeyType) {
cache.removeObject(forKey: KeyWrapper(key))
}
open func removeAllObjects() {
cache.removeAllObjects()
}
open var totalCostLimit: Int {
get { cache.totalCostLimit }
set { cache.totalCostLimit = newValue }
}
open var countLimit: Int {
get { cache.countLimit }
set { cache.countLimit = newValue }
}
open var evictsObjectsWithDiscardedContent: Bool {
get { cache.evictsObjectsWithDiscardedContent }
set { cache.evictsObjectsWithDiscardedContent = newValue }
}
}
|
apache-2.0
|
ac2e6d6714e64c473d3d6375c1d79c79
| 25.706897 | 80 | 0.64009 | 4.320781 | false | false | false | false |
muukii/PhotosProvider
|
PhotosProvider/Classes/PhotosProviderMonitor.swift
|
3
|
1139
|
//
// Monitor.swift
// PhotosProvider
//
// Created by Muukii on 8/7/15.
// Copyright © 2015 muukii. All rights reserved.
//
import Foundation
import Photos
class PhotosProviderMonitor {
var photosDidChange: ((PHChange) -> Void)?
private(set) var isObserving: Bool = false
func startObserving() {
isObserving = true
PHPhotoLibrary.shared().register(self.photosLibraryObserver)
}
func endObserving() {
isObserving = false
PHPhotoLibrary.shared().unregisterChangeObserver(self.photosLibraryObserver)
}
private lazy var photosLibraryObserver: PhotosLibraryObserver = { [weak self] in
let observer = PhotosLibraryObserver()
observer.didChange = { change in
self?.photosDidChange?(change)
}
return observer
}()
}
fileprivate class PhotosLibraryObserver: NSObject, PHPhotoLibraryChangeObserver {
var didChange: ((PHChange) -> Void)?
@objc fileprivate func photoLibraryDidChange(_ changeInstance: PHChange) {
didChange?(changeInstance)
}
}
|
mit
|
436ba8d8c58234c7febd81bfd771d558
| 23.212766 | 84 | 0.642355 | 5.057778 | false | false | false | false |
brunodlz/Couch
|
Couch/Couch/Extension/Date+Extension.swift
|
1
|
1306
|
import Foundation
enum FormatterDate: String {
case server = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
case day = "yyyy/MM/dd"
}
extension Date {
func convertDate(To string: String?) -> DateComponents? {
guard let dateString = string else { return nil }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = FormatterDate.server.rawValue
dateFormatter.timeZone = NSTimeZone(name: "UTC") as TimeZone!
guard let endDate = dateFormatter.date(from: dateString) else { return nil }
let cal = Calendar.current
let unit:NSCalendar.Unit = NSCalendar.Unit(rawValue: UInt.max)
return (cal as NSCalendar).components(unit, from: endDate)
}
func convertString(To dateComponents: DateComponents?, mask: FormatterDate) -> String {
guard let dateComponents = dateComponents else { fatalError("dateComponents is nil") }
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = mask.rawValue
dateFormatter.locale = Locale(identifier: "pt_BR")
let calendar = Calendar.current
guard let date = calendar.date(from: dateComponents) else { fatalError("mask is incorrect") }
return dateFormatter.string(from: date)
}
}
|
mit
|
efaa0f3dc6821029112f073352165820
| 35.277778 | 101 | 0.651608 | 4.783883 | false | true | false | false |
exchangegroup/paged-scroll-view-with-images
|
paged-scroll-view-with-images/TegArray.swift
|
2
|
1346
|
//
// Helper functions to work with arrays.
//
import Foundation
public struct TegArray {
public static func getByIndex<T>(index: Int, array: [T]) -> T? {
if index < 0 || index >= array.count { return nil }
return array[index]
}
public static func uniq<S: SequenceType, E: Hashable where E==S.Generator.Element>(source: S) -> [E] {
var seen: [E:Bool] = [:]
return filter(source) { seen.updateValue(true, forKey: $0) == nil }
}
// Returns the first element for which the condition is true
public static func firstWhere<T>(array: [T], condition: (T)->(Bool)) -> T? {
for item in array {
if condition(item) {
return item
}
}
return nil
}
public static func removeAtIndexSafe<T>(index: Int, inout array: [T]) {
if index < 0 || index >= array.count { return }
array.removeAtIndex(index)
}
public static func convert<T>(array: [AnyObject]) -> [T] {
var result = [T]()
for item in array {
if let item = item as? T {
result.append(item)
}
}
return result
}
// Convert NSArray to Swift array
public static func convertNSArray<T>(arr: NSArray) -> [T] {
var result = [T]()
for obj in arr {
if let objCast = obj as? T {
result.append(objCast)
}
}
return result
}
}
|
mit
|
e1849558e7b83290353d6b859c346bbf
| 22.206897 | 104 | 0.581724 | 3.687671 | false | false | false | false |
sunweifeng/SWFKit
|
SWFKit/Classes/Utils/PageManager.swift
|
1
|
950
|
//
// PageManager.swift
// SWFKit
//
// Created by 孙伟峰 on 2017/6/19.
// Copyright © 2017年 Sun Weifeng. All rights reserved.
//
import UIKit
public class PageManager: NSObject {
public class func topMostController() -> UIViewController? {
var topController: UIViewController?
topController = (UIApplication.shared.keyWindow?.rootViewController as? UINavigationController)?.topViewController
guard topController != nil else {
return nil
}
while (topController!.presentedViewController != nil) {
topController = topController!.presentedViewController
if topController!.isKind(of: UINavigationController.self) {
if let vc = topController as? UINavigationController {
topController = vc.topViewController
}
}
}
return topController
}
}
|
mit
|
c93e7e73ab4e1c085712ce20cc4fedee
| 28.40625 | 122 | 0.612115 | 5.668675 | false | false | false | false |
Josscii/iOS-Demos
|
UIBarButtonItemPositionDemo/UIBarButtonItemPositionDemo/ViewController2.swift
|
1
|
1382
|
//
// ViewController2.swift
// UIBarButtonItemPositionDemo
//
// Created by josscii on 2017/11/7.
// Copyright © 2017年 josscii. All rights reserved.
//
import UIKit
/*
自定义 leftBarButtonItem,缺点很明显,滑动返回会失效,不建议使用
*/
class ViewController2: UIViewController, UIGestureRecognizerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
// navigationItem.hidesBackButton = true
// let button = UIButton(frame: CGRect(x: 0, y: 0, width: 100, height: 44))
// button.setTitle("back", for: .normal)
// button.setTitleColor(.black, for: .normal)
// button.contentHorizontalAlignment = .left
// button.titleEdgeInsets.left = -8
// button.backgroundColor = .red
// button.addTarget(self, action: #selector(pop), for: .touchUpInside)
// let leftbarbuttonitem = UIBarButtonItem(customView: button)
// navigationItem.leftBarButtonItem = leftbarbuttonitem
}
@objc func pop() {
navigationController?.popViewController(animated: true)
}
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
// navigationController?.interactivePopGestureRecognizer?.delegate = self as UIGestureRecognizerDelegate
}
}
|
mit
|
db1a85ba9bc3cad1f116f557d5eab68b
| 30 | 111 | 0.670668 | 4.428571 | false | false | false | false |
Josscii/iOS-Demos
|
CoreAnimationDemo.playground/Contents.swift
|
1
|
1097
|
//: A UIKit based Playground for presenting user interface
import UIKit
import PlaygroundSupport
class MyViewController : UIViewController {
var label: UIView!
override func loadView() {
let view = UIView()
view.backgroundColor = .white
label = UIView()
label.frame = CGRect(x: 150, y: 200, width: 200, height: 20)
label.backgroundColor = .red
view.addSubview(label)
self.view = view
}
override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
let animation = CABasicAnimation(keyPath: "backgroundColor")
animation.fromValue = UIColor.yellow.cgColor
animation.toValue = UIColor.green.cgColor
animation.beginTime = CACurrentMediaTime() + 2
animation.duration = 5
animation.fillMode = kCAFillModeForwards
// animation.isRemovedOnCompletion = false
label.layer.add(animation, forKey: nil)
}
}
// Present the view controller in the Live View window
PlaygroundPage.current.liveView = MyViewController()
|
mit
|
13f195ed57548b6d26583c6991cdff55
| 30.342857 | 79 | 0.655424 | 5.150235 | false | false | false | false |
BennyKJohnson/OpenCloudKit
|
Sources/CKQueryOperation.swift
|
1
|
4361
|
//
// CKQueryOperation.swift
// OpenCloudKit
//
// Created by Benjamin Johnson on 7/07/2016.
//
//
import Foundation
let CKQueryOperationMaximumResults = 0
public class CKQueryOperation: CKDatabaseOperation {
public override init() {
super.init()
}
public convenience init(query: CKQuery) {
self.init()
self.query = query
}
public convenience init(cursor: CKQueryCursor) {
self.init()
self.cursor = cursor
}
public var shouldFetchAssetContent = true
public var query: CKQuery?
public var cursor: CKQueryCursor?
public var resultsCursor: CKQueryCursor?
var isFinishing: Bool = false
public var zoneID: CKRecordZoneID?
public var resultsLimit: Int = CKQueryOperationMaximumResults
public var desiredKeys: [String]?
public var recordFetchedBlock: ((CKRecord) -> Swift.Void)?
public var queryCompletionBlock: ((CKQueryCursor?, Error?) -> Swift.Void)?
override func CKOperationShouldRun() throws {
// "Warn: There's no point in running a query if there are no progress or completion blocks set. Bailing early."
if(query == nil && cursor == nil){
throw CKPrettyError(code: CKErrorCode.InvalidArguments, description: "either a query or query cursor must be provided for \(self)")
}
}
override func finishOnCallbackQueue(error: Error?) {
// log "Operation %@ has completed. Query cursor is %@.%@%@"
self.queryCompletionBlock?(self.resultsCursor, error)
super.finishOnCallbackQueue(error: error)
}
func fetched(record: CKRecord){
callbackQueue.async {
self.recordFetchedBlock?(record)
}
}
override func performCKOperation() {
let queryOperationURLRequest = CKQueryURLRequest(query: query!, cursor: cursor?.data.bridge(), limit: resultsLimit, requestedFields: desiredKeys, zoneID: zoneID)
queryOperationURLRequest.accountInfoProvider = CloudKit.shared.defaultAccount
queryOperationURLRequest.databaseScope = database?.scope ?? .public
queryOperationURLRequest.completionBlock = { [weak self] (result) in
guard let strongSelf = self, !strongSelf.isCancelled else {
return
}
switch result {
case .success(let dictionary):
// Process cursor
if let continuationMarker = dictionary["continuationMarker"] as? String {
#if os(Linux)
let data = NSData(base64Encoded: continuationMarker, options: [])
#else
let data = NSData(base64Encoded: continuationMarker)
#endif
if let data = data {
strongSelf.resultsCursor = CKQueryCursor(data: data, zoneID: CKRecordZoneID(zoneName: "_defaultZone", ownerName: ""))
}
}
// Process Records
if let recordsDictionary = dictionary["records"] as? [[String: Any]] {
// Parse JSON into CKRecords
for recordDictionary in recordsDictionary {
if let record = CKRecord(recordDictionary: recordDictionary) {
// Call RecordCallback
strongSelf.fetched(record: record)
} else {
// Create Error
// Invalid state to be in, this operation normally doesnt provide partial errors
let error = NSError(domain: CKErrorDomain, code: CKErrorCode.PartialFailure.rawValue, userInfo: [NSLocalizedDescriptionKey: "Failed to parse record from server"])
strongSelf.finish(error: error)
return
}
}
}
strongSelf.finish(error: nil)
case .error(let error):
strongSelf.finish(error: error.error)
}
}
queryOperationURLRequest.performRequest()
}
}
|
mit
|
f22bb4a6506522588105dbd4ae07e7b5
| 33.338583 | 190 | 0.559505 | 5.634367 | false | false | false | false |
Kruks/FindViewControl
|
FindViewControl/FindViewControl/ObjectClasses/Photo.swift
|
1
|
2448
|
//
// Photo.swift
//
// Create by Krutika Mac Mini on 27/12/2016
// Copyright © 2016. All rights reserved.
// Model file Generated using JSONExport: https://github.com/Ahmed-Ali/JSONExport
import Foundation
class Photo: NSObject {
var height: Int!
var htmlAttributions: [String]!
var photoReference: String!
var width: Int!
/**
* Instantiate the instance using the passed dictionary values to set the properties values
*/
init(fromDictionary dictionary: NSDictionary) {
height = dictionary["height"] as? Int
htmlAttributions = dictionary["html_attributions"] as? [String]
photoReference = dictionary["photo_reference"] as? String
width = dictionary["width"] as? Int
}
/**
* Returns all the available property values in the form of NSDictionary object where the key is the approperiate json key and the value is the value of the corresponding property
*/
func toDictionary() -> NSDictionary {
let dictionary = NSMutableDictionary()
if height != nil {
dictionary["height"] = height
}
if htmlAttributions != nil {
dictionary["html_attributions"] = htmlAttributions
}
if photoReference != nil {
dictionary["photo_reference"] = photoReference
}
if width != nil {
dictionary["width"] = width
}
return dictionary
}
/**
* NSCoding required initializer.
* Fills the data from the passed decoder
*/
@objc required init(coder aDecoder: NSCoder) {
height = aDecoder.decodeObject(forKey: "height") as? Int
htmlAttributions = aDecoder.decodeObject(forKey: "html_attributions") as? [String]
photoReference = aDecoder.decodeObject(forKey: "photo_reference") as? String
width = aDecoder.decodeObject(forKey: "width") as? Int
}
/**
* NSCoding required method.
* Encodes mode properties into the decoder
*/
@objc func encodeWithCoder(aCoder: NSCoder) {
if height != nil {
aCoder.encode(height, forKey: "height")
}
if htmlAttributions != nil {
aCoder.encode(htmlAttributions, forKey: "html_attributions")
}
if photoReference != nil {
aCoder.encode(photoReference, forKey: "photo_reference")
}
if width != nil {
aCoder.encode(width, forKey: "width")
}
}
}
|
mit
|
d3f3b3e3c4c388c2dee90ad5ef0e0b26
| 29.209877 | 180 | 0.624029 | 4.616981 | false | false | false | false |
mkyt/LrcShow
|
LrcShow/Lyrics.swift
|
1
|
9455
|
//
// Lyrics.swift
// LrcShow
//
// Created by Masahiro Kiyota on 2016/07/16.
// Copyright © 2016 Juzbox. All rights reserved.
//
import Foundation
enum LyricsKind: String {
case karaoke = "kra"
case synced = "lrc"
case unsynced = "txt"
}
/*
Lyrics line and element (collectively denoted as chunk)
*/
protocol LyricsChunk {
var text: String { get }
var timeCode: Double { get }
}
class LyricsElement: LyricsChunk {
var text: String
var timeCode: Double
var range: NSRange
init(text s: String, timeCode c: Double, startPos p: Int) {
text = s
timeCode = c
range = NSMakeRange(p, s.count)
}
convenience init(text s: String, startPos p: Int) {
self.init(text: s, timeCode: 0, startPos: p)
}
convenience init(line s: String, match m: NSTextCheckingResult, startPos p: Int) {
// [mm:ss:cc]text
let nsS = s as NSString
let min = nsS.substring(with: m.range(at: 1))
let sec = nsS.substring(with: m.range(at: 2))
let cenSec = nsS.substring(with: m.range(at: 3))
let text = nsS.substring(with: m.range(at: 4))
var time: Double = 0.0
time += 60 * Double(min)!
time += Double(sec)!
time += 0.01 * Double(cenSec)!
self.init(text: text, timeCode: time, startPos: p)
}
}
class LyricsLine: LyricsChunk {
var elements: [LyricsElement]
init?(karaokeLine line:String, startPos p: Int) {
elements = []
let re = try! NSRegularExpression(pattern: "[\\[<](\\d{2}):(\\d{2})[:\\.](\\d{2})[\\]>]([^\\[<]*)", options: [])
let matches = re.matches(in: line, options: [], range: NSMakeRange(0, line.count))
if matches.count == 0 {
return nil
}
var cur = p
for match in matches {
let elem = LyricsElement(line: line, match: match, startPos: cur)
elements.append(elem)
cur += elem.text.count
}
}
init?(syncedLine line: String, startPos p: Int) {
elements = []
let re = try! NSRegularExpression(pattern: "^\\[(\\d{2}):(\\d{2})[:\\.](\\d{2})\\](.*)$", options: [])
let match = re.firstMatch(in: line, options: [], range: NSMakeRange(0, line.count))
if let match = match {
elements.append(LyricsElement(line: line, match: match, startPos: p))
} else {
return nil
}
}
init(unsyncedLine line: String) {
elements = []
elements.append(LyricsElement(text: line, startPos: 0))
}
var text: String {
return elements.map{ $0.text }.joined(separator: "")
}
var timeCode: Double {
if elements.count == 0 {
return 0
} else {
return elements[0].timeCode
}
}
var range: NSRange {
if elements.count == 0 {
return NSMakeRange(0, 0)
} else {
let firstElemRange = elements[0].range
let lastElemRange = elements[elements.count - 1].range
return NSMakeRange(firstElemRange.location,
lastElemRange.location + lastElemRange.length - firstElemRange.location)
}
}
}
/*
Lyrics file object
*/
typealias LyricsPosition = (line: Int, elem: Int, char: Int)
typealias LyricsMarking = (
finishedLines: NSRange,
currentLine: NSRange,
finishedChunkInCurrentLine: NSRange,
futureChunkInCurrentLine: NSRange,
futureLines: NSRange
)
typealias SearchIndexEntry = (Double, Int, Int)
class LyricsFile {
var rawContent: String
var lines: [LyricsLine]
var searchIndex: [SearchIndexEntry]
var _text: String?
var text: String {
if _text == nil {
_text = lines.map{ $0.text }.joined(separator: "\n")
}
return _text!
}
init(file fileURL: URL) {
rawContent = try! String.init(contentsOf: fileURL)
lines = []
searchIndex = []
_text = nil
}
class func lyricsForMusicFileURL(_ musicFileURL: URL) -> LyricsFile? {
let pathWoExt: NSString = (musicFileURL.path as NSString).deletingPathExtension as NSString
let fm = FileManager.default
for ext in [LyricsKind.karaoke, LyricsKind.synced, LyricsKind.unsynced] {
let candidatePath = pathWoExt.appendingPathExtension(ext.rawValue)!
if (fm.fileExists(atPath: candidatePath)) {
switch ext {
case .karaoke:
return KaraokeLyricsFile(file: URL(fileURLWithPath: candidatePath))
case .synced:
return SyncedLyricsFile(file: URL(fileURLWithPath: candidatePath))
case .unsynced:
return UnsyncedLyricsFile(file: URL(fileURLWithPath: candidatePath))
}
}
}
return nil
}
var kind: LyricsKind { return .unsynced }
func position(time target: Double) -> LyricsPosition {
if kind == .unsynced {
return (0, 0, 0)
}
if searchIndex.count < 1 || target < searchIndex[0].0 {
return (-1, 0, 0)
}
var lo = 0, hi = searchIndex.count
while hi - lo > 1 {
let mid = Int((hi + lo) / 2)
let t = searchIndex[mid].0
if t > target {
hi = mid
} else {
lo = mid
}
}
let lineIndex = searchIndex[lo].1
let elemIndex = searchIndex[lo].2
if kind == .synced {
return (lineIndex, elemIndex, 0)
}
// Karaoke
let elem = lines[lineIndex].elements[elemIndex]
let start = elem.timeCode
var charIndex = 0
if elemIndex < lines[lineIndex].elements.count - 1 {
let nextElem = lines[lineIndex].elements[elemIndex + 1]
let end = nextElem.timeCode
let timePerChar = (end - start) / Double(elem.text.count)
charIndex = Int((target - start) / timePerChar)
} else if lineIndex < lines.count - 1 { // last element in current line
let nextElem = lines[lineIndex + 1].elements[0]
let end = nextElem.timeCode
let timePerChar = (end - start) / Double(elem.text.count)
charIndex = Int((target - start) / timePerChar)
} else { // last element of the whole lyrics
charIndex = 0
}
return (lineIndex, elemIndex, charIndex)
}
func marking(position pos: LyricsPosition) -> LyricsMarking {
var res: LyricsMarking
let endPos = text.count
if pos.line < 0 {
res.finishedLines = NSMakeRange(0, 0)
res.currentLine = NSMakeRange(0, 0)
res.futureLines = NSMakeRange(0, endPos)
res.finishedChunkInCurrentLine = NSMakeRange(0, 0)
res.futureChunkInCurrentLine = NSMakeRange(0, 0)
return res
}
let line = lines[pos.line]
res.finishedLines = NSMakeRange(0, line.range.location)
res.currentLine = line.range
let futureLineStart = line.range.location + line.range.length
res.futureLines = NSMakeRange(futureLineStart, endPos - futureLineStart)
res.finishedChunkInCurrentLine = NSMakeRange(0, 0)
res.futureChunkInCurrentLine = NSMakeRange(0, 0)
if kind == .karaoke {
let elem = line.elements[pos.elem]
let offset = pos.char
res.finishedChunkInCurrentLine = NSMakeRange(line.range.location, elem.range.location - line.range.location + offset)
res.futureChunkInCurrentLine = NSMakeRange(elem.range.location + offset, line.range.length - (elem.range.location - line.range.location + offset))
}
return res
}
}
class KaraokeLyricsFile: LyricsFile {
override init(file fileURL: URL) {
super.init(file: fileURL)
var p = 0
for rawLine in rawContent.components(separatedBy: "\n") {
let line = LyricsLine(karaokeLine: rawLine, startPos: p)
if let line = line {
lines.append(line)
p += line.text.count
p += 1 // new line
}
}
for (i, line) in lines.enumerated() {
for (j, elem) in line.elements.enumerated() {
searchIndex.append((elem.timeCode, i, j))
}
}
}
override var kind: LyricsKind { return .karaoke }
}
class SyncedLyricsFile: LyricsFile {
override init(file fileURL: URL) {
super.init(file: fileURL)
var p = 0
for rawLine in rawContent.components(separatedBy: "\n") {
let line = LyricsLine(syncedLine: rawLine, startPos: p)
if let line = line {
lines.append(line)
p += line.text.count
p += 1 // new line
}
}
for (i, line) in lines.enumerated() {
searchIndex.append((line.timeCode, i, 0))
}
}
override var kind: LyricsKind { return .synced }
}
class UnsyncedLyricsFile: LyricsFile {
override init(file fileURL: URL) {
super.init(file: fileURL)
for line in rawContent.components(separatedBy: "\n") {
lines.append(LyricsLine(unsyncedLine: line))
}
}
override var kind: LyricsKind { return .unsynced }
}
|
mit
|
26eeaba75fc9ace89469e0d5049dee3c
| 31.376712 | 158 | 0.563465 | 4.067986 | false | false | false | false |
vimeo/VimeoUpload
|
Examples/VimeoUpload-iOS-OldUpload/VimeoUpload-iOS-OldUpload/AppDelegate.swift
|
1
|
4134
|
//
// AppDelegate.swift
// VimeoUpload
//
// Created by Hanssen, Alfie on 10/14/15.
// Copyright © 2015 Vimeo. All rights reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//
import UIKit
import Photos
import VimeoNetworking
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate
{
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool
{
_ = VimeoReachabilityProvider.isReachable // Intialize reachability manager listening
OldVimeoUploader.sharedInstance?.applicationDidFinishLaunching() // Ensure init is called on launch
let settings = UIUserNotificationSettings(types: .alert, categories: nil)
application.registerUserNotificationSettings(settings)
let cameraRollViewController = CameraRollViewController(nibName: BaseCameraRollViewController.NibName, bundle:Bundle.main)
let uploadsViewController = UploadsViewController(nibName: UploadsViewController.NibName, bundle:Bundle.main)
let cameraNavController = UINavigationController(rootViewController: cameraRollViewController)
cameraNavController.tabBarItem.title = "Camera Roll"
let uploadsNavController = UINavigationController(rootViewController: uploadsViewController)
uploadsNavController.tabBarItem.title = "Uploads"
let tabBarController = UITabBarController()
tabBarController.viewControllers = [cameraNavController, uploadsNavController]
tabBarController.selectedIndex = 1
let frame = UIScreen.main.bounds
self.window = UIWindow(frame: frame)
self.window?.rootViewController = tabBarController
self.window?.makeKeyAndVisible()
self.requestCameraRollAccessIfNecessary()
return true
}
func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping () -> Void)
{
guard let descriptorManager = OldVimeoUploader.sharedInstance?.descriptorManager else
{
return
}
if descriptorManager.canHandleEventsForBackgroundURLSession(withIdentifier: identifier)
{
descriptorManager.handleEventsForBackgroundURLSession(completionHandler: completionHandler)
}
}
private func requestCameraRollAccessIfNecessary()
{
PHPhotoLibrary.requestAuthorization { status in
switch status
{
case .authorized:
print("Camera roll access granted")
case .restricted:
print("Unable to present camera roll. Camera roll access restricted.")
case .denied:
print("Unable to present camera roll. Camera roll access denied.")
default:
// place for .NotDetermined - in this callback status is already determined so should never get here
break
}
}
}
}
|
mit
|
21eab886fc88db489ed84e785d16958f
| 41.173469 | 147 | 0.709654 | 5.646175 | false | false | false | false |
hebertialmeida/ModelGen
|
Sources/ModelGenKit/JsonParser+Context.swift
|
1
|
4314
|
//
// JsonParser+Context.swift
// ModelGen
//
// Created by Heberti Almeida on 2017-05-10.
// Copyright © 2017 ModelGen. All rights reserved.
//
import Foundation
extension JsonParser {
public func stencilContextFor(_ language: Language) throws -> JSON {
try dicToArray()
try mapProperties()
try prepareContextFor(language)
return [
"spec": json,
"nestedObjects": hasNestedObjects()
]
}
// MARK: Prepare JSON to be used by template
private func dicToArray() throws {
guard let items = json["properties"] as? JSON else {
throw JsonParserError.missingProperties
}
var properties = [JSON]()
for (key, value) in items.sorted(by: { $0.key < $1.key }) {
guard let value = value as? JSON else {
throw JsonParserError.missingProperties
}
var nValue = value
nValue["name"] = key
properties.append(nValue)
}
json["properties"] = properties
}
private func mapProperties() throws {
guard let items = json["properties"] as? [JSON] else {
throw JsonParserError.missingProperties
}
properties = try items.map { try SchemaProperty(from: $0) }
}
private func prepareContextFor(_ language: Language) throws {
guard let items = json["properties"] as? [JSON] else {
throw JsonParserError.missingProperties
}
var required = [String]()
if let requiredItems = json["required"] as? [String] {
required = requiredItems
}
var imports: [String] = []
var elements = items
for index in elements.indices {
guard let name = elements[index]["name"] as? String else {
throw JsonParserError.missingProperties
}
let property = properties[index]
elements[index]["type"] = try Schema.matchTypeFor(property, language: language)
elements[index]["name"] = standardName(name)
elements[index]["key"] = name
elements[index]["array"] = property.type == "array"
elements[index]["nestedObject"] = hasNestedObjects(property)
elements[index]["required"] = required.contains(name)
elements[index]["keyPath"] = name.contains(".")
elements[index]["primitiveType"] = try Schema.isPrimitiveTypeFor(property, language: language)
imports.append(contentsOf: try Schema.matchPackageTypeFor(property, language: language))
if let ref = property.ref {
elements[index]["refType"] = try Schema.matchRefType(ref, language: language)
}
if let ref = property.items?.ref {
elements[index]["refType"] = try Schema.matchRefType(ref, language: language)
}
}
json["properties"] = elements
json["imports"] = imports.removeDuplicates().sorted(by: { $0 < $1 })
json["modifiedProperties"] = elements.filter({
guard let name = $0["name"] as? String, let key = $0["key"] as? String else {
return false
}
return name != key
})
}
private func standardName(_ name: String) -> String {
let splitedName = name.components(separatedBy: ".")
guard splitedName.count > 0, let last = splitedName.last else {
return fixVariableName(name)
}
return fixVariableName(last)
}
// MARK: Recursively check for nested objects
private func hasNestedObjects() -> Bool {
var references = 0
for property in properties {
if hasNestedObjects(property) {
references += 1
}
}
return references > 0
}
private func hasNestedObjects(_ property: SchemaProperty) -> Bool {
if property.ref != nil {
return true
}
if let items = property.items {
return items.ref != nil ? true : hasNestedObjects(items)
}
if let additionalProperties = property.additionalProperties {
return additionalProperties.ref != nil ? true : hasNestedObjects(additionalProperties)
}
return false
}
}
|
mit
|
f50ed0d5d2dcb7327f2034bcc7408a9c
| 32.434109 | 106 | 0.578252 | 4.776301 | false | false | false | false |
ikiapps/IKILogger
|
Sources/IKILogger.swift
|
1
|
10058
|
//
// IKILogger.swift
//
// version 1.0.0
//
// The MIT License (MIT)
// Copyright (c) 2016 ikiApps LLC.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
import Foundation
#if CRASHLYTICS
import Crashlytics
#endif
/**
This library provides DLog style debugging for Swift, with or without Crashlytics.
IKILogger lets you tag debugging output with colored symbols and keeps the logging
from printing to stdout so that it is not seen by end users.
Dates are added to logging commands to give them context in time. Additionally,
logging output can be suppressed by a date cutoff.
IKILogger previously had color output support from the XcodeColors plugin.
See https://github.com/robbiehanson/XcodeColors.
With Xcode 8, plugins are no longer supported. That is the reason for using emoji
symbols to represent different color states.
Colored debugging logging enhances logs by adding an extra dimension of
debugging data that can be quickly discerned without reading. This is especially
useful for those that associate meanings to colors.
In this library, the meaning of CRITICAL is assigned to the color red and the
double exclamation symbol (!!). This color value will always be logged and is,
therefore, useful for printing NSError occurrences.
Output is passed to Crashlytics logging. See
https://docs.fabric.io/apple/crashlytics/enhanced-reports.html#custom-logs.
Crashlytics will be used if -DCRASHLYTICS is set for the current build target.
If Crashlytics is not in use, then output will only be shown when -DDEBUG is set
in the Swift compiler flags under Build Settings for the Xcode target.
Usage Examples:
dLog("data \(data)", date: "2016-Jul-28");
dLogYellow("", date: "2016-Jul-28")
dLogRed("error \(error)", date: "2016-Jul-28");
*/
/// Flag to enable logging output through IKILogger.
public var ikiLogger_enabled = true
/// Cut off output that has a logging date before this date. The format of this string is "yyyy-MMM-dd".
public var ikiLogger_suppressBeforeDate = "2000-Jan-01"
/// A prefix that can be used for filtering output.
public var ikiLogger_prefix = "ikiApps"
/// Determine whether or not Crashlytics will be used for logging.
#if CRASHLYTICS
public var ikiLogger_useCrashlytics = true
#else
public var ikiLogger_useCrashlytics = false
#endif
/// Determine whether or not to use color output.
public var ikiLogger_useColor = false
let ESCAPE = "\u{001b}["
let RESET_FG = "\u{001b}[" + "fg;" // Clear any foreground color.
let RESET_BG = "\u{001b}[" + "bg;" // Clear any background color.
let RESET = "\u{001b}[" + ";" // Clear any foreground or background color.
/// Old colors kept for reference.
struct LogColor {
static let critical = "bg220,100,100;" // Messages using this color will always be logged.
static let important = "bg255,212,120;"
static let highlighted = "bg255,252,120;"
static let reviewed = "bg213,251,120;"
static let valuable = "bg118,214,255;"
static let toBeReviewed = "bg215,131,255;"
static let notImportant = "bg192,192,192;"
static let none = "fg0,34,98;"
}
struct LogSymbol {
static let critical = "‼️" // Messages using this color will always be logged.
static let important = "✴️" // Eight point star.
static let highlighted = "💛"
static let reviewed = "✅"
static let valuable = "💙"
static let toBeReviewed = "💜"
static let notImportant = "❔"
static let none = "⬜️"
}
public func dLog(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.none, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogRed(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.critical, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogOrange(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.important, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogYellow(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.highlighted, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogGreen(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.reviewed, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogBlue(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.valuable, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogPurple(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.toBeReviewed, message: message, date: date, filename: filename, function: function, line: line)
}
public func dLogGray(message: String?, date: String? = nil, filename: String = #file, function: String = #function, line: Int = #line)
{
logMessageWithColor(color: LogSymbol.notImportant, message: message, date: date, filename: filename, function: function, line: line)
}
#if VERBOSE_DEBUG
// Verbose debugging has not been implemented yet.
#else
public func vLog(message: String, date: String? = nil) {}
public func vLogRed(message: String, date: String? = nil) {}
public func vLogOrange(message: String, date: String? = nil) {}
public func vLogYellow(message: String, date: String? = nil) {}
public func vLogGreen(message: String, date: String? = nil) {}
public func vLogBlue(message: String, date: String? = nil) {}
public func vLogPurple(message: String, date: String? = nil) {}
public func vLogGray(message: String, date: String? = nil) {}
#endif
// ------------------------------------------------------------
// MARK: - Private -
// ------------------------------------------------------------
/// Print a logging message using color output.
private func logMessageWithColor(color: String,
message: String?,
date: String?,
filename: String,
function: String,
line: Int)
{
guard let dateString = date, ikiLogger_enabled else {
return;
}
if messageShouldBeLoggedBasedOnDate(dateString: dateString, colorString: color) {
if let uwMessage = message as String? {
#if CRASHLYTICS
if ikiLogger_useCrashlytics {
if ikiLogger_useColor {
CLSNSLogv("\(ikiLogger_prefix) \(color) -[%@:%d] %@ - %@", getVaList([(filename as NSString).lastPathComponent, line, function, uwMessage]))
} else {
CLSNSLogv("-[%@:%d] %@ - %@", getVaList([(filename as NSString).lastPathComponent, line, function, uwMessage]))
}
}
#else
if ikiLogger_useColor {
NSLog("\(ikiLogger_prefix) \(color) -[\((filename as NSString).lastPathComponent):\(line)] \(function) - \(uwMessage)")
} else {
NSLog("-[\((filename as NSString).lastPathComponent):\(line)] \(function) - \(uwMessage)")
}
#endif
}
}
}
/// Decide if a date comparison should be ignored based on the logging color.
private func dateComparisonShouldBeIgnored(colorString: String) -> Bool
{
var ignoreDateComparison = false
// Ignore date comparisons if the color level is CRITICAL.
if colorString == LogColor.critical {
ignoreDateComparison = true
}
return ignoreDateComparison;
}
/// Log the message if the creation date for the message is after the suppression date and the color is not set for forced logging.
private func messageShouldBeLoggedBasedOnDate(dateString: String, colorString: String) -> Bool
{
if dateComparisonShouldBeIgnored(colorString: colorString) { return true; }
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MMM-dd"
let newDate = formatter.date(from: dateString)
var printMessage = false
let beforeDate = formatter.date(from: ikiLogger_suppressBeforeDate)
if let uwNewDate = newDate, let uwBeforeDate = beforeDate {
if uwNewDate.compare(uwBeforeDate) == ComparisonResult.orderedDescending {
printMessage = true
}
}
return printMessage;
}
|
mit
|
8c957ededadbf99ac7e8b71aba308a5c
| 40.458678 | 164 | 0.680754 | 4.123716 | false | false | false | false |
trenskow/Slaminate
|
Slaminate/Operators.swift
|
1
|
1146
|
//
// Operators.swift
// Slaminate
//
// Created by Kristian Trenskow on 25/02/16.
// Copyright © 2016 Trenskow.io. All rights reserved.
//
import Foundation
// Operator to only assign if nil.
infix operator ??=
infix operator |=
func ??=<T>(lhs: inout T?, rhs: T?) {
lhs = lhs ?? rhs
}
public func +(lhs: Animation, rhs: Animation) -> Animation {
return lhs.and(animation: rhs)
}
public func |(lhs: Animation, rhs: Animation) -> Animation {
return lhs.then(animation: rhs)
}
public func +=(lhs: inout Animation, rhs: Animation) {
lhs = lhs.and(animation: rhs)
}
public func |=(lhs: inout Animation, rhs: Animation) {
lhs = lhs.then(animation: rhs)
}
public func +(lhs: Curve, rhs: Curve) -> Curve {
return lhs.add(curve: rhs)
}
public func *(lhs: Curve, rhs: Curve) -> Curve {
return lhs.multiply(curve: rhs)
}
public func |(lhs: Curve, rhs: Curve) -> Curve {
return lhs.or(curve: rhs)
}
public func +=(lhs: inout Curve, rhs: Curve) {
lhs = lhs + rhs
}
public func *=(lhs: inout Curve, rhs: Curve) {
lhs = lhs * rhs
}
public func |=(lhs: inout Curve, rhs: Curve) {
lhs = lhs | rhs
}
|
mit
|
bf98591b64d5d0d110265846920344a3
| 19.087719 | 60 | 0.631441 | 3.15427 | false | false | false | false |
DanielFulton/ImageLibraryTests
|
ImageLibraryTests/ImageCacheLibrary.swift
|
1
|
7903
|
//
// ImageCacheLibrary.swift
// ImageLibraryTests
//
// Created by Daniel Fulton on 8/10/16.
// Copyright © 2016 GLS Japan. All rights reserved.
//
import Kingfisher
import Haneke
import MapleBacon
import ImageLoader
import AlamofireImage
import Alamofire
import Nuke
let downloader = ImageDownloader()
enum ImageCacheLibrary:Int {
case kingfisher = 1
case haneke
case mapleBacon
case imageLoader
case alamofireImage
case nuke
case hayabusa
func fetchImage(imageView:UIImageView, url:NSURL, completion:(result:TestResult?)->Void) {
switch self {
case .kingfisher:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let interval = CACurrentMediaTime()
imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: nil, progressBlock: nil) { (image, error, cacheType, imageURL) in
if (image == nil) {
print("kingfisher failed")
testNextOperation()
return
}
let elapsed = CACurrentMediaTime()
print("kingfisher finished in \(elapsed - interval) seconds")
completion(result: TestResult(libraryName: "Kingfisher", elapsedTime: elapsed - interval, libraryType: .kingfisher))
testNextOperation()
}
})
case .haneke:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let hanekeStartTime = CACurrentMediaTime()
imageView.hnk_setImageFromURL(url, placeholder: nil, format: nil, failure: { (failureError) in
print("haneke failed.")
testNextOperation()
}) { (image) in
let hanekeFinishTime = CACurrentMediaTime()
print("haneke finished in \(hanekeFinishTime - hanekeStartTime) seconds")
completion(result: TestResult(libraryName: "Haneke", elapsedTime: hanekeFinishTime - hanekeStartTime, libraryType: .haneke))
testNextOperation()
}
})
case .mapleBacon:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let mapleBaconStartTime = CACurrentMediaTime()
imageView.setImageWithURL(url, placeholder: nil, crossFadePlaceholder: false, cacheScaled: false) { (image, error) in
if (image != nil) {
let mapleBaconFinishTime = CACurrentMediaTime()
print("maple bacon finished in \(mapleBaconFinishTime - mapleBaconStartTime)")
completion(result: TestResult(libraryName: "MapleBacon", elapsedTime: mapleBaconFinishTime - mapleBaconStartTime, libraryType: .mapleBacon))
//model.results.append(TestResult(libraryName: "mapleBacon", elapsedTime: mapleBaconFinishTime - mapleBaconStartTime, libraryType: .mapleBacon))
} else {
print("maple bacon failed")
}
testNextOperation()
}
})
case .imageLoader:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let imageLoaderStartTime = CACurrentMediaTime()
imageView.load(url, placeholder: nil) { (url, image, error, type) in
let imageLoaderEndTime = CACurrentMediaTime()
if (image != nil) {
print("ImageLoader finished in \(imageLoaderEndTime - imageLoaderStartTime) seconds")
completion(result: TestResult(libraryName: "SwiftImageLoader", elapsedTime: imageLoaderEndTime - imageLoaderStartTime, libraryType: .imageLoader))
} else {
print("ImageLoader failed.")
}
testNextOperation()
}
})
case .alamofireImage:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let request = NSURLRequest(URL: url)
let alamofireStartTime = CACurrentMediaTime()
downloader.downloadImage(URLRequest: request) { (resp:Response) in
if let img = resp.result.value {
let alamofireEndTime = CACurrentMediaTime()
print("alamofire finished in \(alamofireEndTime - alamofireStartTime) seconds")
completion(result: TestResult(libraryName: "AlamoFireImage", elapsedTime: alamofireEndTime - alamofireStartTime, libraryType: .alamofireImage))
imageView.image = img
} else {
print("alamofire failed")
}
testNextOperation()
}
})
case .nuke:
ImageQueueSingleton.sharedInstance.addFetchOperation({
let request = ImageRequest(URL: url)
var options = ImageViewLoadingOptions()
let nukeStartTime = CACurrentMediaTime()
options.handler = { view, task, response, options in
let nukeEndTime = CACurrentMediaTime()
if ((task.response?.isSuccess) != nil) {
print("nuke finished in \(nukeEndTime - nukeStartTime) seconds")
completion(result: TestResult(libraryName: "Nuke", elapsedTime: nukeEndTime - nukeStartTime, libraryType: .nuke))
}
testNextOperation()
}
imageView.nk_setImageWith(request, options: options).resume()
})
case .hayabusa:
ImageQueueSingleton.sharedInstance.addFetchOperation({
if let op = self.hayabusaOp(imageView, url: url) {
NSOperationQueue().addOperation(op)
}
})
}
}
func prefetchURLs(urls:[NSURL]) {
switch self {
case .kingfisher:
let prefetchOp = NSBlockOperation(block: {
let prefetcher = ImagePrefetcher.init(urls: urls, optionsInfo: nil, progressBlock: nil, completionHandler: { (skippedResources, failedResources, completedResources) in
})
prefetcher.start()
})
prefetchOp.queuePriority = .High
ImageQueueSingleton.sharedInstance.queue.addOperation(prefetchOp)
default:
print("this library doesnt prefetch")
}
}
func hayabusaOp(imageView:UIImageView, url:NSURL) -> HayabusaOperation? {
let startTime = CACurrentMediaTime()
let op = HayabusaOperation(url: url) { (image, error) in
let endTime = CACurrentMediaTime()
if image != nil {
print("ImageURLOperation finished in \(endTime - startTime) seconds")
model.results.append(TestResult(libraryName: "ImageURLOperation", elapsedTime: endTime - startTime, libraryType: .hayabusa))
NSOperationQueue.mainQueue().addOperationWithBlock({
imageView.image = image
})
} else {
print("hayabusa failed")
}
}
return op
}
}
class ImageQueueSingleton {
let queue:NSOperationQueue = NSOperationQueue()
static let sharedInstance:ImageQueueSingleton = {
let instance = ImageQueueSingleton()
instance.queue.maxConcurrentOperationCount = 1
return instance
} ()
func addFetchOperation(closure:()->Void) {
let op = NSBlockOperation {
closure()
}
op.queuePriority = .VeryHigh
op.qualityOfService = .UserInitiated
self.queue.addOperation(op)
}
}
|
mit
|
01d5cee18ed29b604a3fb3e77aef3ae7
| 44.41954 | 183 | 0.57264 | 5.64832 | false | true | false | false |
fakerabbit/memoria
|
Memoria/LineTextField.swift
|
1
|
1574
|
//
// LineTextField.swift
// Memoria
//
// Created by Mirko Justiniano on 3/3/17.
// Copyright © 2017 MM. All rights reserved.
//
import Foundation
import UIKit
class LineTextField: UITextField {
private let chatInset: CGFloat = 2
private let topInset: CGFloat = 10
private lazy var line:UIView! = {
let v = UIView(frame: CGRect.zero)
v.backgroundColor = Utils.backgroundColor()
return v
}()
// MARK:- Init
override init(frame: CGRect) {
super.init(frame: frame)
self.backgroundColor = UIColor.clear
self.font = Utils.mainFont()
self.textColor = Utils.backgroundColor()
self.returnKeyType = .next
self.addSubview(line)
}
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override func textRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + chatInset, y: bounds.origin.y + topInset, width: bounds.size.width - chatInset * 2, height: bounds.size.height)
}
override func editingRect(forBounds bounds: CGRect) -> CGRect {
return CGRect(x: bounds.origin.x + chatInset, y: bounds.origin.y + topInset, width: bounds.size.width - chatInset * 2, height: bounds.size.height)
}
// MARK:- Layout
override func layoutSubviews() {
super.layoutSubviews()
let w = self.frame.size.width
let h = self.frame.size.height
line.frame = CGRect(x: 0, y: h, width: w, height: 1)
}
}
|
mit
|
37258e8f338849262d90ddcbb71339ed
| 28.12963 | 154 | 0.624285 | 4.043702 | false | false | false | false |
sbcmadn1/swift
|
swiftweibo05/GZWeibo05/Class/Module/Main/View/CZVistorView.swift
|
2
|
11936
|
//
// CZVistorView.swift
// GZWeibo05
//
// Created by zhangping on 15/10/26.
// Copyright © 2015年 zhangping. All rights reserved.
//
import UIKit
/*
使用frame:
origin: 指定位置
size: 指定尺寸大小
*/
// 定义协议
protocol CZVistorViewDelegte: NSObjectProtocol {
func vistorViewRegistClick()
func vistorViewLoginClick()
}
class CZVistorView: UIView {
// 属性
weak var vistorViewDelegate: CZVistorViewDelegte?
// MARK: - 按钮点击事件
/// 注册
func registClick() {
// if let delegate = vistorViewDelegate {
// delegate.vistorViewRegistClick()
// } else {
// print("妹子")
// }
// ? 前面的变量有值才执行后面的代码,没有值就什么都不做
vistorViewDelegate?.vistorViewRegistClick()
}
/// 登录
func loginClick() {
vistorViewDelegate?.vistorViewLoginClick()
}
// MARK: - 构造函数
required init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
override init(frame: CGRect) {
super.init(frame: frame)
prepareUI()
}
// MARK: - 设置访客视图内容
/**
设置访客视图内容,出了首页
- parameter imageName: 图片名称
- parameter message: 消息
*/
func setupVistorView(imageName: String, message: String) {
// 隐藏房子
homeView.hidden = true
iconView.image = UIImage(named: imageName)
messageLabel.text = message
self.sendSubviewToBack(coverView)
}
override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) {
print(iconView.layer.animationKeys())
}
// 转轮动画
func startRotationAnimation() {
// 创建动画
let animation = CABasicAnimation(keyPath: "transform.rotation")
// 设置参数
animation.toValue = 2 * M_PI
animation.repeatCount = MAXFLOAT
animation.duration = 20
// 完成的时候不移除
animation.removedOnCompletion = false
// 开始动画
iconView.layer.addAnimation(animation, forKey: "homeRotation")
}
/// 暂停旋转
func pauseAnimation() {
// 记录暂停时间
let pauseTime = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil)
// 设置动画速度为0
iconView.layer.speed = 0
// 设置动画偏移时间
iconView.layer.timeOffset = pauseTime
}
/// 恢复旋转
func resumeAnimation() {
// 获取暂停时间
let pauseTime = iconView.layer.timeOffset
// 设置动画速度为1
iconView.layer.speed = 1
iconView.layer.timeOffset = 0
iconView.layer.beginTime = 0
let timeSincePause = iconView.layer.convertTime(CACurrentMediaTime(), fromLayer: nil) - pauseTime
iconView.layer.beginTime = timeSincePause
}
/// 准备UI
func prepareUI() {
// 设置背景
backgroundColor = UIColor(white: 237.0 / 255, alpha: 1)
// 添加子控件
addSubview(iconView)
// 遮盖
addSubview(coverView)
addSubview(homeView)
addSubview(messageLabel)
addSubview(registerButton)
addSubview(loginButton)
// 设置约束
iconView.translatesAutoresizingMaskIntoConstraints = false
coverView.translatesAutoresizingMaskIntoConstraints = false
homeView.translatesAutoresizingMaskIntoConstraints = false
messageLabel.translatesAutoresizingMaskIntoConstraints = false
registerButton.translatesAutoresizingMaskIntoConstraints = false
loginButton.translatesAutoresizingMaskIntoConstraints = false
// 创建约束
// view1.attr1 = view2.attr2 * multiplier + constant
// 转轮
// CenterX
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// CenterY
self.addConstraint(NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: -40))
// 小房子
// x
addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
addConstraint(NSLayoutConstraint(item: homeView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0))
// 消息label
// x
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0))
// y
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: iconView, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// width
addConstraint(NSLayoutConstraint(item: messageLabel, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 240))
// 注册按钮
// 左边
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
// 顶部
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// 宽度
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
addConstraint(NSLayoutConstraint(item: registerButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
// 登录按钮
// 右边
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
// 顶部
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: messageLabel, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 16))
// 宽度
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Width, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 100))
// 高度
addConstraint(NSLayoutConstraint(item: loginButton, attribute: NSLayoutAttribute.Height, relatedBy: NSLayoutRelation.Equal, toItem: nil, attribute: NSLayoutAttribute.NotAnAttribute, multiplier: 1, constant: 35))
// 遮盖
// 左边
addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Left, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Left, multiplier: 1, constant: 0))
// 上边
addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
// 右边
addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
// 下边
addConstraint(NSLayoutConstraint(item: coverView, attribute: NSLayoutAttribute.Bottom, relatedBy: NSLayoutRelation.Equal, toItem: registerButton, attribute: NSLayoutAttribute.Bottom, multiplier: 1, constant: 0))
}
func test() {
// 创建约束
// view1.attr1 = view2.attr2 * multiplier + constant
// CenterX
let cX = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterX, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterX, multiplier: 1, constant: 0)
self.addConstraint(cX)
// CenterY
let cY = NSLayoutConstraint(item: iconView, attribute: NSLayoutAttribute.CenterY, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.CenterY, multiplier: 1, constant: 0)
self.addConstraint(cY)
}
// MARK: - 懒加载
/// 转轮
private lazy var iconView: UIImageView = {
let imageView = UIImageView()
// 设置图片
let image = UIImage(named: "visitordiscover_feed_image_smallicon")
imageView.image = image
imageView.sizeToFit()
return imageView
}()
/// 小房子.只有首页有
private lazy var homeView: UIImageView = {
let imageView = UIImageView()
// 设置图片
let image = UIImage(named: "visitordiscover_feed_image_house")
imageView.image = image
imageView.sizeToFit()
return imageView
}()
/// 消息文字
private lazy var messageLabel: UILabel = {
let label = UILabel()
// 设置文字
label.text = "关注一些人,看看有什么惊喜"
label.textColor = UIColor.lightGrayColor()
label.numberOfLines = 0
label.sizeToFit()
return label
}()
/// 注册按钮
private lazy var registerButton: UIButton = {
let button = UIButton()
// 设置文字
button.setTitle("注册", forState: UIControlState.Normal)
button.setTitleColor(UIColor.orangeColor(), forState: UIControlState.Normal)
// 设置背景
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.sizeToFit()
// 添加点击事件
button.addTarget(self, action: "registClick", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
/// 登录按钮
private lazy var loginButton: UIButton = {
let button = UIButton()
// 设置文字
button.setTitle("登录", forState: UIControlState.Normal)
button.setTitleColor(UIColor.blackColor(), forState: UIControlState.Normal)
// 设置背景
button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Normal)
button.sizeToFit()
// 添加点击事件
button.addTarget(self, action: "loginClick", forControlEvents: UIControlEvents.TouchUpInside)
return button
}()
// 遮盖
private lazy var coverView: UIImageView = UIImageView(image: UIImage(named: "visitordiscover_feed_mask_smallicon"))
}
|
mit
|
9831bad82568c2b8f7b0398f7d0ee97c
| 35.775974 | 222 | 0.648627 | 5.292991 | false | false | false | false |
ianthetechie/SwiftCGI-Demo
|
Carthage/Checkouts/SwiftCGI/SwiftCGI Framework/SwiftCGI/HTTPTypes.swift
|
1
|
7229
|
//
// HTTPTypes.swift
// SwiftCGI
//
// Created by Ian Wagner on 1/7/15.
// Copyright (c) 2015 Ian Wagner. All rights reserved.
//
// MARK: Utility definitions
let HTTPNewline = "\r\n"
let HTTPTerminator = "\r\n\r\n"
// MARK: Simple enumerations
public enum HTTPRangeUnit: String {
case Bytes = "bytes"
case None = "none"
}
public enum HTTPMethod: String {
case OPTIONS = "OPTIONS"
case GET = "GET"
case HEAD = "HEAD"
case POST = "POST"
case PUT = "PUT"
case DELETE = "DELETE"
case TRACE = "TRACE"
case CONNECT = "CONNECT"
}
public enum HTTPCacheControlResponse {
case Public
case Private
case NoCache
case NoStore
case NoTransform
case MustRevalidate
case ProxyRevalidate
case MaxAge(Int)
case SMaxAge(Int)
case CacheExtension
}
extension HTTPCacheControlResponse: HTTPHeaderSerializable {
public var headerSerializableValue: String {
switch self {
case .Public:
return "public"
case .Private: // TODO: optional field name
return "private"
case .NoCache: // TODO: optional field name
return "no-cache"
case .NoStore:
return "no-store"
case .NoTransform:
return "no-transform"
case .MustRevalidate:
return "must-revalidate"
case .ProxyRevalidate:
return "proxy-revalidate"
case .MaxAge(let seconds):
return "max-age = \(seconds)"
case .SMaxAge(let seconds):
return "s-maxage = \(seconds)"
case .CacheExtension:
return "cache-extension"
}
}
}
public enum Charset: String {
case UTF8 = "utf-8"
}
/// Types conforming to this protocol may be interpolated safely into an HTTP header line.
public protocol HTTPHeaderSerializable {
var headerSerializableValue: String { get }
}
// MARK: Status codes
public typealias HTTPStatusCode = Int
public enum HTTPStatus: HTTPStatusCode {
case OK = 200
case Created = 201
case Accepted = 202
case MovedPermanently = 301
case SeeOther = 303
case NotModified = 304
case TemporaryRedirect = 307
case BadRequest = 400
case Unauthorized = 401
case Forbidden = 403
case NotFound = 404
case MethodNotAllowed = 405
case NotAcceptable = 406
case InternalServerError = 500
case NotImplemented = 501
case ServiceUnavailable = 503
var description: String {
switch self {
case .OK: return "OK"
case .Created: return "Created"
case .Accepted: return "Accepted"
case .MovedPermanently: return "Moved Permanently"
case .SeeOther: return "See Other"
case .NotModified: return "Not Modified"
case .TemporaryRedirect: return "Temporary Redirect"
case .BadRequest: return "Bad Request"
case .Unauthorized: return "Unauthorized"
case .Forbidden: return "Forbidden"
case .NotFound: return "Not Found"
case .MethodNotAllowed: return "Method Not Allowed"
case .NotAcceptable: return "Not Acceptable"
case .InternalServerError: return "Internal Server Error"
case .NotImplemented: return "Not Implemented"
case .ServiceUnavailable: return "Service Unavailable"
}
}
}
// MARK: HTTP headers
// TODO: Unit test everything below this line
public protocol HTTPHeader: Equatable, HTTPHeaderSerializable {
var key: String { get }
}
public func ==<T: HTTPHeader>(lhs: T, rhs: T) -> Bool {
return lhs.key == rhs.key && lhs.headerSerializableValue == rhs.headerSerializableValue
}
// TODO: Finish adding all of the HTTP response headers
public enum HTTPResponseHeader: HTTPHeader {
case AccessControlAllowOrigin(String)
case AcceptPatch(HTTPContentType)
case AcceptRanges(HTTPRangeUnit)
case Age(Int)
case Allow(HTTPMethod)
case CacheControl(HTTPCacheControlResponse)
case ContentLength(Int)
case ContentType(HTTPContentType)
case SetCookie([String: String])
public var key: String {
switch self {
case .AccessControlAllowOrigin(_): return "Access-Control-Allow-Origin"
case .AcceptPatch(_): return "Accept-Patch"
case .AcceptRanges(_): return "Accept-Ranges"
case .Age(_): return "Age"
case .Allow(_): return "Allow"
case .CacheControl(_): return "Cache-Control"
case .ContentLength(_): return "Content-Length"
case .ContentType(_): return "Content-Type"
case .SetCookie(_): return "Set-Cookie"
}
}
public var headerSerializableValue: String {
switch self {
case .AccessControlAllowOrigin(let value): return value
case .AcceptPatch(let value): return value.headerSerializableValue
case .AcceptRanges(let value): return value.rawValue
case .Age(let value): return String(value)
case .Allow(let value): return value.rawValue
case .CacheControl(let value): return value.headerSerializableValue
case .ContentLength(let length): return String(length)
case .ContentType(let type): return type.headerSerializableValue
case .SetCookie(let cookies): return cookies.map({ (key, value) in "\(key)=\(value)" }).joinWithSeparator("\(HTTPNewline)\(self.key): ")
}
}
}
// Note to future self and anyone else reading this code: additional types of generated data should
// be included here. If someone (including my future self) thinks of a good reason to include types
// such as video/mp4 that are typically used for static files, then there should be a VERY good use
// case for it. Web application frameworks are designed for dynamic response generation, not serving
// static files. nginx is perfectly good at that already. Notable exceptions to the "no static file
// types" rule are images, which have many valid dynamic generation use cases (QR codes, barcodes,
// transformations on uploaded files, etc).
public enum HTTPContentType: Equatable {
case TextHTML(Charset)
case TextPlain(Charset)
case ApplicationJSON
case ImagePNG
case ImageJPEG
}
extension HTTPContentType: HTTPHeaderSerializable {
public var headerSerializableValue: String {
switch self {
case .TextHTML(let charset): return "text/html; charset=\(charset.rawValue)"
case .TextPlain(let charset): return "text/plain; charset=\(charset.rawValue)"
case .ApplicationJSON: return "application/json"
case .ImagePNG: return "image/png"
case .ImageJPEG: return "image/jpeg"
}
}
}
public func ==(a: HTTPContentType, b: HTTPContentType) -> Bool {
switch (a, b) {
case (.TextHTML(let x), .TextHTML(let y)) where x == y: return true
case (.TextPlain(let x), .TextPlain(let y)) where x == y: return true
case (.ApplicationJSON, .ApplicationJSON): return true
case (.ImagePNG, .ImagePNG): return true
case (.ImageJPEG, .ImageJPEG): return true
default: return false
}
}
|
bsd-2-clause
|
04870761d0e491f07c81d9134722144f
| 31.272321 | 144 | 0.648914 | 4.445879 | false | false | false | false |
RMizin/PigeonMessenger-project
|
FalconMessenger/ChatsControllers/ChatLogViewController+PhotoEditorDelegate.swift
|
1
|
2583
|
//
// ChatLogController+PhotoEditorDelegate.swift
// Pigeon-project
//
// Created by Roman Mizin on 8/23/17.
// Copyright © 2017 Roman Mizin. All rights reserved.
//
import UIKit
import Photos
import AVKit
import CropViewController
private let nibName = "PhotoEditorViewController"
private var selectedPhotoIndexPath: IndexPath!
extension ChatLogViewController: CropViewControllerDelegate {
func presentPhotoEditor(forImageAt indexPath: IndexPath) {
guard let image = inputContainerView.attachedMedia[indexPath.row].object?.asUIImage else { return }
inputContainerView.resignAllResponders()
let cropController = CropViewController(croppingStyle: .default, image: image)
cropController.delegate = self
selectedPhotoIndexPath = indexPath
self.present(cropController, animated: true, completion: nil)
}
func cropViewController(_ cropViewController: CropViewController, didCropToImage image: UIImage, withRect cropRect: CGRect, angle: Int) {
guard selectedPhotoIndexPath != nil else { return }
self.inputContainerView.attachedMedia[selectedPhotoIndexPath.row].object = image.jpegData(compressionQuality: 1)
self.inputContainerView.attachCollectionView.reloadItems(at: [selectedPhotoIndexPath])
dismissCropController(cropViewController: cropViewController)
}
func cropViewController(_ cropViewController: CropViewController, didFinishCancelled cancelled: Bool) {
dismissCropController(cropViewController: cropViewController)
}
func dismissCropController(cropViewController: CropViewController) {
selectedPhotoIndexPath = nil
cropViewController.dismiss(animated: true, completion: nil)
cropViewController.delegate = nil //to avoid memory leaks
updateContainerViewLayout()
}
func updateContainerViewLayout() {
inputContainerView.handleRotation()
//needed to update input container layout if device was rotated during the image editing
}
func presentVideoPlayer(forUrlAt indexPath: IndexPath) {
guard let pathURL = inputContainerView.attachedMedia[indexPath.item].fileURL else { return }
let videoURL = URL(string: pathURL)
let player = AVPlayer(url: videoURL!)
let playerViewController = AVPlayerViewController()
if DeviceType.isIPad {
playerViewController.modalPresentationStyle = .overFullScreen
} else {
playerViewController.modalPresentationStyle = .overCurrentContext
}
playerViewController.player = player
inputContainerView.resignAllResponders()
present(playerViewController, animated: true, completion: nil)
}
}
|
gpl-3.0
|
5d8f5bba72c2591837efc01eddecd412
| 38.121212 | 139 | 0.780015 | 5.062745 | false | false | false | false |
watson-developer-cloud/ios-sdk
|
Sources/DiscoveryV2/Models/DocumentClassifierModel.swift
|
1
|
2950
|
/**
* (C) Copyright IBM Corp. 2022.
*
* 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
/**
Information about a document classifier model.
*/
public struct DocumentClassifierModel: Codable, Equatable {
/**
The status of the training run.
*/
public enum Status: String {
case training = "training"
case available = "available"
case failed = "failed"
}
/**
A unique identifier of the document classifier model.
*/
public var modelID: String?
/**
A human-readable name of the document classifier model.
*/
public var name: String
/**
A description of the document classifier model.
*/
public var description: String?
/**
The date that the document classifier model was created.
*/
public var created: Date?
/**
The date that the document classifier model was last updated.
*/
public var updated: Date?
/**
Name of the CSV file that contains the training data that is used to train the document classifier model.
*/
public var trainingDataFile: String?
/**
Name of the CSV file that contains data that is used to test the document classifier model. If no test data is
provided, a subset of the training data is used for testing purposes.
*/
public var testDataFile: String?
/**
The status of the training run.
*/
public var status: String?
/**
An object that contains information about a trained document classifier model.
*/
public var evaluation: ClassifierModelEvaluation?
/**
A unique identifier of the enrichment that is generated by this document classifier model.
*/
public var enrichmentID: String?
/**
The date that the document classifier model was deployed.
*/
public var deployedAt: Date?
// Map each property name to the key that shall be used for encoding/decoding.
private enum CodingKeys: String, CodingKey {
case modelID = "model_id"
case name = "name"
case description = "description"
case created = "created"
case updated = "updated"
case trainingDataFile = "training_data_file"
case testDataFile = "test_data_file"
case status = "status"
case evaluation = "evaluation"
case enrichmentID = "enrichment_id"
case deployedAt = "deployed_at"
}
}
|
apache-2.0
|
1658d30457efa6549fc0905d88c558df
| 27.365385 | 115 | 0.660678 | 4.638365 | false | true | false | false |
daniel-barros/TV-Calendar
|
TV Calendar/ShowUpdater.swift
|
1
|
10902
|
//
// ShowUpdater.swift
// TV Calendar
//
// Created by Daniel Barros López on 11/20/16.
// Copyright © 2016 Daniel Barros. All rights reserved.
//
import ExtendedFoundation
import RealmSwift
let lastAiredEpisodesUpdateDateKey = "lastAiredEpisodesUpdateDateKey"
let lastOutdatedInfoUpdateDateKey = "lastOutdatedInfoUpdateDateKey"
let lastTimeZoneIdentifierKey = "lastTimeZoneIdentifierKey"
protocol Countable {
var count: Int { get }
}
extension Array: Countable {}
extension ArraySlice: Countable {}
extension Results: Countable {}
extension List: Countable {}
protocol ShowUpdaterDelegate: class {
/// - parameter info: May contain an array of strings for the key "ids", only for an .episodes update where episodes where deleted.
/// - warning: If updateType == .airedEpisodes or .timeZone, `show` should be ignored.
func didUpdate(_ updateType: ShowUpdater.UpdateType,
for show: Show,
withSuccess success: Bool,
error: Show.FetchError?,
info: [String: Any]?,
updater: ShowUpdater)
/// Gets called AFTER all the other `didUpdate(...)` delegate calls.
func didEndAllUpdates(updater: ShowUpdater)
}
/// Facilitates fetching new info and updating tracked shows, allows to cancel some updates, keeps track of when these updates take place and lets you know if new updates should be performed.
///
/// It should be used instead of calling a show's updateEpisodes(), updateBasicInfo() or updatePoster() methods.
///
/// It lets the delegate know when any update is made.
/// - warning: Not thread-safe.
class ShowUpdater {
enum UpdateType {
case airedEpisodes, poster(replaceExisting: Bool), episodes, timeZone
/// Includes the show's basic info, episodes and airedEpisodes.
case outdatedInfo
}
weak var delegate: ShowUpdaterDelegate?
/// Any update that started before this date is considered invalidated.
fileprivate var validPosterUpdateStartDate = Date()
private var _numberOfOngoingUpdates = 0
private let internalQueue = DispatchQueue(label: "serialQueue", qos: .default)
fileprivate var numberOfOngoingUpdates: Int {
get {
return internalQueue.sync { _numberOfOngoingUpdates }
}
set {
internalQueue.sync { _numberOfOngoingUpdates = newValue }
assert(newValue >= 0)
if newValue == 0 {
delegate?.didEndAllUpdates(updater: self)
}
}
}
/// `true` if no update today.
var needsToUpdateAiredEpisodes: Bool {
if let lastUpdateDate = UserDefaults.standard.object(forKey: lastAiredEpisodesUpdateDateKey) as? Date {
return Calendar.current.isDateInToday(lastUpdateDate) == false
} else {
return true
}
}
/// `true` if no update in two days.
var needsToUpdateOutdatedInfo: Bool {
if let lastUpdateDate = UserDefaults.standard.object(forKey: lastOutdatedInfoUpdateDateKey) as? Date {
return Calendar.current.numberOfDays(from: lastUpdateDate, to: .now) > 1
} else {
return true
}
}
var needsToUpdateTimeZone: Bool {
if let timeZoneId = UserDefaults.standard.object(forKey: lastTimeZoneIdentifierKey) as? String,
let lastTimeZone = TimeZone(identifier: timeZoneId) {
return lastTimeZone != .current
} else {
return true
}
}
/// Sets the updater's last update date to now, making all the needsToUpdate... properties `false` for today at least.
func resetLastUpdateDate() {
UserDefaults.standard.set(Date(), forKey: lastAiredEpisodesUpdateDateKey)
UserDefaults.standard.set(Date(), forKey: lastOutdatedInfoUpdateDateKey)
UserDefaults.standard.set(TimeZone.current.identifier, forKey: lastTimeZoneIdentifierKey)
}
func cancelOngoingPosterUpdates() {
validPosterUpdateStartDate = Date()
}
/// `didUpdate(_:for:withSuccess:error:in:)` will get called on the delegate:
///
/// - One time if the updateType is .airedEpisodes, .poster or .timeZone (you can ignore the show parameter).
///
/// - Twice for each updated show if updating episodes (.episodes and .airedEpisodes updates, the latter only if the former was successful)
///
/// - Up to 3 times for each updated show if updating outdated info (.outdatedInfo, .episodes and .airedEpisodes updates, .episodes only if the update was necessary or possible and .airedEpisodes following same rules as if updating episodes directly).
func update(_ updateType: UpdateType, for show: Show, timeout: TimeInterval = .infinity) {
update(updateType, for: [show], timeout: timeout)
}
/// `didUpdate(_:for:withSuccess:error:in:)` will get called on the delegate:
///
/// - One time if the updateType is .airedEpisodes, .poster or .timeZone (you can ignore the show parameter).
///
/// - Twice for each updated show if updating episodes (.episodes and .airedEpisodes updates, the latter only if the former was successful)
///
/// - Up to 3 times for each updated show if updating outdated info (.outdatedInfo, .episodes and .airedEpisodes updates, .episodes only if the update was necessary or possible and .airedEpisodes following same rules as if updating episodes directly).
func update<T>(_ updateType: UpdateType, for shows: T, timeout: TimeInterval = .infinity) where T: Sequence, T: Countable, T.Iterator.Element == Show {
numberOfOngoingUpdates += shows.count
if case .poster(_) = updateType {
assert(timeout == .infinity, "poster updates with timeout not implemented yet")
}
switch updateType {
case .airedEpisodes: updateAiredEpisodes(for: shows)
case .poster(let replaceExisting): updatePoster(for: shows, replacingExistingInfo: replaceExisting)
case .episodes: updateEpisodes(for: shows, timeout: timeout)
case .outdatedInfo: updateOutdatedInfo(for: shows, timeout: timeout)
case .timeZone: updateTimeZone(for: shows)
}
}
}
// MARK: Updates
fileprivate extension ShowUpdater {
func updateAiredEpisodes<T>(for shows: T) where T: Sequence, T: Countable, T.Iterator.Element == Show {
shows.forEach { _ = $0.updateCurrentSeasonAiredEpisodes() }
UserDefaults.standard.set(Date(), forKey: lastAiredEpisodesUpdateDateKey)
delegate?.didUpdate(.airedEpisodes, for: Show(), withSuccess: true, error: nil, info: nil, updater: self)
numberOfOngoingUpdates -= shows.count
}
func updateOutdatedInfo<T>(for shows: T, timeout: TimeInterval) where T: Sequence, T.Iterator.Element == Show {
for show in shows {
let lastUpdateDate = show.updateDate
show.updateBasicInfo(timeout: timeout) { result in
// If updateDate is same, there's nothing to update
if show.updateDate != lastUpdateDate {
switch result {
case .success:
self.updateEpisodes(for: [show], timeout: timeout)
self.delegate?.didUpdate(.outdatedInfo, for: show, withSuccess: result.isSuccessful, error: result.error, info: nil, updater: self)
// (self.numberOfOngoingUpdates is decreased in updateEpisodes(for:) )
case .failure(let error):
self.delegate?.didUpdate(.outdatedInfo, for: show, withSuccess: false, error: error, info: nil, updater: self)
self.numberOfOngoingUpdates -= 1
}
}
// Aired episodes are updated as result of episodes update. If none is performed, we update them here
else {
if show.updateCurrentSeasonAiredEpisodes() {
self.delegate?.didUpdate(.airedEpisodes, for: show, withSuccess: result.isSuccessful, error: nil, info: nil, updater: self)
}
self.numberOfOngoingUpdates -= 1
}
if result.isSuccessful {
UserDefaults.standard.set(Date(), forKey: lastOutdatedInfoUpdateDateKey)
UserDefaults.standard.set(Date(), forKey: lastAiredEpisodesUpdateDateKey)
}
}
}
}
func updateTimeZone<T>(for shows: T) where T: Sequence, T: Countable, T.Iterator.Element == Show {
shows.forEach { $0.timeZone = .current }
UserDefaults.standard.set(TimeZone.current.identifier, forKey: lastTimeZoneIdentifierKey)
delegate?.didUpdate(.timeZone, for: Show(), withSuccess: true, error: nil, info: nil, updater: self)
numberOfOngoingUpdates -= shows.count
}
func updatePoster<T>(for shows: T, replacingExistingInfo: Bool) where T: Sequence, T.Iterator.Element == Show {
let startDate = Date()
for show in shows {
// Poster already exists, we don't need new one
if !replacingExistingInfo && show.poster != nil {
numberOfOngoingUpdates -= 1
continue
}
// Poster is outdated (hasn't been updated for new season)
if replacingExistingInfo && !show.isPosterOutdated {
numberOfOngoingUpdates -= 1
continue
}
show.updatePoster { success in
if startDate >= self.validPosterUpdateStartDate {
self.delegate?.didUpdate(.poster(replaceExisting: replacingExistingInfo), for: show, withSuccess: success, error: nil, info: nil, updater: self)
}
self.numberOfOngoingUpdates -= 1
}
}
}
func updateEpisodes<T>(for shows: T, timeout: TimeInterval) where T: Sequence, T.Iterator.Element == Show {
for show in shows {
show.updateEpisodes(timeout: timeout) { result in
// Get event ids for deleted episodes
let info: [String: Any]?
switch result {
case .success(let ids): info = ["ids": ids]
case .failure(_): info = nil
}
// Notify the delegate
self.delegate?.didUpdate(.episodes, for: show, withSuccess: result.isSuccessful, error: result.error as? Show.FetchError, info: info, updater: self)
if result.isSuccessful {
self.delegate?.didUpdate(.airedEpisodes, for: show, withSuccess: result.isSuccessful, error: result.error as? Show.FetchError, info: nil, updater: self)
}
self.numberOfOngoingUpdates -= 1
}
}
}
}
|
gpl-3.0
|
d5a15e3b482a2c39c1509defbdc0404b
| 45.581197 | 256 | 0.633486 | 4.793316 | false | false | false | false |
instacrate/Subber-api
|
Sources/App/Models/Onboarding.swift
|
2
|
1030
|
//
// Onboarding.swift
// subber-api
//
// Created by Hakon Hanesand on 1/22/17.
//
//
import Foundation
import Vapor
import Auth
import Fluent
import Sanitized
final class Onboarding: Model, JSONConvertible, Preparation, Sanitizable {
static var permitted: [String] = ["email"]
var id: Node?
var exists = false
let email: String
init(node: Node, in context: Context = EmptyNode) throws {
id = try node.extract("id")
email = try node.extract("email")
}
func makeNode(context: Context = EmptyNode) throws -> Node {
return try Node(node: [
"email" : .string(email)
]).add(objects: [
"id" : id
])
}
static func prepare(_ database: Database) throws {
try database.create(self.entity) { onboarding in
onboarding.string("email")
onboarding.id()
}
}
static func revert(_ database: Database) throws {
try database.delete(self.entity)
}
}
|
mit
|
be79980d712452d8402e5f924219a811
| 20.914894 | 74 | 0.580583 | 4.12 | false | false | false | false |
carabina/APNGKit
|
APNGKit/APNGImageCache.swift
|
10
|
4850
|
//
// APNGImageCache.swift
// APNGKit
//
// Created by Wei Wang on 15/8/30.
//
// Copyright (c) 2015 Wei Wang <[email protected]>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import UIKit
/// Cache for APNGKit. It will hold apng images initialized from specified init methods.
/// If the same file is requested later, APNGKit will look it up in this cache first to improve performance.
public class APNGCache {
private static let defaultCacheInstance = APNGCache()
/// The default cache object. It is used internal in APNGKit.
/// You should always use this object to interact with APNG cache as well.
public class var defaultCache: APNGCache {
return defaultCacheInstance
}
let cacheObject = NSCache()
init() {
// Limit the cache to prevent memory warning as possible.
// The cache will be invalidated once a memory warning received,
// so we need to keep cache in limitation and try to not trigger the memory warning.
// See clearMemoryCache() for more.
cacheObject.totalCostLimit = 100 * 1024 * 1024 //100 MB
cacheObject.countLimit = 15
cacheObject.name = "com.onevcat.APNGKit.cache"
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache",
name: UIApplicationDidReceiveMemoryWarningNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: "clearMemoryCache",
name: UIApplicationDidEnterBackgroundNotification, object: nil)
}
deinit {
NSNotificationCenter.defaultCenter().removeObserver(self)
}
/**
Cache an APNG image with specified key.
- parameter image: The image should be cached.
- parameter key: The key of that image
*/
public func setImage(image: APNGImage, forKey key: String) {
cacheObject.setObject(image, forKey: key, cost: image.cost)
}
/**
Remove an APNG image from cache with specified key.
- parameter key: The key of that image
*/
public func removeImageForKey(key: String) {
cacheObject.removeObjectForKey(key)
}
func imageForKey(key: String) -> APNGImage? {
return cacheObject.objectForKey(key) as? APNGImage
}
/**
Clear the memory cache.
- note: Generally speaking you could just use APNGKit without worrying the memory and cache.
The cached images will be removed when a memory warning is received or your app is switched to background.
However, there is a chance that you want to do an operation requiring huge amount of memory, which may cause
your app OOM directly without receiving a memory warning. In this situation, you could call this method first
to release the APNG cache for your memory costing operation.
*/
@objc public func clearMemoryCache() {
// The cache will not work once it receives a memory warning from iOS 8.
// It seems an intended behaviours to reduce memory pressure.
// See http://stackoverflow.com/questions/27289360/nscache-objectforkey-always-return-nil-after-memory-warning-on-ios-8
// The solution in that post does not work on iOS 9. I guess just follow the system behavior would be good.
cacheObject.removeAllObjects()
}
}
extension APNGImage {
var cost: Int {
var s = 0
for f in frames {
if let image = f.image {
// Totol bytes
s += Int(image.size.height * image.size.width * image.scale * image.scale * CGFloat(self.bitDepth))
}
}
return s
}
}
|
mit
|
ffc7b8935f68076396ccc97174334a1b
| 41.552632 | 135 | 0.668247 | 4.830677 | false | false | false | false |
zhuyunfeng1224/XiheMtxx
|
XiheMtxx/VC/Photo/PhotoAlbumViewController.swift
|
1
|
6136
|
//
// PhotoAlbumViewController.swift
// EasyCard
//
// Created by echo on 2017/2/21.
// Copyright © 2017年 羲和. All rights reserved.
//
import UIKit
import Photos
// 相册对象
class AlbumObject: NSObject {
var assets: [PHAsset] = []
var albumName: String = ""
}
class PhotoAlbumViewController: PhotoBaseViewController {
lazy var tableView: UITableView = {
let _tableView = UITableView(frame: CGRect.zero)
_tableView.backgroundColor = UIColor.colorWithHexString(hex: "#f9f9f9")
_tableView.register(PhotoAlbumTableViewCell.self, forCellReuseIdentifier: String(describing: PhotoAlbumTableViewCell.self))
_tableView.translatesAutoresizingMaskIntoConstraints = false
_tableView.rowHeight = 90
_tableView.delegate = self
_tableView.dataSource = self
_tableView.tableFooterView = UIView()
_tableView.separatorColor = UIColor.colorWithHexString(hex: "#e6e6e6")
return _tableView
}()
var albums: [AlbumObject] = []
lazy var userAlbums: AlbumObject = {
let _userAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumUserLibrary, options: nil)
let assets = PhotoAlbumViewController.fetchAssetsFromCollection(collectionResult: _userAlbums)
var album = AlbumObject()
album.assets = assets
album.albumName = "相机胶卷"
return album
}()
lazy var recentAlbums: AlbumObject = {
let _recentAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumRecentlyAdded, options: nil)
let assets = PhotoAlbumViewController.fetchAssetsFromCollection(collectionResult: _recentAlbums)
var album = AlbumObject()
album.assets = assets
album.albumName = "最近添加"
return album
}()
lazy var favourAlbums: AlbumObject = {
let _favourAlbums = PHAssetCollection.fetchAssetCollections(with: .smartAlbum, subtype: .smartAlbumFavorites, options: nil)
let assets = PhotoAlbumViewController.fetchAssetsFromCollection(collectionResult: _favourAlbums)
var album = AlbumObject()
album.assets = assets
album.albumName = "个人收藏"
return album
}()
override func viewDidLoad() {
super.viewDidLoad()
self.title = "选择照片"
self.view.addSubview(self.tableView)
self.view.setNeedsUpdateConstraints()
self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named:"btn_back_arrow_25x25_"), style: .done, target: self, action: #selector(backButtonClicked(sender:)))
self.navigationItem.leftItemsSupplementBackButton = true
if self.userAlbums.assets.count > 0 {
self.albums.append(self.userAlbums)
}
if self.recentAlbums.assets.count > 0 {
self.albums.append(self.recentAlbums)
}
if self.favourAlbums.assets.count > 0 {
self.albums.append(self.favourAlbums)
}
let indexFirst = IndexPath(row: 0, section: 0)
self.tableView(self.tableView, didSelectRowAt: indexFirst)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
override func updateViewConstraints() {
super.updateViewConstraints()
let tableHContraints = NSLayoutConstraint.constraints(withVisualFormat: "H:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["tableView": self.tableView])
let tableVContraints = NSLayoutConstraint.constraints(withVisualFormat: "V:|-0-[tableView]-0-|", options: NSLayoutFormatOptions(rawValue:0), metrics: nil, views: ["tableView": self.tableView])
self.view.addConstraints(tableHContraints)
self.view.addConstraints(tableVContraints)
}
// MARK: Private Method
// 获取相册中图片
open static func fetchAssetsFromCollection(collectionResult: PHFetchResult<PHAssetCollection>!) -> [PHAsset] {
var assets: [PHAsset] = []
let option = PHFetchOptions()
option.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
var result: PHFetchResult<PHAsset>?
if collectionResult.count != 0 {
result = PHAsset.fetchAssets(in: collectionResult.firstObject!, options: option)
}
if let result = result {
result.enumerateObjects({ (obj, index, stop) in
if obj.mediaType == .image {
assets.append(obj)
}
})
}
return assets
}
func backButtonClicked(sender: Any) -> Void {
self.dismiss(animated: true) {
}
}
}
extension PhotoAlbumViewController: UITableViewDataSource, UITableViewDelegate {
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return self.albums.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell: PhotoAlbumTableViewCell = tableView.dequeueReusableCell(withIdentifier: String(describing: PhotoAlbumTableViewCell.self)) as! PhotoAlbumTableViewCell
if indexPath.row < self.albums.count {
let album = self.albums[indexPath.row]
cell.titleLabel.text = album.albumName
let assets = album.assets
cell.detailLabel.text = "\(assets.count)张"
if let lastAsset: PHAsset = assets.last {
cell.asset = lastAsset
}
}
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let assetVC = PhotoAssetViewController()
if indexPath.row < self.albums.count {
let album = self.albums[indexPath.row]
assetVC.assets = album.assets
assetVC.title = album.albumName
}
self.navigationController?.pushViewController(assetVC, animated: true)
}
}
|
mit
|
612861b8f94059a0063b64b2102c1ab7
| 37.436709 | 200 | 0.653548 | 4.99014 | false | false | false | false |
joerocca/GitHawk
|
Pods/Tabman/Sources/Tabman/TabmanBar/Styles/Abstract/TabmanButtonBar.swift
|
1
|
11265
|
//
// TabmanButtonBar.swift
// Tabman
//
// Created by Merrick Sapsford on 14/03/2017.
// Copyright © 2017 Merrick Sapsford. All rights reserved.
//
import UIKit
import Pageboy
/// Abstract class for button bars.
internal class TabmanButtonBar: TabmanBar {
//
// MARK: Types
//
internal typealias TabmanButtonBarItemCustomize = (_ button: UIButton, _ previousButton: UIButton?) -> Void
//
// MARK: Constants
//
private struct Defaults {
static let minimumItemHeight: CGFloat = 40.0
static let itemImageSize: CGSize = CGSize(width: 25.0, height: 25.0)
static let titleWithImageSize: CGSize = CGSize(width: 20.0, height: 20.0)
}
//
// MARK: Properties
//
internal var buttons = [UIButton]()
internal var horizontalMarginConstraints = [NSLayoutConstraint]()
internal var edgeMarginConstraints = [NSLayoutConstraint]()
internal var focussedButton: UIButton? {
didSet {
guard focussedButton !== oldValue else {
return
}
focussedButton?.setTitleColor(self.selectedColor, for: .normal)
focussedButton?.tintColor = self.selectedColor
oldValue?.setTitleColor(self.color, for: .normal)
oldValue?.tintColor = self.color
}
}
public var textFont: UIFont = Appearance.defaultAppearance.text.font! {
didSet {
guard textFont != oldValue else {
return
}
self.updateButtons(update: { (button) in
button.titleLabel?.font = textFont
})
}
}
public var color: UIColor = Appearance.defaultAppearance.state.color!
public var selectedColor: UIColor = Appearance.defaultAppearance.state.selectedColor!
public var imageRenderingMode: UIImageRenderingMode = Appearance.defaultAppearance.style.imageRenderingMode! {
didSet {
guard oldValue != imageRenderingMode else {
return
}
updateButtons(update: {
guard let image = $0.currentImage else {
return
}
$0.setImage(image.withRenderingMode(imageRenderingMode), for: .normal)
})
}
}
public var itemVerticalPadding: CGFloat = Appearance.defaultAppearance.layout.itemVerticalPadding! {
didSet {
guard itemVerticalPadding != oldValue else {
return
}
self.updateButtons { (button) in
let insets = UIEdgeInsets(top: itemVerticalPadding, left: 0.0,
bottom: itemVerticalPadding, right: 0.0)
button.contentEdgeInsets = insets
self.layoutIfNeeded()
}
}
}
/// The spacing between each bar item.
public var interItemSpacing: CGFloat = Appearance.defaultAppearance.layout.interItemSpacing! {
didSet {
self.updateConstraints(self.horizontalMarginConstraints,
withValue: interItemSpacing)
self.layoutIfNeeded()
self.updateForCurrentPosition()
}
}
/// The inset at the edge of the bar items.
public var edgeInset: CGFloat = Appearance.defaultAppearance.layout.edgeInset! {
didSet {
self.updateConstraints(self.edgeMarginConstraints,
withValue: edgeInset)
self.layoutIfNeeded()
self.updateForCurrentPosition()
}
}
/// Check if a button should response to events
open override func hitTest(_ point: CGPoint, with event: UIEvent?) -> UIView? {
let view = super.hitTest(point, with: event)
guard let button = view as? UIButton, let index = self.buttons.index(of: button) else {
return view
}
guard self.responder?.bar(self, shouldSelectItemAt: index) ?? true else {
return nil
}
return view
}
//
// MARK: TabmanBar Lifecycle
//
public override func construct(in contentView: UIView,
for items: [TabmanBar.Item]) {
self.buttons.removeAll()
self.horizontalMarginConstraints.removeAll()
self.edgeMarginConstraints.removeAll()
}
public override func update(forAppearance appearance: Appearance,
defaultAppearance: Appearance) {
super.update(forAppearance: appearance,
defaultAppearance: defaultAppearance)
let color = appearance.state.color
self.color = color ?? defaultAppearance.state.color!
let selectedColor = appearance.state.selectedColor
self.selectedColor = selectedColor ?? defaultAppearance.state.selectedColor!
let interItemSpacing = appearance.layout.interItemSpacing
self.interItemSpacing = interItemSpacing ?? defaultAppearance.layout.interItemSpacing!
let textFont = appearance.text.font
self.textFont = textFont ?? defaultAppearance.text.font!
let itemVerticalPadding = appearance.layout.itemVerticalPadding
self.itemVerticalPadding = itemVerticalPadding ?? defaultAppearance.layout.itemVerticalPadding!
let edgeInset = appearance.layout.edgeInset
self.edgeInset = edgeInset ?? defaultAppearance.layout.edgeInset!
self.imageRenderingMode = appearance.style.imageRenderingMode ?? defaultAppearance.style.imageRenderingMode!
// update left margin for progressive style
if self.indicator?.isProgressiveCapable ?? false {
let indicatorIsProgressive = appearance.indicator.isProgressive ?? defaultAppearance.indicator.isProgressive!
let leftMargin = self.indicatorLeftMargin?.constant ?? 0.0
let indicatorWasProgressive = leftMargin == 0.0
if indicatorWasProgressive && !indicatorIsProgressive {
self.indicatorLeftMargin?.constant = leftMargin - self.edgeInset
} else if !indicatorWasProgressive && indicatorIsProgressive {
self.indicatorLeftMargin?.constant = 0.0
}
}
}
//
// MARK: Content
//
internal func addBarButtons(toView view: UIView,
items: [TabmanBar.Item],
customize: TabmanButtonBarItemCustomize) {
var previousButton: UIButton?
for (index, item) in items.enumerated() {
let button = UIButton(forAutoLayout: ())
view.addSubview(button)
if let image = item.image, let title = item.title {
// resize images to fit
let resizedImage = image.resize(toSize: Defaults.titleWithImageSize)
if resizedImage.size != .zero {
button.setImage(resizedImage.withRenderingMode(imageRenderingMode), for: .normal)
}
button.setTitle(title, for: .normal)
// Nudge it over a little bit
button.titleEdgeInsets = UIEdgeInsets(top: 0.0, left: 5.0, bottom: 0.0, right: 0.0)
} else if let title = item.title {
button.setTitle(title, for: .normal)
} else if let image = item.image {
// resize images to fit
let resizedImage = image.resize(toSize: Defaults.itemImageSize)
if resizedImage.size != .zero {
button.setImage(resizedImage.withRenderingMode(imageRenderingMode), for: .normal)
}
}
// appearance
button.titleLabel?.adjustsFontSizeToFitWidth = true
button.titleLabel?.font = self.textFont
// layout
NSLayoutConstraint.autoSetPriority(UILayoutPriority(500), forConstraints: {
button.autoSetDimension(.height, toSize: Defaults.minimumItemHeight)
})
button.autoPinEdge(toSuperviewEdge: .top)
button.autoPinEdge(toSuperviewEdge: .bottom)
let verticalPadding = self.itemVerticalPadding
let insets = UIEdgeInsets(top: verticalPadding, left: 0.0, bottom: verticalPadding, right: 0.0)
button.contentEdgeInsets = insets
// Add horizontal pin constraints
// These are breakable (For equal width instances etc.)
NSLayoutConstraint.autoSetPriority(UILayoutPriority(500), forConstraints: {
if let previousButton = previousButton {
self.horizontalMarginConstraints.append(button.autoPinEdge(.leading, to: .trailing, of: previousButton))
} else { // pin to leading
self.edgeMarginConstraints.append(button.autoPinEdge(toSuperviewEdge: .leading))
}
if index == items.count - 1 {
self.edgeMarginConstraints.append(button.autoPinEdge(toSuperviewEdge: .trailing))
}
})
// allow button to be compressed
NSLayoutConstraint.autoSetPriority(UILayoutPriority(400), forConstraints: {
button.autoSetContentCompressionResistancePriority(for: .horizontal)
})
// Accessibility
button.accessibilityLabel = item.accessibilityLabel
button.accessibilityHint = item.accessibilityHint
if let accessibilityTraits = item.accessibilityTraits {
button.accessibilityTraits = accessibilityTraits
}
customize(button, previousButton)
previousButton = button
}
}
internal enum ButtonContext {
case all
case target
case unselected
}
internal func updateButtons(withContext context: ButtonContext = .all, update: (UIButton) -> Void) {
for button in self.buttons {
if context == .all ||
(context == .target && button === self.focussedButton) ||
(context == .unselected && button !== self.focussedButton) {
update(button)
}
}
}
//
// MARK: Actions
//
@objc internal func tabButtonPressed(_ sender: UIButton) {
if let index = self.buttons.index(of: sender), (self.responder?.bar(self, shouldSelectItemAt: index) ?? true) {
self.responder?.bar(self, didSelectItemAt: index)
}
}
//
// MARK: Layout
//
internal func updateConstraints(_ constraints: [NSLayoutConstraint], withValue value: CGFloat) {
for constraint in constraints {
var value = value
if constraint.constant < 0.0 || constraint.firstAttribute == .trailing {
value = -value
}
constraint.constant = value
}
self.layoutIfNeeded()
}
}
|
mit
|
2a286b943382bd0d881c5758faabf24b
| 36.421927 | 124 | 0.582919 | 5.677419 | false | false | false | false |
jpush/aurora-imui
|
iOS/IMUIMessageCollectionView/Views/IMUIVideoMessageContentView.swift
|
1
|
2515
|
//
// IMUIVideoMessageContentView.swift
// sample
//
// Created by oshumini on 2017/6/12.
// Copyright © 2017年 HXHG. All rights reserved.
//
import UIKit
import AVFoundation
public class IMUIVideoMessageContentView: UIView, IMUIMessageContentViewProtocol {
lazy var videoView = UIImageView()
lazy var playBtn = UIButton()
lazy var videoDuration = UILabel()
override init(frame: CGRect) {
super.init(frame: frame)
self.addSubview(self.videoView)
videoView.addSubview(playBtn)
videoView.addSubview(videoDuration)
playBtn.frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 56, height: 56))
playBtn.setImage(UIImage.imuiImage(with: "video_play_btn"), for: .normal)
videoDuration.textColor = UIColor.white
videoDuration.font = UIFont.systemFont(ofSize: 10.0)
}
required public init?(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
public func layoutContentView(message: IMUIMessageModelProtocol) {
let layout = message.layout
self.layoutVideo(with: message.mediaFilePath())
videoView.frame = CGRect(origin: CGPoint.zero, size: layout.bubbleContentSize)
playBtn.center = CGPoint(x: videoView.imui_width/2, y: videoView.imui_height/2)
let durationX = videoView.imui_width - 30
let durationY = videoView.imui_height - 24
videoDuration.frame = CGRect(x: durationX,
y: durationY,
width: 30,
height: 24)
}
func layoutVideo(with videoPath: String) {
let asset = AVURLAsset(url: URL(fileURLWithPath: videoPath), options: nil)
let seconds = Int (CMTimeGetSeconds(asset.duration))
if seconds/3600 > 0 {
videoDuration.text = "\(seconds/3600):\(String(format: "%02d", (seconds/3600)%60)):\(seconds%60)"
} else {
videoDuration.text = "\(seconds / 60):\(String(format: "%02d", seconds % 60))"
}
let serialQueue = DispatchQueue(label: "videoLoad")
serialQueue.async {
do {
let imgGenerator = AVAssetImageGenerator(asset: asset)
imgGenerator.appliesPreferredTrackTransform = true
let cgImage = try imgGenerator.copyCGImage(at: CMTimeMake(value: 0, timescale: 1), actualTime: nil)
DispatchQueue.main.async {
self.videoView.image = UIImage(cgImage: cgImage)
}
} catch {
DispatchQueue.main.async {
self.videoView.image = nil
}
}
}
}
}
|
mit
|
ee6b855148579094c29e41ee74e3f7a4
| 32.052632 | 107 | 0.655653 | 4.316151 | false | false | false | false |
PedroTrujilloV/TIY-Assignments
|
34--First-Contact/Friends/Friends/PersonDetailViewController.swift
|
1
|
2995
|
//
// PersonDetailViewController.swift
// Friends
//
// Created by Ben Gohlke on 11/19/15.
// Copyright © 2015 The Iron Yard. All rights reserved.
//
import UIKit
import RealmSwift
class PersonDetailViewController: UIViewController, UITableViewDataSource, UITableViewDelegate
{
@IBOutlet weak var friendCountLabel: UILabel!
@IBOutlet weak var tableView: UITableView!
let realm = try! Realm()
var person: Person?
var allPeople: Results<Person>!
override func viewDidLoad()
{
super.viewDidLoad()
allPeople = realm.objects(Person).filter("name != %@", person!.name).sorted("name")
updateFriendCountLabel()
}
func updateFriendCountLabel()
{
friendCountLabel.text = "\(person!.name) has \(person!.friendCount) friend\(person!.friendCount == 1 ? "" : "s")"
}
override func didReceiveMemoryWarning()
{
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// MARK: - UITableView Data Source
func numberOfSectionsInTableView(tableView: UITableView) -> Int
{
return 1
}
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int
{
return allPeople.count
}
func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String?
{
return "Add some friends"
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell
{
let cell = tableView.dequeueReusableCellWithIdentifier("FriendCell", forIndexPath: indexPath)
let aPossibleFriend = allPeople[indexPath.row]
cell.textLabel?.text = aPossibleFriend.name
let results = person!.friends.filter("name == %@", aPossibleFriend.name)
if results.count == 1
{
cell.accessoryType = .Checkmark
}
else
{
cell.accessoryType = .None
}
return cell
}
func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath)
{
tableView.deselectRowAtIndexPath(indexPath, animated: true)
let cell = tableView.cellForRowAtIndexPath(indexPath)
if cell?.accessoryType == UITableViewCellAccessoryType.None
{
cell?.accessoryType = .Checkmark
try! realm.write { () -> Void in
self.person!.friends.append(self.allPeople[indexPath.row])
self.person!.friendCount++
}
updateFriendCountLabel()
}
else
{
cell?.accessoryType = .None
try! realm.write { () -> Void in
let index = self.person!.friends.indexOf(self.allPeople[indexPath.row])
self.person!.friends.removeAtIndex(index!)
self.person!.friendCount--
}
updateFriendCountLabel()
}
}
}
|
cc0-1.0
|
8d45cf097c9c188cf8f7b230e9695ca9
| 28.95 | 121 | 0.616566 | 5.188908 | false | false | false | false |
adamcumiskey/BlockDataSource
|
Example/BlockDataSource/MiddlewareViewController.swift
|
1
|
1405
|
//
// MiddlewareViewController.swift
// BlockDataSource_Example
//
// Created by Adam on 6/25/18.
// Copyright © 2018 CocoaPods. All rights reserved.
//
import BlockDataSource
import UIKit
class MiddlewareViewController: BlockTableViewController {
init() {
super.init(style: .plain)
self.title = "Middleware"
self.tableView.sectionHeaderHeight = UITableViewAutomaticDimension
self.tableView.rowHeight = UITableViewAutomaticDimension
self.dataSource = DataSource(
sections: [
Section(
header: Reusable { (view: InformationHeaderFooterView) in
view.titleLabel.text = "Middleware is applied to each cell before it is displayed."
},
items: (0..<50).map { item in
return Item { (cell: UITableViewCell) in
cell.textLabel?.text = "\(item)"
}
},
footerText: "Middleware can be created for items, section headers/footers, and table/collection views"
)
],
middleware: Middleware(
tableViewCellMiddleware: [
TableViewCellMiddleware.noCellSelectionStyle,
TableViewCellMiddleware.cellGradient
]
)
)
}
}
|
mit
|
d51af51387ae411e5e9e037d75d7e355
| 34.1 | 122 | 0.551994 | 5.777778 | false | false | false | false |
PurpleSweetPotatoes/SwiftKit
|
SwiftKit/ui/BQPopVc.swift
|
1
|
2124
|
//
// BQPopVc.swift
// MyShortApp
//
// Created by baiqiang on 2018/11/17.
// Copyright © 2018年 baiqiang. All rights reserved.
//
import UIKit
typealias PopHandler = ((_ objc: Any?) -> Void)
class BQPopVc: UIViewController {
var showTime: TimeInterval = 0.25
var hideTime: TimeInterval = 0.25
var dictInfo: Any?
var handle:PopHandler?
var backObjc: Any?
/// if not need backView can removeFromSupView
var backView: UIView = UIView(frame: UIScreen.main.bounds)
public class func showView(presentVc: UIViewController, dictInfo:Any? = nil, handle:PopHandler? = nil) {
let popVc = self.init()
popVc.dictInfo = dictInfo
popVc.handle = handle
popVc.modalPresentationStyle = .overCurrentContext
presentVc.present(popVc, animated: false) {
popVc.animationShow()
}
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
backView.backgroundColor = UIColor.black.withAlphaComponent(0.25)
view.addSubview(backView)
view.addTapGes {[weak self] (tapView) in
self?.handle = nil
self?.animationHide()
}
}
private func dismissSelf() {
DispatchQueue.delay(0.2) {
self.dismiss(animated: false) {[weak self] in
if let hand = self?.handle {
hand(self?.backObjc)
}
}
}
}
//MARK:- ***** subClass can override, need use super func *****
func animationShow() {
UIView.animate(withDuration: showTime) {
self.backView.isHidden = false
}
}
func animationHide() {
if !backView.isHidden {
UIView.animate(withDuration: hideTime, animations: {
self.backView.isHidden = true;
}) { (finished) in
self.dismissSelf()
}
} else {
DispatchQueue.delay(hideTime) {
self.dismissSelf()
}
}
}
}
|
apache-2.0
|
5122e5c8152bf9ce78341a7b4da54243
| 26.192308 | 108 | 0.558227 | 4.532051 | false | false | false | false |
wireapp/wire-ios-data-model
|
Source/Model/Message/Mention.swift
|
1
|
3020
|
//
// Wire
// Copyright (C) 2018 Wire Swiss GmbH
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see http://www.gnu.org/licenses/.
//
import Foundation
@objc
public class Mention: NSObject {
public let range: NSRange
public let user: UserType
init?(_ protobuf: WireProtos.Mention, context: NSManagedObjectContext) {
let userRemoteID = protobuf.hasQualifiedUserID ? protobuf.qualifiedUserID.id : protobuf.userID
let domain = protobuf.hasQualifiedUserID ? protobuf.qualifiedUserID.domain : nil
guard
let userId = UUID(uuidString: userRemoteID),
protobuf.length > 0,
protobuf.start >= 0,
let user = ZMUser.fetch(with: userId, domain: domain, in: context)
else {
return nil
}
self.user = user
self.range = NSRange(location: Int(protobuf.start), length: Int(protobuf.length))
}
public init(range: NSRange, user: UserType) {
self.range = range
self.user = user
}
public override func isEqual(_ object: Any?) -> Bool {
guard let otherMention = object as? Mention else { return false }
return user.isEqual(otherMention.user) && NSEqualRanges(range, otherMention.range)
}
}
extension Mention {
static func mentions(from protos: [WireProtos.Mention]?, messageText: String?, moc: NSManagedObjectContext?) -> [Mention] {
guard let protos = protos,
let messageText = messageText,
let managedObjectContext = moc else { return [] }
let mentions = Array(protos.compactMap({ Mention($0, context: managedObjectContext) }).prefix(500))
var mentionRanges = IndexSet()
let messageRange = NSRange(messageText.startIndex ..< messageText.endIndex, in: messageText)
return mentions.filter({ mention in
let range = mention.range.range
guard !mentionRanges.intersects(integersIn: range), range.upperBound <= messageRange.upperBound else { return false }
mentionRanges.insert(integersIn: range)
return true
})
}
}
// MARK: - Helper
fileprivate extension NSRange {
var range: Range<Int> {
return lowerBound..<upperBound
}
}
@objc public extension Mention {
var isForSelf: Bool {
return user.isSelfUser
}
}
public extension ZMTextMessageData {
var isMentioningSelf: Bool {
return mentions.any(\.isForSelf)
}
}
|
gpl-3.0
|
aeea9d6238bc0439962abd6a0eb9f891
| 30.134021 | 129 | 0.666556 | 4.507463 | false | false | false | false |
germc/IBM-Ready-App-for-Retail
|
iOS/ReadyAppRetail/ReadyAppRetail/Models/BeaconManager.swift
|
2
|
9769
|
/*
Licensed Materials - Property of IBM
© Copyright IBM Corporation 2015. All Rights Reserved.
*/
import UIKit
import Realm
class BeaconManager: NSObject, CLLocationManagerDelegate {
var locationManager : CLLocationManager?
var allBeacons: Array<String> = Array<String>()
var beaconRegion : CLBeaconRegion?
var closestBeaconID: String!
var departmentsCount: Int = 0
var productClose: Product = Product()
var listItemsTableViewController: ListItemsTableViewController!
var canRefreshListItemsTableViewController: Bool = false
var lastSortedByID : String!
//order not important, contains departmentId:beacon assigned to it
var departments : [String: String] = [String:String]()
//just to order the departments when assigning to beacons. contains departments only
var departmentsArray: [String]!
/**
override the init method to set up locationManager, delegate, beaconRegion, and present popup to request location usage from user
:returns:
*/
override init() {
super.init()
//set beacon manager delegate
self.locationManager = CLLocationManager()
self.locationManager!.delegate = self
//set beacon region
self.beaconRegion = CLBeaconRegion(proximityUUID: NSUUID(UUIDString: "B9407F30-F5F8-466E-AFF9-25556B57FE6D"), identifier: "MIL_Lab")
self.beaconRegion!.notifyOnEntry = true
self.beaconRegion!.notifyOnExit = true
}
/**
function to receive departments and set departmentsArray
:param: departmentArray -- array to be passed in
*/
func receiveDepartments(departmentArray : Array<String>){
self.departmentsArray = departmentArray
for department in departmentArray {
self.departments[department] = ""
}
}
/**
begin beacon detection monitoring for the given beaconRegion
*/
func startBeaconDetection() {
// - Start monitoring
self.locationManager!.startMonitoringForRegion(self.beaconRegion)
}
/**
start ranging beacons once it started monitoring
:param: manager
:param: region
*/
func locationManager(manager: CLLocationManager!, didStartMonitoringForRegion region: CLRegion!) {
NSLog("Scanning for beacons in region --> %@...", region.identifier)
self.locationManager!.startRangingBeaconsInRegion(region as! CLBeaconRegion)
}
/**
func to be called upon entering given region (with beacons)
:param: manager
:param: region
*/
func locationManager(manager: CLLocationManager!, didEnterRegion region: CLRegion!) {
// - Start ranging beacons
NSLog("You entered the region --> %@ - starting scan for beacons", region.identifier)
//self.delegate!.didEnterRegion(region as CLBeaconRegion)
self.locationManager!.startRangingBeaconsInRegion(region as! CLBeaconRegion)
XtifyHelper.updateNearSummitStore()
}
/**
func to be called upon exiting given region
:param: manager
:param: region
*/
func locationManager(manager: CLLocationManager!, didExitRegion region: CLRegion!) {
// - Stop ranging beacons
NSLog("You exited the region --> %@ - stopping scan for beacons", region)
//self.delegate!.didExitRegion(region as CLBeaconRegion)
self.locationManager!.stopRangingBeaconsInRegion(region as! CLBeaconRegion)
}
/**
func to be called upon a failure in monitoring beacons
:param: manager
:param: region
:param: error
*/
func locationManager(manager: CLLocationManager!, monitoringDidFailForRegion region: CLRegion!, withError error: NSError!) {
NSLog("Error monitoring \(error)")
}
/**
func to be called approx once per second while ranging beacons. assigns newly discovered beacons to a department in the order given to departmentsArray
:param: manager
:param: beacons
:param: region
*/
func locationManager(manager: CLLocationManager!, didRangeBeacons beacons: [AnyObject]!, inRegion region: CLBeaconRegion!) {
var knownBeacons = beacons.filter{ $0.proximity != CLProximity.Unknown } //filter out unknown beacons
//let knownBeacons = beacons.filter{$0.proximity == CLProximity.Immediate}
//if beacons are found at all, continue
if (knownBeacons.count > 0) {
let closestBeacon = knownBeacons[0] as! CLBeacon //save closest Beacon for sorting later
var newBeaconID = closestBeacon.major.stringValue + closestBeacon.minor.stringValue
if (newBeaconID != self.closestBeaconID) { //if new closest beacon
self.closestBeaconID = newBeaconID
}
//if new beacon discovered, add it to a department.
//NOTE: in the real world you wouldn't dynamically assign beacons to a department. Beacons would typically be hard coded to a department already.
if (self.allBeacons.count < knownBeacons.count) {
self.addBeaconsToDepartments(self.closestBeaconID)
}
//Check to make sure the closestBeaconId is different from the last beacon id we sorted the list by. Also check to make sure the list items tableview controller is visible, no point in sorting the list when the table view controller isn't visible. Also check to make sure the beacon we are about to sort by is of imediate proximity.
if (self.lastSortedByID != self.closestBeaconID && self.canRefreshListItemsTableViewController == true && (closestBeacon.proximity == CLProximity.Immediate)) {
self.lastSortedByID = self.closestBeaconID
self.sortListByLocation(self.listItemsTableViewController.list.products, list: self.listItemsTableViewController.list)
}
}
//no beacons detected
else {
NSLog("No beacons are nearby")
}
}
/**
func containing the algorithm to assign beacons to departments if they haven't been assigned yet. assigns departments in order they are received from Worklight (in departmentsArray)
:param: closeBeaconID -- the id of the closest beacon
*/
func addBeaconsToDepartments(closeBeaconID: String!){
if contains(self.allBeacons, closeBeaconID) { //if beacon has already been assigned, don't do anything!
return
}
if (self.departments[self.departmentsArray[self.departmentsCount]] == "") { //if department not been assigned a beacon yet
self.allBeacons.append(closeBeaconID) //make note that we've assigned this beacon now
self.departments[self.departmentsArray[self.departmentsCount]] = closeBeaconID
println("Beacon \(closeBeaconID) assigned to Department \(self.departmentsArray[self.departmentsCount])")
self.departmentsCount++ //assign next department next time
}
}
/**
func to sort an array of products in a given list, and return a List object in the new order based on closest beacon/department
:param: dataArray -- data array of products passed in from ListItemsTableViewController
:param: list -- list these products belong to
:returns: same list with new order based on proximity
*/
func sortListByLocation(dataArray: RLMArray!, list: List) {
var refresh: Bool = false //only reorder list if at least one department has been detected as closest
for (var i = 0; i < Int(dataArray.count); i++){
self.productClose = dataArray.objectAtIndex(UInt(i)) as! Product
if (self.departments[self.productClose.departmentId as String] == self.closestBeaconID) {
//if product's department is also the closest beacon/department, set closer (0) proximity
RealmHelper.addProductToListWithProximity(list, product: self.productClose, proximityDesired: "0", index: UInt(i)) //rearrange product in Realm
self.listItemsTableViewController.departmentSortedBy = self.productClose.departmentName as String //update which department list is being sorted by
//println("Moved \(self.productClose.departmentName) to top of list!")
refresh = true
} else {
//product is not closeby, so make proximity farther (1)
RealmHelper.addProductToListWithProximity(list, product: self.productClose, proximityDesired: "1", index: UInt(i))
}
}
if (refresh == true){ //only reorder list if at least one department has been detected as closest
self.listItemsTableViewController.dataArray = list.products.sortedResultsUsingProperty("proximity", ascending: true)
self.listItemsTableViewController.reorderList()
}
}
/**
returns the string for proximity of a beacon
:param: proximity
:returns:
*/
class func proximityAsString(proximity: CLProximity) -> String {
switch proximity {
case CLProximity.Far:
return "Far"
case CLProximity.Near:
return "Near"
case CLProximity.Immediate:
return "Immediate"
case CLProximity.Unknown:
return "Unknown"
}
}
}
|
epl-1.0
|
b8c9734a361a0f9cfc75754b1354b36e
| 37.305882 | 344 | 0.644451 | 5.300054 | false | false | false | false |
dcordero/BlurFace
|
BlurFace/BlurFace/BlurFace.swift
|
1
|
3126
|
import UIKit
public class BlurFace {
private let ciDetector = CIDetector(ofType: CIDetectorTypeFace, context: nil ,options: [CIDetectorAccuracy : CIDetectorAccuracyHigh])
private var ciImage: CIImage!
private var orientation: UIImageOrientation = .Up
private lazy var features : [AnyObject]! = { self.ciDetector.featuresInImage(self.ciImage) }()
private lazy var context = { CIContext(options: nil) }()
// MARK: Initializers
public init(image: UIImage!) {
setImage(image)
}
public func setImage(image: UIImage!) {
ciImage = CIImage(image: image)
orientation = image.imageOrientation
features = nil
}
// MARK: Public
public func hasFaces() -> Bool {
return !features.isEmpty
}
public func blurFaces() -> UIImage {
let pixelateFiler = CIFilter(name: "CIPixellate")
pixelateFiler.setValue(ciImage, forKey: kCIInputImageKey)
pixelateFiler.setValue(max(ciImage!.extent().width, ciImage.extent().height) / 60.0, forKey: kCIInputScaleKey)
var maskImage: CIImage?
for feature in featureFaces() {
let centerX = feature.bounds.origin.x + feature.bounds.size.width / 2.0
let centerY = feature.bounds.origin.y + feature.bounds.size.height / 2.0
let radius = min(feature.bounds.size.width, feature.bounds.size.height) / 1.5
let radialGradient = CIFilter(name: "CIRadialGradient")
radialGradient.setValue(radius, forKey: "inputRadius0")
radialGradient.setValue(radius + 1, forKey: "inputRadius1")
radialGradient.setValue(CIColor(red: 0, green: 1, blue: 0, alpha: 1), forKey: "inputColor0")
radialGradient.setValue(CIColor(red: 0, green: 0, blue: 0, alpha: 0), forKey: "inputColor1")
radialGradient.setValue(CIVector(x: centerX, y: centerY), forKey: kCIInputCenterKey)
let circleImage = radialGradient.outputImage.imageByCroppingToRect(ciImage.extent())
if (maskImage == nil) {
maskImage = circleImage
}
else {
let filter = CIFilter(name: "CISourceOverCompositing")
filter.setValue(circleImage, forKey: kCIInputImageKey)
filter.setValue(maskImage, forKey: kCIInputBackgroundImageKey)
maskImage = filter.outputImage
}
}
let composite = CIFilter(name: "CIBlendWithMask")
composite.setValue(pixelateFiler.outputImage, forKey: kCIInputImageKey)
composite.setValue(ciImage, forKey: kCIInputBackgroundImageKey)
composite.setValue(maskImage, forKey: kCIInputMaskImageKey)
let cgImage = context.createCGImage(composite.outputImage, fromRect: composite.outputImage.extent())
return UIImage(CGImage: cgImage, scale: 1, orientation: orientation)!
}
// MARK: Private
private func featureFaces() -> [CIFeature] {
return features as! [CIFeature]
}
}
|
mit
|
0332cf0b652616fc07627ac962cff01b
| 39.076923 | 137 | 0.630518 | 4.765244 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.