repo_name
stringlengths
6
91
ref
stringlengths
12
59
path
stringlengths
7
936
license
stringclasses
15 values
copies
stringlengths
1
3
content
stringlengths
61
714k
hash
stringlengths
32
32
line_mean
float64
4.88
60.8
line_max
int64
12
421
alpha_frac
float64
0.1
0.92
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
yonaskolb/SwagGen
refs/heads/master
Sources/Swagger/Schema/ObjectSchema.swift
mit
1
import JSONUtilities public struct ObjectSchema { public let requiredProperties: [Property] public let optionalProperties: [Property] public let properties: [Property] public let minProperties: Int? public let maxProperties: Int? public let additionalProperties: Schema? public let abstract: Bool public let discriminator: Discriminator? public init(requiredProperties: [Property], optionalProperties: [Property], properties: [Property], minProperties: Int? = nil, maxProperties: Int? = nil, additionalProperties: Schema? = nil, abstract: Bool = false, discriminator: Discriminator? = nil) { self.requiredProperties = requiredProperties self.optionalProperties = optionalProperties self.properties = properties self.minProperties = minProperties self.maxProperties = maxProperties self.additionalProperties = additionalProperties self.abstract = abstract self.discriminator = discriminator } } public struct Property { public let name: String public let required: Bool public let schema: Schema public init(name: String, required: Bool, schema: Schema) { self.name = name self.required = required self.schema = schema } } public extension Property { var nullable: Bool { if case let .reference(ref) = schema.type { return !required || ref.value.metadata.nullable } else { return !required || schema.metadata.nullable } } } extension ObjectSchema: JSONObjectConvertible { public init(jsonDictionary: JSONDictionary) throws { let requiredPropertyNames: [String] = (jsonDictionary.json(atKeyPath: "required")) ?? [] let propertiesByName: [String: Schema] = (jsonDictionary.json(atKeyPath: "properties")) ?? [:] requiredProperties = requiredPropertyNames.compactMap { name in if let schema = propertiesByName[name] { return Property(name: name, required: true, schema: schema) } return nil } optionalProperties = propertiesByName.compactMap { name, schema in if !requiredPropertyNames.contains(name) { return Property(name: name, required: false, schema: schema) } return nil }.sorted { $0.name < $1.name } properties = requiredProperties + optionalProperties minProperties = jsonDictionary.json(atKeyPath: "minProperties") maxProperties = jsonDictionary.json(atKeyPath: "maxProperties") if let bool: Bool = jsonDictionary.json(atKeyPath: "additionalProperties") { if bool { additionalProperties = Schema(metadata: Metadata(), type: .any) } else { additionalProperties = nil } } else { additionalProperties = jsonDictionary.json(atKeyPath: "additionalProperties") } abstract = (jsonDictionary.json(atKeyPath: "x-abstract")) ?? false discriminator = jsonDictionary.json(atKeyPath: "discriminator") } }
0d7a444650877e764a65ef0c7f29818c
34.866667
102
0.63259
false
false
false
false
NghiaTranUIT/GuillotineMenu
refs/heads/master
GuillotineMenu/GuillotineMenuViewController.swift
mit
13
// // GuillotineViewController.swift // GuillotineMenu // // Created by Maksym Lazebnyi on 3/24/15. // Copyright (c) 2015 Yalantis. All rights reserved. // import UIKit class GuillotineMenuViewController: UIViewController { var hostNavigationBarHeight: CGFloat! var hostTitleText: NSString! var menuButton: UIButton! var menuButtonLeadingConstraint: NSLayoutConstraint! var menuButtonTopConstraint: NSLayoutConstraint! private let menuButtonLandscapeLeadingConstant: CGFloat = 1 private let menuButtonPortraitLeadingConstant: CGFloat = 7 private let hostNavigationBarHeightLandscape: CGFloat = 32 private let hostNavigationBarHeightPortrait: CGFloat = 44 override func viewDidLoad() { super.viewDidLoad() } override func viewDidAppear(animated: Bool) { super.viewDidAppear(animated) } override func viewWillLayoutSubviews() { super.viewWillLayoutSubviews() } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() } override func viewWillTransitionToSize(size: CGSize, withTransitionCoordinator coordinator: UIViewControllerTransitionCoordinator) { super.viewWillTransitionToSize(size, withTransitionCoordinator: coordinator) coordinator.animateAlongsideTransition(nil) { (context) -> Void in if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { self.menuButtonLeadingConstraint.constant = self.menuButtonLandscapeLeadingConstant self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant } else { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height self.menuButtonLeadingConstraint.constant = self.menuButtonPortraitLeadingConstant; self.menuButtonTopConstraint.constant = self.menuButtonPortraitLeadingConstant+statusbarHeight } } } // MARK: Actions func closeMenuButtonTapped() { self.dismissViewControllerAnimated(true, completion: nil) } func setMenuButtonWithImage(image: UIImage) { let statusbarHeight = UIApplication.sharedApplication().statusBarFrame.size.height let buttonImage = UIImage(CGImage: image.CGImage, scale: 1.0, orientation: .Right) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } else { menuButton = UIButton(frame: CGRectMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight, 30.0, 30.0)) } menuButton.setImage(image, forState: .Normal) menuButton.setImage(image, forState: .Highlighted) menuButton.imageView!.contentMode = .Center menuButton.addTarget(self, action: Selector("closeMenuButtonTapped"), forControlEvents: .TouchUpInside) menuButton.setTranslatesAutoresizingMaskIntoConstraints(false) menuButton.transform = CGAffineTransformMakeRotation( ( 90 * CGFloat(M_PI) ) / 180 ); self.view.addSubview(menuButton) if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonLandscapeLeadingConstant, menuButtonPortraitLeadingConstant)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } else { var (leading, top) = self.view.addConstraintsForMenuButton(menuButton, offset: UIOffsetMake(menuButtonPortraitLeadingConstant, menuButtonPortraitLeadingConstant+statusbarHeight)) menuButtonLeadingConstraint = leading menuButtonTopConstraint = top } } } extension GuillotineMenuViewController: GuillotineAnimationProtocol { func anchorPoint() -> CGPoint { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { //In this case value is calculated manualy as the method is called before viewDidLayourSubbviews when the menuBarButton.frame is updated. return CGPointMake(16, 16) } return self.menuButton.center } func navigationBarHeight() -> CGFloat { if UIDevice.currentDevice().orientation == .LandscapeLeft || UIDevice.currentDevice().orientation == .LandscapeRight { return hostNavigationBarHeightLandscape } else { return hostNavigationBarHeightPortrait } } func hostTitle () -> NSString { return hostTitleText } }
a7552cd30d62bd4f2b5f013a1e11e123
42.051724
190
0.70845
false
false
false
false
TotalDigital/People-iOS
refs/heads/master
Pods/InitialsImageView/InitialsImageView.swift
apache-2.0
1
// // InitialsImageView.swift // // // Created by Tom Bachant on 1/28/17. // // import UIKit let kFontResizingProportion: CGFloat = 0.4 let kColorMinComponent: Int = 30 let kColorMaxComponent: Int = 214 extension UIImageView { public func setImageForName(string: String, backgroundColor: UIColor?, circular: Bool, textAttributes: [String: AnyObject]?) { let initials: String = initialsFromString(string: string) let color: UIColor = (backgroundColor != nil) ? backgroundColor! : randomColor() let attributes: [String: AnyObject] = (textAttributes != nil) ? textAttributes! : [ NSFontAttributeName: self.fontForFontName(name: nil), NSForegroundColorAttributeName: UIColor.white ] self.image = imageSnapshot(text: initials, backgroundColor: color, circular: circular, textAttributes: attributes) } private func fontForFontName(name: String?) -> UIFont { let fontSize = self.bounds.width * kFontResizingProportion; if name != nil { return UIFont(name: name!, size: fontSize)! } else { return UIFont.systemFont(ofSize: fontSize) } } private func imageSnapshot(text imageText: String, backgroundColor: UIColor, circular: Bool, textAttributes: [String : AnyObject]) -> UIImage { let scale: CGFloat = UIScreen.main.scale var size: CGSize = self.bounds.size if (self.contentMode == .scaleToFill || self.contentMode == .scaleAspectFill || self.contentMode == .scaleAspectFit || self.contentMode == .redraw) { size.width = (size.width * scale) / scale size.height = (size.height * scale) / scale } UIGraphicsBeginImageContextWithOptions(size, false, scale) let context: CGContext = UIGraphicsGetCurrentContext()! if circular { // Clip context to a circle let path: CGPath = CGPath(ellipseIn: self.bounds, transform: nil) context.addPath(path) context.clip() } // Fill background of context context.setFillColor(backgroundColor.cgColor) context.fill(CGRect(x: 0, y: 0, width: size.width, height: size.height)) // Draw text in the context let textSize: CGSize = imageText.size(attributes: textAttributes) let bounds: CGRect = self.bounds imageText.draw(in: CGRect(x: bounds.midX - textSize.width / 2, y: bounds.midY - textSize.height / 2, width: textSize.width, height: textSize.height), withAttributes: textAttributes) let snapshot: UIImage = UIGraphicsGetImageFromCurrentImageContext()!; UIGraphicsEndImageContext(); return snapshot; } } private func initialsFromString(string: String) -> String { var displayString: String = "" var words: [String] = string.components(separatedBy: .whitespacesAndNewlines) // Get first letter of the first and last word if words.count > 0 { let firstWord: String = words.first! if firstWord.characters.count > 0 { // Get character range to handle emoji (emojis consist of 2 characters in sequence) let range: Range<String.Index> = firstWord.startIndex..<firstWord.index(firstWord.startIndex, offsetBy: 1) let firstLetterRange: Range = firstWord.rangeOfComposedCharacterSequences(for: range) displayString.append(firstWord.substring(with: firstLetterRange).uppercased()) } if words.count >= 2 { var lastWord: String = words.last! while lastWord.characters.count == 0 && words.count >= 2 { words.removeLast() lastWord = words.last! } if words.count > 1 { // Get character range to handle emoji (emojis consist of 2 characters in sequence) let range: Range<String.Index> = lastWord.startIndex..<lastWord.index(lastWord.startIndex, offsetBy: 1) let lastLetterRange: Range = lastWord.rangeOfComposedCharacterSequences(for: range) displayString.append(lastWord.substring(with: lastLetterRange).uppercased()) } } } return displayString } private func randomColorComponent() -> Int { let limit = kColorMaxComponent - kColorMinComponent return kColorMinComponent + Int(arc4random_uniform(UInt32(limit))) } private func randomColor() -> UIColor { let red = CGFloat(randomColorComponent()) / 255.0 let green = CGFloat(randomColorComponent()) / 255.0 let blue = CGFloat(randomColorComponent()) / 255.0 return UIColor(red: red, green: green, blue: blue, alpha: 1.0) }
470225f1c01563f851d921d4baa89c8f
36.161765
147
0.604472
false
false
false
false
trungphamduc/Calendar
refs/heads/master
Example/AAA/MonthCollectionCell.swift
mit
1
// // MonthCollectionCell.swift // Calendar // // Created by Lancy on 02/06/15. // Copyright (c) 2015 Lancy. All rights reserved. // import UIKit protocol MonthCollectionCellDelegate: class { func didSelect(date: Date) } class MonthCollectionCell: UICollectionViewCell, UICollectionViewDataSource, UICollectionViewDelegateFlowLayout { @IBOutlet var collectionView: UICollectionView! var monthCellDelgate: MonthCollectionCellDelegate? var dates = [Date]() var previousMonthVisibleDatesCount = 0 var currentMonthVisibleDatesCount = 0 var nextMonthVisibleDatesCount = 0 var logic: CalendarLogic? { didSet { populateDates() if collectionView != nil { collectionView.reloadData() } } } var selectedDate: Date? { didSet { if collectionView != nil { collectionView.reloadData() } } } func populateDates() { if logic != nil { dates = [Date]() dates += logic!.previousMonthVisibleDays! dates += logic!.currentMonthDays! dates += logic!.nextMonthVisibleDays! previousMonthVisibleDatesCount = logic!.previousMonthVisibleDays!.count currentMonthVisibleDatesCount = logic!.currentMonthDays!.count nextMonthVisibleDatesCount = logic!.nextMonthVisibleDays!.count } else { dates.removeAll(keepCapacity: false) } } override func awakeFromNib() { super.awakeFromNib() let nib = UINib(nibName: "DayCollectionCell", bundle: nil) self.collectionView.registerNib(nib, forCellWithReuseIdentifier: "DayCollectionCell") let headerNib = UINib(nibName: "WeekHeaderView", bundle: nil) self.collectionView.registerNib(headerNib, forSupplementaryViewOfKind: UICollectionElementKindSectionHeader, withReuseIdentifier: "WeekHeaderView") } func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { // 7*6 = 42 :- 7 columns (7 days in a week) and 6 rows (max 6 weeks in a month) return 42 } func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCellWithReuseIdentifier("DayCollectionCell", forIndexPath: indexPath) as! DayCollectionCell let date = dates[indexPath.item] cell.date = (indexPath.item < dates.count) ? date : nil cell.mark = (selectedDate == date) cell.disabled = (indexPath.item < previousMonthVisibleDatesCount) || (indexPath.item >= previousMonthVisibleDatesCount + currentMonthVisibleDatesCount) return cell } func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) { if monthCellDelgate != nil { monthCellDelgate!.didSelect(dates[indexPath.item]) } } func collectionView(collectionView: UICollectionView, viewForSupplementaryElementOfKind kind: String, atIndexPath indexPath: NSIndexPath) -> UICollectionReusableView { return collectionView.dequeueReusableSupplementaryViewOfKind(UICollectionElementKindSectionHeader, withReuseIdentifier: "WeekHeaderView", forIndexPath: indexPath) as! UICollectionReusableView } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize { return CGSizeMake(collectionView.frame.width/7.0, collectionView.frame.height/7.0) } func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, referenceSizeForHeaderInSection section: Int) -> CGSize { return CGSizeMake(collectionView.frame.width, collectionView.frame.height/7.0) } }
c0575a44e148526698a704334ef54a3d
33.651376
195
0.735504
false
false
false
false
LunaGao/cnblogs-Mac-Swift
refs/heads/master
CNBlogsForMac/News/NewsDetailViewController.swift
mit
1
// // NewsDetailViewController.swift // CNBlogsForMac // // Created by Luna Gao on 15/12/2. // Copyright © 2015年 gao.luna.com. All rights reserved. // import Cocoa import WebKit class NewsDetailViewController: BaseViewController { @IBOutlet weak var detailNewsWebView: WebView! var newsId = 0; var newsTitle = ""; let newsApi = NewsWebApi() override func viewDidLoad() { super.viewDidLoad() self.title = newsTitle } override func viewDidAppear() { newsApi.newsBodyRequest(newsId) { (response) -> Void in var localHtmlString = NSString.init(data: response, encoding: NSUTF8StringEncoding)! localHtmlString = localHtmlString.substringToIndex(localHtmlString.length - 1) localHtmlString = localHtmlString.substringFromIndex(1) localHtmlString = self.transferredString(localHtmlString as String) // NSLog("%@", localHtmlString) self.detailNewsWebView.mainFrame.loadHTMLString(localHtmlString as String, baseURL: nil) // self.detailBlogWebView.mainFrame.loadData(response, MIMEType: "text/html", textEncodingName: "utf-8", baseURL: nil) } } func transferredString(var string:String) -> String { string = string.stringByReplacingOccurrencesOfString("\\\"", withString: "\"") string = string.stringByReplacingOccurrencesOfString("\\r\\n", withString: "\n") string = string.stringByReplacingOccurrencesOfString("\\t", withString: "\t") string = string.stringByReplacingOccurrencesOfString("\\n", withString: "\n") // 基本样式 string = string + "<link type=\"text/css\" rel=\"stylesheet\" href=\"http://www.cnblogs.com/bundles/news.css\"/>" // 有代码段时用来收起和展示的js string = string + "<script src=\"http://www.cnblogs.com/bundles/news.js\" type=\"text/javascript\"></script>" string = string + "<script src=\"http://common.cnblogs.com/script/jquery.js\" type=\"text/javascript\"></script>" return string } }
21efa7b7ad86a9cf3307c7a5626df0ed
41.408163
141
0.653032
false
false
false
false
Jnosh/swift
refs/heads/master
test/SILGen/transparent_attribute.swift
apache-2.0
13
// RUN: %target-swift-frontend -emit-silgen -emit-verbose-sil %s | %FileCheck %s // Test that the attribute gets set on default argument generators. @_transparent func transparentFuncWithDefaultArgument (x: Int = 1) -> Int { return x } func useTransparentFuncWithDefaultArgument() -> Int { return transparentFuncWithDefaultArgument(); // CHECK-LABEL: sil hidden @_T021transparent_attribute37useTransparentFuncWithDefaultArgumentSiyF // CHECK: apply {{.*}} line:8:44 // CHECK: apply {{.*}} line:8:10 // CHECK: return } func transparentFuncWithoutDefaultArgument (x: Int = 1) -> Int { return x } func useTransparentFuncWithoutDefaultArgument() -> Int { return transparentFuncWithoutDefaultArgument(); // CHECK-LABEL: sil hidden @_T021transparent_attribute40useTransparentFuncWithoutDefaultArgumentSiyF // CHECK: apply {{.*}} line:21:47 // CHECK-NOT: transparent // CHECK: apply {{.*}} line:21:10 // CHECK: return } // Make sure the transparent attribute is set on constructors (allocating and initializing). struct StructWithTranspConstructor { @_transparent init () {} } func testStructWithTranspConstructor() -> StructWithTranspConstructor { return StructWithTranspConstructor() // transparent_attribute.StructWithTranspConstructor.constructor // CHECK-APPLY: sil hidden @_T021transparent_attribute27StructWithTranspConstructorV{{[_0-9a-zA-Z]*}}fC // testStructWithTranspConstructor // CHECK-APPLY: _T21transparent_attribute31testStructWithTranspConstructorFT_VS_27StructWithTranspConstructor // CHECK: apply {{.*}} line:36:10 } struct MySt {} var _x = MySt() var x1 : MySt { @_transparent get { return _x } @_transparent set { _x = newValue } } var x2 : MySt { @_transparent set(v) { _x = v } @_transparent get { return _x } } func testProperty(z: MySt) { x1 = z x2 = z var m1 : MySt = x1 var m2 : MySt = x2 // CHECK-APPLY: sil hidden @_T021transparent_attribute12testPropertyyAA4MyStV1z_tF // CHECK: function_ref @_T021transparent_attribute2x1AA4MyStVfs // CHECK-NEXT: apply // CHECK: function_ref @_T021transparent_attribute2x2AA4MyStVfs // CHECK-NEXT: apply // CHECK: function_ref @_T021transparent_attribute2x1AA4MyStVfg // CHECK-NEXT: apply // CHECK: function_ref @_T021transparent_attribute2x2AA4MyStVfg // CHECK-NEXT: apply } var _tr2 = MySt() var _tr3 = MySt() struct MyTranspStruct {} extension MyTranspStruct { @_transparent init(input : MySt) {} mutating func tr1() {} var tr2: MySt { get { return _tr2 } set { _tr2 = newValue } } } extension MyTranspStruct { @_transparent var tr3: MySt { get { return _tr3 } set { _tr3 = newValue } } } func testStructExtension() { var c : MyTranspStruct = MyTranspStruct(input: _x) c.tr1() var s : MySt = c.tr2 var t : MySt = c.tr3 // CHECK-APPLY: sil hidden @_TF21transparent_attribute13testStructExtensionFT_T_ // CHECK: [[INIT:%[0-9]+]] = function_ref @_T021transparent_attribute14MyTranspStructV{{[_0-9a-zA-Z]*}}fC // CHECK: apply [[INIT]] // CHECK: [[TR1:%[0-9]+]] = function_ref @_T021transparent_attribute14MyTranspStructV3tr1{{[_0-9a-zA-Z]*}}F // CHECK: apply [[TR1]] // CHECK: [[TR2:%[0-9]+]] = function_ref @_T021transparent_attribute14MyTranspStructV3tr2AA0C2StVfg // CHECK: apply [[TR2]] // CHECK: [[TR3:%[0-9]+]] = function_ref @_T021transparent_attribute14MyTranspStructV3tr3AA0C2StVfg // CHECK: apply [[TR3]] } enum MyEnum { case onetransp case twotransp } extension MyEnum { @_transparent func tr3() {} } func testEnumExtension() { MyEnum.onetransp.tr3() // CHECK-APPLY: sil hidden @_T021transparent_attribute17testEnumExtensionyyF // CHECK: [[TR3:%[0-9]+]] = function_ref @_T021transparent_attribute6MyEnumO3tr3{{[_0-9a-zA-Z]*}}F // CHECK: [[INIT:%[0-9]+]] = enum $MyEnum, #MyEnum.onetransp!enumelt // CHECK: apply [[TR3]]([[INIT]]) } struct testVarDecl { @_transparent var max: Int { get { return 0xFF } mutating set { max = 0xFF } } func testVarDeclFoo () { var z: Int = max // CHECK-APPLY: sil hidden @_T021transparent_attribute11testVarDeclV0cdE3Foo{{[_0-9a-zA-Z]*}}F // CHECK: [[TR4:%[0-9]+]] = function_ref @_T021transparent_attribute11testVarDeclV3maxSifg // CHECK: apply [[TR4]] } } struct testVarDeclShortenedSyntax { @_transparent static var max: Int { return 0xFF }; func testVarDeclShortenedSyntaxfoo () { var z: Int = testVarDeclShortenedSyntax.max // CHECK-APPLY: sil hidden @_T021transparent_attribute26testVarDeclShortenedSyntaxV0cdeF9Syntaxfoo{{[_0-9a-zA-Z]*}}F // CHECK: [[TR5:%[0-9]+]] = function_ref @_T021transparent_attribute26testVarDeclShortenedSyntaxV3maxSifgZ // CHECK: apply [[TR5]] } }; @_transparent var transparentOnGlobalVar: Int { get { return 0xFF } } // CHECK: sil hidden [transparent] @_T021transparent_attribute0A11OnGlobalVarSifg // Local functions in transparent context are fragile. @_transparent public func foo() { // CHECK-LABEL: sil shared [serialized] @_T021transparent_attribute3fooyyF3barL_yyF : $@convention(thin) () -> () func bar() {} bar() // CHECK-LABEL: sil shared [serialized] @_T021transparent_attribute3fooyyFyycfU_ : $@convention(thin) () -> () { let f: () -> () = {} f() // CHECK-LABEL: sil shared [serialized] @_T021transparent_attribute3fooyyF3zimL_yyF : $@convention(thin) () -> () { func zim() { // CHECK-LABEL: sil shared [serialized] @_T021transparent_attribute3fooyyF3zimL_yyF4zangL_yyF : $@convention(thin) () -> () { func zang() { } zang() } zim() } // Check that @_versioned entities have public linkage. // CHECK-LABEL: sil @_T021transparent_attribute25referencedFromTransparentyyF : $@convention(thin) () -> () { @_versioned func referencedFromTransparent() {} // CHECK-LABEL: sil [transparent] [serialized] @_T021transparent_attribute23referencesVersionedFuncyycyF : $@convention(thin) () -> @owned @callee_owned () -> () { @_transparent public func referencesVersionedFunc() -> () -> () { return referencedFromTransparent }
da94b0571f3b0fc0dc31bf95ab6670a9
28
163
0.683149
false
true
false
false
yendohu/SwiftIO
refs/heads/master
SwiftIO/UDPChannel.swift
mit
1
// // UDPMavlinkReceiver.swift // SwiftIO // // Created by Jonathan Wight on 4/22/15. // Copyright (c) 2015 schwa.io. All rights reserved. // import Foundation import Darwin public struct Datagram { public let from:Address public let timestamp:Timestamp public let data:NSData public init(from:Address, timestamp:Timestamp = Timestamp(), data:NSData) { self.from = from self.timestamp = timestamp self.data = data } } // MARK: - public var debugLog:(AnyObject? -> Void)? = println // MARK: - /** * A GCD based UDP listener. */ public class UDPChannel { enum ErrorCode:Int { case unknown = -1 } public var address:Address public var readHandler:(Datagram -> Void)? = loggingReadHandler public var errorHandler:(NSError -> Void)? = loggingErrorHandler private var resumed:Bool = false private var queue:dispatch_queue_t! private var source:dispatch_source_t! private var socket:Int32! public init(address:Address) { self.address = address } public convenience init(hostname:String, port:Int16, family:ProtocolFamily? = nil) { let addresses = Address.addresses(hostname, service:"\(port)", `protocol`: .UDP, family: family) self.init(address:addresses[0]) } public func resume() { debugLog?("Resuming") socket = Darwin.socket(PF_INET, SOCK_DGRAM, IPPROTO_UDP) if socket < 0 { handleError(code:.unknown, description: "TODO") return } var reuseSocketFlag:Int = 1 let result = Darwin.setsockopt(socket, SOL_SOCKET, SO_REUSEADDR, &reuseSocketFlag, socklen_t(sizeof(Int))) if result != 0 { cleanup() handleError(code:.unknown, description: "TODO") return } queue = dispatch_queue_create("io.schwa.SwiftIO.UDP", DISPATCH_QUEUE_CONCURRENT) if queue == nil { cleanup() handleError(code:.unknown, description: "TODO") return } source = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, UInt(socket), 0, queue) if queue == nil { cleanup() handleError(code:.unknown, description: "TODO") return } dispatch_source_set_cancel_handler(source) { debugLog?("Cancel handler") self.cleanup() self.resumed = false } dispatch_source_set_event_handler(source) { self.read() } dispatch_source_set_registration_handler(source) { debugLog?("Registration handler") var sockaddr = self.address.addr let result = Darwin.bind(self.socket, sockaddr.pointer, socklen_t(sockaddr.length)) if result != 0 { let error = self.makeError(code:.unknown, description: "TODO") self.errorHandler?(error) self.cancel() return } self.resumed = true debugLog?("We're good to go!") } dispatch_resume(source) } public func cancel() { assert(source != nil, "Cancel called with source = nil.") assert(resumed == true) dispatch_source_cancel(source) } public func send(data:NSData, address:Address! = nil, writeHandler:((Bool,NSError?) -> Void)? = loggingWriteHandler) { precondition(queue != nil, "Cannot send data without a queue") precondition(resumed == true, "Cannot send data on unresumed queue") dispatch_async(queue) { debugLog?("Send") let address:Address = address ?? self.address var sockaddr = address.addr var result = Darwin.sendto(self.socket, data.bytes, data.length, 0, sockaddr.pointer, socklen_t(sockaddr.length)) if result == data.length { writeHandler?(true, nil) } else if result < 0 { writeHandler?(false, self.makeError(code:.unknown, description: "TODO")) } if result < data.length { writeHandler?(false, self.makeError(code:.unknown, description: "TODO")) } } } internal func read() { var data:NSMutableData! = NSMutableData(length: 4096) let address = Address.with() { (addr:UnsafeMutablePointer<sockaddr>, inout addrlen:socklen_t) -> Void in let result = Darwin.recvfrom(socket, data.mutableBytes, data.length, 0, addr, &addrlen) if result < 0 { handleError(code:.unknown, description: "TODO") return } data.length = result } let datagram = Datagram(from: address, timestamp: Timestamp(), data: data) readHandler?(datagram) } internal func cleanup() { if let socket = self.socket { Darwin.close(socket) } self.socket = nil self.queue = nil self.source = nil } internal func makeError(code:ErrorCode = .unknown, description:String) -> NSError { let userInfo = [ NSLocalizedDescriptionKey: description ] let error = NSError(domain: "io.schwa.SwiftIO.Error", code: code.rawValue, userInfo: userInfo) return error } internal func handleError(code:ErrorCode = .unknown, description:String) { let error = makeError(code:code, description:description) errorHandler?(error) } } // MARK: - internal func loggingReadHandler(datagram:Datagram) { debugLog?("READ") } internal func loggingErrorHandler(error:NSError) { debugLog?("ERROR: \(error)") } internal func loggingWriteHandler(success:Bool, error:NSError?) { if success { debugLog?("WRITE") } else { loggingErrorHandler(error!) } }
ad0bccbc851ac9106f943497c3ec4258
27.495146
125
0.590971
false
false
false
false
wfleming/pico-block
refs/heads/master
pblock/Models/Rule.swift
mit
1
// // Rule.swift // pblock // // Created by Will Fleming on 7/10/15. // Copyright © 2015 PBlock. All rights reserved. // import Foundation import CoreData @objc(Rule) class Rule: NSManagedObject { // intitialize from a ParsedRule in the default object context convenience init(inContext: NSManagedObjectContext, parsedRule: ParsedRule) { self.init(inContext: inContext) sourceText = parsedRule.sourceText actionType = parsedRule.actionType actionSelector = parsedRule.actionSelector triggerUrlFilter = parsedRule.triggerUrlFilter triggerResourceTypes = parsedRule.triggerResourceTypes triggerLoadTypes = parsedRule.triggerLoadTypes if let ifDomains = parsedRule.triggerIfDomain { triggerIfDomain = NSOrderedSet(array: ifDomains.map({ (domainStr) -> RuleDomain in let d = RuleDomain(inContext: inContext) d.domain = domainStr return d })) } if let unlessDomains = parsedRule.triggerUnlessDomain { triggerUnlessDomain = NSOrderedSet(array: unlessDomains.map({ (domainStr) -> RuleDomain in let d = RuleDomain(inContext: inContext) d.domain = domainStr return d })) } } var actionType: RuleActionType { get { if nil == actionTypeRaw { return RuleActionType.Invalid } else { let rawVal = actionTypeRaw!.shortValue if let enumVal = RuleActionType(rawValue: rawVal) { return enumVal } else { return RuleActionType.Invalid } } } set(newValue) { actionTypeRaw = NSNumber(short: newValue.rawValue) } } /** NB: this is a bit tricky in that you can mutuate the options values, but then the set logic won't get triggered, so the coredata serialized value won't be updated. So, for now, never mutate the value of loadTypes on an instance, always set it to a new value. i.e. don't use unionInPlace. */ var triggerLoadTypes: RuleLoadTypeOptions { get { if nil == triggerLoadTypeRaw { return RuleLoadTypeOptions.None } else { return RuleLoadTypeOptions(rawValue: triggerLoadTypeRaw!.shortValue) } } set(newValue) { if newValue == RuleLoadTypeOptions.None { triggerLoadTypeRaw = nil } else { triggerLoadTypeRaw = NSNumber(short: newValue.rawValue) } } } // NB: same caution as loadTypes above var triggerResourceTypes: RuleResourceTypeOptions { get { if nil == triggerResourceTypeRaw { return RuleResourceTypeOptions.None } else { return RuleResourceTypeOptions(rawValue: triggerResourceTypeRaw!.shortValue) } } set(newValue) { if newValue == RuleResourceTypeOptions.None { triggerResourceTypeRaw = nil } else { triggerResourceTypeRaw = NSNumber(short: newValue.rawValue) } } } // return the WebKit Content Blocker JSON for this rule func asJSON() -> Dictionary<String, AnyObject> { var actionJSON = Dictionary<String, AnyObject>(), triggerJSON = Dictionary<String, AnyObject>() actionJSON["type"] = actionType.jsonValue() if let cssSelector = actionSelector { actionJSON["selector"] = cssSelector } if let urlFilter = triggerUrlFilter { triggerJSON["url-filter"] = urlFilter } if let resourceTypes = triggerResourceTypes.jsonValue() { triggerJSON["resource-type"] = resourceTypes } if let loadTypes = triggerLoadTypes.jsonValue() { triggerJSON["load-type"] = loadTypes } if let ifDomains = triggerIfDomain?.array where ifDomains.count > 0 { triggerJSON["if-domain"] = ifDomains.map { $0.domain } } if let unlessDomains = triggerUnlessDomain?.array where unlessDomains.count > 0 { triggerJSON["unless-domain"] = unlessDomains.map { $0.domain } } return [ "action": actionJSON, "trigger": triggerJSON, ] } }
221e50c9b204194ca6125bd934aafa74
28.893939
99
0.666244
false
false
false
false
asp2insp/CodePathFinalProject
refs/heads/master
Pretto/Utils.swift
mit
1
// // Utils.swift // Pretto // // Created by Francisco de la Pena on 6/23/15. // Copyright (c) 2015 Pretto. All rights reserved. // import Foundation let titleForCachingImagesQueue = "co.twisterlabs.Pretto.caching" var GlobalMainQueue: dispatch_queue_t { return dispatch_get_main_queue() } var GlobalUserInteractiveQueue: dispatch_queue_t { return dispatch_get_global_queue(Int(QOS_CLASS_USER_INTERACTIVE.value), 0) } var GlobalUserInitiatedQueue: dispatch_queue_t { return dispatch_get_global_queue(Int(QOS_CLASS_USER_INITIATED.value), 0) } var GlobalUtilityQueue: dispatch_queue_t { return dispatch_get_global_queue(Int(QOS_CLASS_UTILITY.value), 0) } var GlobalBackgroundQueue: dispatch_queue_t { return dispatch_get_global_queue(Int(QOS_CLASS_BACKGROUND.value), 0) } var CustomImageCachingQueue: dispatch_queue_t { return dispatch_queue_create(titleForCachingImagesQueue, DISPATCH_QUEUE_CONCURRENT) } // Auxiliary Functions func delay(delay:Double, closure:()->()) { dispatch_after( dispatch_time( DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)) ), dispatch_get_main_queue(), closure) } func openWebsiteInSafari() { UIApplication.sharedApplication().openURL(NSURL(string: "http://www.pretto.co")!) } func printAppStatus() { switch UIApplication.sharedApplication().applicationState { case .Active: println("UIApplicationState = Active") case .Inactive: println("UIApplicationState = Inactive") case .Background: println("UIApplicationState = Background") default: println("UIApplicationState = Unknown") } } func printBackgroundRefreshStatus() { switch UIApplication.sharedApplication().backgroundRefreshStatus { case .Available: println("UIBackgroundRefreshStatus = Active") default: println("UIBackgroundRefreshStatus = Restricted or Denied") } } func printBackgroundRemainingTime() { println("Application BackgroundTimeRemaining: \(UIApplication.sharedApplication().backgroundTimeRemaining)") } // Animated Transitions // Remember to remove snapshots from supperview in the completion block when calling this methods: // // animateFromLeftToRight(destinationVC, snapshotOut, snapshotIn) { (success) -> () in // self.dismissViewControllerAnimated(false, completion: { () -> Void in // snapshotIn.removeFromSuperview() // snapshotOut.removeFromSuperview() // } // } // func animateFromRightToLeft(destinationViewController: UIViewController, initialSnapshot: UIView, finalSnapShot: UIView, completion: (success: Bool) -> ()) { initialSnapshot.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) finalSnapShot.frame = CGRect(x: UIScreen.mainScreen().bounds.width, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) UIApplication.sharedApplication().keyWindow!.addSubview(initialSnapshot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(initialSnapshot) UIApplication.sharedApplication().keyWindow!.addSubview(finalSnapShot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(finalSnapShot) UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in initialSnapshot.center = CGPoint(x: -(UIScreen.mainScreen().bounds.width / 2), y: UIScreen.mainScreen().bounds.height / 2) finalSnapShot.center = CGPoint(x: UIScreen.mainScreen().bounds.width / 2, y: UIScreen.mainScreen().bounds.height / 2) }) { (success:Bool) -> Void in completion(success: success) } } func animateFromLeftToRight(destinationViewController: UIViewController, initialSnapshot: UIView, finalSnapShot: UIView, completion: (success: Bool) -> ()) { initialSnapshot.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) finalSnapShot.frame = CGRect(x: -UIScreen.mainScreen().bounds.width, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) UIApplication.sharedApplication().keyWindow!.addSubview(initialSnapshot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(initialSnapshot) UIApplication.sharedApplication().keyWindow!.addSubview(finalSnapShot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(finalSnapShot) UIView.animateWithDuration(0.3, delay: 0, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in initialSnapshot.center = CGPoint(x: UIScreen.mainScreen().bounds.width * 1.5, y: UIScreen.mainScreen().bounds.height / 2) finalSnapShot.center = CGPoint(x: UIScreen.mainScreen().bounds.width / 2, y: UIScreen.mainScreen().bounds.height / 2) }) { (success:Bool) -> Void in completion(success: success) } } func animateShrink(destinationViewController: UIViewController, initialSnapshot: UIView, finalSnapShot: UIView, completion: (success: Bool) -> ()) { initialSnapshot.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) finalSnapShot.frame = CGRect(x: 0, y: 0, width: UIScreen.mainScreen().bounds.width, height: UIScreen.mainScreen().bounds.height) UIApplication.sharedApplication().keyWindow!.addSubview(finalSnapShot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(finalSnapShot) UIApplication.sharedApplication().keyWindow!.addSubview(initialSnapshot) UIApplication.sharedApplication().keyWindow!.bringSubviewToFront(initialSnapshot) UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 1, options: UIViewAnimationOptions.CurveEaseOut, animations: { () -> Void in initialSnapshot.transform = CGAffineTransformMakeScale(0.01, 0.01) }) { (success:Bool) -> Void in completion(success: success) } }
c273adfd61b8d7f75d717a127571b6e0
44.088889
174
0.734965
false
false
false
false
joalbright/Gameboard
refs/heads/master
Gameboards.playground/Sources/Boards/Chess.swift
apache-2.0
1
import UIKit public struct Chess { public enum PieceType: String { case none = " " case rook1 = "♜" case knight1 = "♞" case bishop1 = "♝" case queen1 = "♛" case king1 = "♚" case pawn1 = "♟" case rook2 = "♖" case knight2 = "♘" case bishop2 = "♗" case queen2 = "♕" case king2 = "♔" case pawn2 = "♙" } public static var board: Grid { return Grid([ "♜♞♝♛♚♝♞♜".array(), 8 ✕ "♟", 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ EmptyPiece, 8 ✕ "♙", "♖♘♗♕♔♗♘♖".array() ]) } public static let playerPieces = ["♜♞♝♛♚♝♞♜♟","♖♘♗♕♔♗♘♖♙"] public static func validateEmptyPath(_ s1: Square, _ s2: Square, _ grid: Grid) throws { let mRow = s2.0 - s1.0 let mCol = s2.1 - s1.1 let d1 = mRow == 0 ? 0 : mRow > 0 ? 1 : -1 let d2 = mCol == 0 ? 0 : mCol > 0 ? 1 : -1 var p1 = s1.0 + d1, p2 = s1.1 + d2 while p1 != s2.0 || p2 != s2.1 { guard grid[p1,p2] == EmptyPiece else { throw MoveError.blockedmove } p1 += d1 p2 += d2 } } public static func validateMove(_ s1: Square, _ s2: Square, _ p1: Piece, _ p2: Piece, _ grid: Grid, _ hint: Bool = false) throws -> Piece? { let mRow = s2.0 - s1.0 let mCol = s2.1 - s1.1 // let dR = mRow == 0 ? 0 : mRow > 0 ? 1 : -1 // let dC = mCol == 0 ? 0 : mCol > 0 ? 1 : -1 switch PieceType(rawValue: p1) ?? .none { case .bishop1, .bishop2: guard abs(mRow) == abs(mCol) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .king1, .king2: guard abs(mRow) < 2 && abs(mCol) < 2 else { throw MoveError.invalidmove } case .knight1, .knight2: guard (abs(mRow) == 2 && abs(mCol) == 1) || (abs(mRow) == 1 && abs(mCol) == 2) else { throw MoveError.invalidmove } case .pawn1: guard (abs(mCol) == 0 && p2 == EmptyPiece) || (abs(mCol) == 1 && mRow == 1 && p2 != EmptyPiece) else { throw MoveError.invalidmove } guard (mRow < 2 && mRow > 0) || (s1.0 == 1 && mRow == 2) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .pawn2: guard (abs(mCol) == 0 && p2 == EmptyPiece) || (abs(mCol) == 1 && mRow == -1 && p2 != EmptyPiece) else { throw MoveError.invalidmove } guard (mRow > -2 && mRow < 0) || (s1.0 == 6 && mRow == -2) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .queen1, .queen2: guard mRow == 0 || mCol == 0 || abs(mRow) == abs(mCol) else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .rook1, .rook2: guard mRow == 0 || mCol == 0 else { throw MoveError.invalidmove } try validateEmptyPath(s1, s2, grid) case .none: throw MoveError.incorrectpiece } guard !hint else { return nil } let piece = grid[s2.0,s2.1] grid[s2.0,s2.1] = p1 // place my piece in target square grid[s1.0,s1.1] = EmptyPiece // remove my piece from original square return piece } } // Coordinates public let A8 = ("a",8), A7 = ("a",7), A6 = ("a",6), A5 = ("a",5), A4 = ("a",4), A3 = ("a",3), A2 = ("a",2), A1 = ("a",1) public let B8 = ("b",8), B7 = ("b",7), B6 = ("b",6), B5 = ("b",5), B4 = ("b",4), B3 = ("b",3), B2 = ("b",2), B1 = ("b",1) public let C8 = ("c",8), C7 = ("c",7), C6 = ("c",6), C5 = ("c",5), C4 = ("c",4), C3 = ("c",3), C2 = ("c",2), C1 = ("c",1) public let D8 = ("d",8), D7 = ("d",7), D6 = ("d",6), D5 = ("d",5), D4 = ("d",4), D3 = ("d",3), D2 = ("d",2), D1 = ("d",1) public let E8 = ("e",8), E7 = ("e",7), E6 = ("e",6), E5 = ("e",5), E4 = ("e",4), E3 = ("e",3), E2 = ("e",2), E1 = ("e",1) public let F8 = ("f",8), F7 = ("f",7), F6 = ("f",6), F5 = ("f",5), F4 = ("f",4), F3 = ("f",3), F2 = ("f",2), F1 = ("f",1) public let G8 = ("g",8), G7 = ("g",7), G6 = ("g",6), G5 = ("g",5), G4 = ("g",4), G3 = ("g",3), G2 = ("g",2), G1 = ("g",1) public let H8 = ("h",8), H7 = ("h",7), H6 = ("h",6), H5 = ("h",5), H4 = ("h",4), H3 = ("h",3), H2 = ("h",2), H1 = ("h",1)
f46d960168fb230444ceacc1d5be947d
33.978102
145
0.412563
false
false
false
false
zjjzmw1/SwiftCodeFragments
refs/heads/master
SwiftCodeFragments/CodeFragments/Category/UIKitCategory/UINavigationItem/UINavigationItem+JCLoading.swift
mit
1
// // UINavigationItem+JCLoading.swift // JCSwiftKitDemo // // Created by molin.JC on 2017/1/22. // Copyright © 2017年 molin. All rights reserved. // import UIKit private var _kLoading = "kLoading"; extension UINavigationItem { func startLoadingAnimating() { self.stopLoadingAnimating(); objc_setAssociatedObject(self, _kLoading, self.titleView, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC); let loader = UIActivityIndicatorView.init(activityIndicatorStyle: UIActivityIndicatorViewStyle.gray); self.titleView = loader; loader.startAnimating(); } func stopLoadingAnimating() { let componentToRestore = objc_getAssociatedObject(self, _kLoading); self.titleView = componentToRestore as! UIView?; objc_setAssociatedObject(self, _kLoading, nil, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC); } }
22a8252f631aa7292c3da9c9403ec056
31.571429
124
0.714912
false
false
false
false
noppoMan/aws-sdk-swift
refs/heads/main
Sources/Soto/Services/WorkDocs/WorkDocs_Error.swift
apache-2.0
1
//===----------------------------------------------------------------------===// // // This source file is part of the Soto for AWS open source project // // Copyright (c) 2017-2020 the Soto project authors // Licensed under Apache License v2.0 // // See LICENSE.txt for license information // See CONTRIBUTORS.txt for the list of Soto project authors // // SPDX-License-Identifier: Apache-2.0 // //===----------------------------------------------------------------------===// // THIS FILE IS AUTOMATICALLY GENERATED by https://github.com/soto-project/soto/tree/main/CodeGenerator. DO NOT EDIT. import SotoCore /// Error enum for WorkDocs public struct WorkDocsErrorType: AWSErrorType { enum Code: String { case concurrentModificationException = "ConcurrentModificationException" case conflictingOperationException = "ConflictingOperationException" case customMetadataLimitExceededException = "CustomMetadataLimitExceededException" case deactivatingLastSystemUserException = "DeactivatingLastSystemUserException" case documentLockedForCommentsException = "DocumentLockedForCommentsException" case draftUploadOutOfSyncException = "DraftUploadOutOfSyncException" case entityAlreadyExistsException = "EntityAlreadyExistsException" case entityNotExistsException = "EntityNotExistsException" case failedDependencyException = "FailedDependencyException" case illegalUserStateException = "IllegalUserStateException" case invalidArgumentException = "InvalidArgumentException" case invalidCommentOperationException = "InvalidCommentOperationException" case invalidOperationException = "InvalidOperationException" case invalidPasswordException = "InvalidPasswordException" case limitExceededException = "LimitExceededException" case prohibitedStateException = "ProhibitedStateException" case requestedEntityTooLargeException = "RequestedEntityTooLargeException" case resourceAlreadyCheckedOutException = "ResourceAlreadyCheckedOutException" case serviceUnavailableException = "ServiceUnavailableException" case storageLimitExceededException = "StorageLimitExceededException" case storageLimitWillExceedException = "StorageLimitWillExceedException" case tooManyLabelsException = "TooManyLabelsException" case tooManySubscriptionsException = "TooManySubscriptionsException" case unauthorizedOperationException = "UnauthorizedOperationException" case unauthorizedResourceAccessException = "UnauthorizedResourceAccessException" } private let error: Code public let context: AWSErrorContext? /// initialize WorkDocs public init?(errorCode: String, context: AWSErrorContext) { guard let error = Code(rawValue: errorCode) else { return nil } self.error = error self.context = context } internal init(_ error: Code) { self.error = error self.context = nil } /// return error code string public var errorCode: String { self.error.rawValue } /// The resource hierarchy is changing. public static var concurrentModificationException: Self { .init(.concurrentModificationException) } /// Another operation is in progress on the resource that conflicts with the current operation. public static var conflictingOperationException: Self { .init(.conflictingOperationException) } /// The limit has been reached on the number of custom properties for the specified resource. public static var customMetadataLimitExceededException: Self { .init(.customMetadataLimitExceededException) } /// The last user in the organization is being deactivated. public static var deactivatingLastSystemUserException: Self { .init(.deactivatingLastSystemUserException) } /// This exception is thrown when the document is locked for comments and user tries to create or delete a comment on that document. public static var documentLockedForCommentsException: Self { .init(.documentLockedForCommentsException) } /// This exception is thrown when a valid checkout ID is not presented on document version upload calls for a document that has been checked out from Web client. public static var draftUploadOutOfSyncException: Self { .init(.draftUploadOutOfSyncException) } /// The resource already exists. public static var entityAlreadyExistsException: Self { .init(.entityAlreadyExistsException) } /// The resource does not exist. public static var entityNotExistsException: Self { .init(.entityNotExistsException) } /// The AWS Directory Service cannot reach an on-premises instance. Or a dependency under the control of the organization is failing, such as a connected Active Directory. public static var failedDependencyException: Self { .init(.failedDependencyException) } /// The user is undergoing transfer of ownership. public static var illegalUserStateException: Self { .init(.illegalUserStateException) } /// The pagination marker or limit fields are not valid. public static var invalidArgumentException: Self { .init(.invalidArgumentException) } /// The requested operation is not allowed on the specified comment object. public static var invalidCommentOperationException: Self { .init(.invalidCommentOperationException) } /// The operation is invalid. public static var invalidOperationException: Self { .init(.invalidOperationException) } /// The password is invalid. public static var invalidPasswordException: Self { .init(.invalidPasswordException) } /// The maximum of 100,000 folders under the parent folder has been exceeded. public static var limitExceededException: Self { .init(.limitExceededException) } /// The specified document version is not in the INITIALIZED state. public static var prohibitedStateException: Self { .init(.prohibitedStateException) } /// The response is too large to return. The request must include a filter to reduce the size of the response. public static var requestedEntityTooLargeException: Self { .init(.requestedEntityTooLargeException) } /// The resource is already checked out. public static var resourceAlreadyCheckedOutException: Self { .init(.resourceAlreadyCheckedOutException) } /// One or more of the dependencies is unavailable. public static var serviceUnavailableException: Self { .init(.serviceUnavailableException) } /// The storage limit has been exceeded. public static var storageLimitExceededException: Self { .init(.storageLimitExceededException) } /// The storage limit will be exceeded. public static var storageLimitWillExceedException: Self { .init(.storageLimitWillExceedException) } /// The limit has been reached on the number of labels for the specified resource. public static var tooManyLabelsException: Self { .init(.tooManyLabelsException) } /// You've reached the limit on the number of subscriptions for the WorkDocs instance. public static var tooManySubscriptionsException: Self { .init(.tooManySubscriptionsException) } /// The operation is not permitted. public static var unauthorizedOperationException: Self { .init(.unauthorizedOperationException) } /// The caller does not have access to perform the action on the resource. public static var unauthorizedResourceAccessException: Self { .init(.unauthorizedResourceAccessException) } } extension WorkDocsErrorType: Equatable { public static func == (lhs: WorkDocsErrorType, rhs: WorkDocsErrorType) -> Bool { lhs.error == rhs.error } } extension WorkDocsErrorType: CustomStringConvertible { public var description: String { return "\(self.error.rawValue): \(self.message ?? "")" } }
60ae3aa4ad35f41be6c16c3aab43b31f
59.511628
175
0.748911
false
false
false
false
AllenLucian/lxmwb
refs/heads/master
lxmwb/lxmwb/class/Main/TabBarViewController.swift
mit
1
// // TabBarViewController.swift // lxmwb // // Created by FutureHub on 2017/10/7. // Copyright © 2017年 Westrice. All rights reserved. // import UIKit class TabBarViewController: UITabBarController { lazy var btn : UIButton = UIButton(type: UIButtonType.custom) override func viewDidLoad() { super.viewDidLoad() self.setUpControllers() } override func viewWillAppear(_ animated: Bool) { super.viewWillAppear(true) self.setBtn() } /// 设置子控制器 func setUpControllers(){ addChildViewControllers(viewController: "WBViewController", title: "微博", imageNamed: "tabbar_home") addChildViewControllers(viewController: "DiscoverViewController", title: "发现", imageNamed: "tabbar_discover") addChildViewController(CenterViewController()) addChildViewControllers(viewController: "MessageViewController", title: "消息", imageNamed: "tabbar_message_center") addChildViewControllers(viewController: "MYViewController", title: "我", imageNamed: "tabbar_profile") } } // MARK:Tabbar中间的加好按钮 extension TabBarViewController { func setBtn() { /// 按钮的宽度 let btnWidth = tabBar.bounds.width / CGFloat((viewControllers?.count)!) + 1 /// 按钮的x值 let btnX = btnWidth * 2 /// iphoneX的高度 let iphoneXHeight : CGFloat = 812.0 /// 按钮的y值 var btnY = btn.frame.origin.y //1.设置按钮的背景颜色 self.btn.setBackgroundImage(UIImage(named:"tabbar_compose_button"), for: .normal) //2.设置按钮高亮状态下的背景颜色 self.btn.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), for: .highlighted) //3.设置按钮的图标 self.btn.setImage(UIImage(named:"tabbar_compose_icon_add"), for: .normal) self.btn.setImage(UIImage(named:"tabbar_compose_icon_add_highlighted"), for: .highlighted) /// 按钮的frame self.tabBar.addSubview(btn) if UIScreen.main.bounds.height == iphoneXHeight { btnY = 5 }else{ btnY = 0 } self.btn.frame = CGRect(x: btnX, y: btnY, width: btnWidth, height: tabBar.bounds.height) } } // MARK:创建控制器 extension TabBarViewController { /// 创建控制器 /// - parameter viewController : 子控制器名称 /// - parameter title : 子控制器的标题 /// - parameter imageNamed : 子控制器的图片 func addChildViewControllers(viewController:String,title:String,imageNamed:String) { //1.动态获取命名空间 let nameSpace = Bundle.main.infoDictionary?["CFBundleExecutable"] as! String //2.告诉编译器类型暂时是class let cls : AnyClass = NSClassFromString(nameSpace + "." + viewController)! //3.告诉编译器真实的类型是BaseViewController let vcCls = cls as! BaseViewController.Type //4.实例化控制器 let vc = vcCls.init() //5.从内向外设置,这样tabbar和nav都有 vc.title = title vc.tabBarItem.image = UIImage(named:imageNamed) vc.tabBarItem.selectedImage = UIImage(named:imageNamed + "_highlighted") //6.设置文字效果 self.tabBar.tintColor = UIColor.black //7.创建导航控制器 let nav = navViewController() nav.addChildViewController(vc) //8.把导航控制器添加到tabbar self.addChildViewController(nav) } }
12480a7a5d81788e133b993c61f1cf1a
32.12
122
0.631341
false
false
false
false
gabrielfalcao/MusicKit
refs/heads/master
Playgrounds/UnalteredExtendedChords.playground/Contents.swift
mit
2
import MusicKit let unalteredTetrads = ChordQuality.UnalteredTetrads // (symbols, intervals) var unalteredPentads = ([String](), [String]()) var unalteredHexads = ([String](), [String]()) var unalteredHeptads = ([String](), [String]()) for q in unalteredTetrads { // pentad symbols var name = q.name.stringByReplacingOccurrencesOfString("Seventh", withString: "Ninth") var symbol = q.description.stringByReplacingOccurrencesOfString("7", withString: "9") var symbolLine = "case \(name) = \"\(symbol)\"" unalteredPentads.0.append(symbolLine) // pentad intervals var intervals = MKUtil.intervals( MKUtil.semitoneIndices(q.intervals) + [Float(ChordExtension.Nine.rawValue)]) var intIntervals = [Int]() for i in intervals { intIntervals.append(Int(i)) } var intervalLine = "case \(name): return \(intIntervals)" unalteredPentads.1.append(intervalLine) // hexad symbols name = q.name.stringByReplacingOccurrencesOfString("Seventh", withString: "Eleventh") symbol = q.description.stringByReplacingOccurrencesOfString("7", withString: "11") symbolLine = "case \(name) = \"\(symbol)\"" unalteredHexads.0.append(symbolLine) // hexad intervals intervals = MKUtil.intervals( MKUtil.semitoneIndices(q.intervals) + [Float(ChordExtension.Nine.rawValue), Float(ChordExtension.Eleven.rawValue)]) intIntervals.removeAll() for i in intervals { intIntervals.append(Int(i)) } intervalLine = "case \(name): return \(intIntervals)" unalteredHexads.1.append(intervalLine) // heptad symbols name = q.name.stringByReplacingOccurrencesOfString("Seventh", withString: "Thirteenth") symbol = q.description.stringByReplacingOccurrencesOfString("7", withString: "13") symbolLine = "case \(name) = \"\(symbol)\"" unalteredHeptads.0.append(symbolLine) // heptad intervals intervals = MKUtil.intervals( MKUtil.semitoneIndices(q.intervals) + [Float(ChordExtension.Nine.rawValue), Float(ChordExtension.Eleven.rawValue), Float(ChordExtension.Thirteen.rawValue)]) intIntervals.removeAll() for i in intervals { intIntervals.append(Int(i)) } intervalLine = "case \(name): return \(intIntervals)" unalteredHeptads.1.append(intervalLine) } func printCode(groupName: String, symbols: [String], intervals: [String]) { print("// \(groupName)\n") symbols.map { print("\($0)\n") } print("\n") print("// \(groupName)\n") intervals.map { print("\($0)\n") } print("\n") } printCode("unaltered pentads", unalteredPentads.0, unalteredPentads.1) printCode("unaltered hexads", unalteredHexads.0, unalteredHexads.1) printCode("unaltered heptads", unalteredHeptads.0, unalteredHeptads.1)
bbe80fc21f4826368260435afc273be6
39.085714
91
0.685317
false
false
false
false
AnRanScheme/MagiRefresh
refs/heads/master
Example/MagiRefresh/Example/PlaceHolderExample/TableViewController.swift
mit
1
// // TableViewController.swift // magiLoadingPlaceHolder // // Created by 安然 on 2018/8/6. // Copyright © 2018年 anran. All rights reserved. // import UIKit class TableViewController: UITableViewController { var items = [String]() var sections = 1 var isSelected = false @IBAction func addAction(_ sender: UIBarButtonItem) { items.append("添加一行数据") tableView.reloadData() } @IBAction func deleteAction(_ sender: Any) { if items.count > 0 { items.removeLast() tableView.reloadData() } } @IBAction func changeAction(_ sender: UIBarButtonItem) { changeBarAction(sender) } override func viewDidLoad() { super.viewDidLoad() setupUI() } deinit { print(self.debugDescription+"------销毁了") } fileprivate func setupUI() { navigationController?.navigationBar.isTranslucent = false tableView.separatorStyle = .none tableView.register( UITableViewCell.self, forCellReuseIdentifier: "reuseIdentifier") if #available(iOS 11.0, *) { tableView.contentInsetAdjustmentBehavior = .never } else { automaticallyAdjustsScrollViewInsets = false } self.navigationController?.navigationBar.setBackgroundImage(UIImage(), for: UIBarMetrics.default) tableView.magiRefresh.bindStyleForFooterRefresh( themeColor: UIColor.cyan, refreshStyle: MagiRefreshStyle.animatableArrow) { [weak self] in self?.tableView.magiRefresh.footer?.endRefreshingWithAlertText("", completion: nil) self?.tableView.reloadData() print("bindStyleForFooterRefresh") } let header = MagiArrowHeader() header.magiRefreshingClosure { [weak self] in self?.tableView.magiRefresh.header?.endRefreshing() self?.tableView.reloadData() print("bindStyleForHeaderRefresh") } tableView.magiRefresh.header = header /* tableView.magiRefresh.bindStyleForHeaderRefresh( themeColor: UIColor.cyan, refreshStyle: MagiRefreshStyle.animatableArrow) { [weak self] in self?.tableView.magiRefresh.header?.endRefreshing() self?.tableView.reloadData() print("bindStyleForHeaderRefresh") } */ setupCustomPlaceHolderView() } //自定义空数据界面显示 fileprivate func setupCustomPlaceHolderView() { let emptyView = Bundle.main.loadNibNamed( "MyEmptyView", owner: self, options: nil)?.last as! MyEmptyView emptyView.reloadBtn.addTarget( self, action: #selector(reloadBtnAction(_:)), for: .touchUpInside) emptyView.frame = view.bounds //空数据界面显示 let placeHolder = MagiPlaceHolder.createCustomPlaceHolder(emptyView) tableView.magiRefresh.placeHolder = placeHolder tableView.magiRefresh.placeHolder?.tapBlankViewClosure = { print("点击界面空白区域") } tableView.magiRefresh.showPlaceHolder() } @objc fileprivate func reloadBtnAction(_ sender: UIButton) { print("点击刷新按钮") } @objc fileprivate func changeBarAction(_ sender: UIBarButtonItem) { if isSelected { isSelected = false setupCustomPlaceHolderView() } else { isSelected = true //空数据界面显示 let placeHolder = MagiPlaceHolder.createPlaceHolderWithClosure( imageName: "search_noData", title: "暂无数据", detailTitle: "", refreshBtnTitle: "") { print("点击刷新按钮") } placeHolder.contentViewOffset = -100 placeHolder.titleLabFont = UIFont.systemFont(ofSize: 18) placeHolder.titleLabTextColor = UIColor.purple tableView.magiRefresh.placeHolder = placeHolder tableView.magiRefresh.placeHolder?.tapBlankViewClosure = { print("点击界面空白区域") } tableView.magiRefresh.showPlaceHolder() } } } // MARK: - Table view data source extension TableViewController { override func numberOfSections(in tableView: UITableView) -> Int { return sections } override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "reuseIdentifier", for: indexPath) cell.textLabel?.text = items[indexPath.item] return cell } override func tableView(_ tableView: UITableView, canEditRowAt indexPath: IndexPath) -> Bool { return true } override func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) { if editingStyle == .delete { items.removeLast() tableView.deleteRows(at: [indexPath], with: .automatic) } } override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { let item = items[indexPath.item] switch item { case "点击重新加载": items.removeAll() tableView.reloadData() case "点击添加行": tableView.beginUpdates() items.append("new row") tableView.insertRows(at: [IndexPath(row: tableView.numberOfRows(inSection: indexPath.section), section: indexPath.section)], with: .automatic) tableView.endUpdates() case "点击删除行": tableView.beginUpdates() items.removeLast() let index = IndexPath(row: tableView.numberOfRows(inSection: indexPath.section) - 1, section: indexPath.section) tableView.deleteRows(at: [index], with: .automatic) tableView.endUpdates() default: break } } }
f21956fb5137a7e3af09df5ff95036f8
32.793478
154
0.608234
false
false
false
false
dkulundzic/SqliteDatabase
refs/heads/master
SqliteDatabase/Todo.swift
mit
1
// // Todo.swift // SqliteDatabase // // Created by Domagoj Kulundžić on 03/02/17. // Copyright © 2017 InBetweeners. All rights reserved. // import Foundation import SqliteDatabase public struct Todo { public let description: String public let completed: Bool public init(description: String, completed: Bool = false) { self.description = description self.completed = completed } } extension Todo: SqliteDatabaseMappable { public static var columns: [String] { return [ "Description", "Completed" ] } public init?(row: SqliteDatabaseRow) { guard let description = row["Description"] as? String, let completed = row["Completed"] as? Bool else { return nil } self.description = description self.completed = completed } public func values() -> [Any?] { var values = [Any?]() values.append(description as Any?) values.append(completed as Any?) return values } }
0b0cb8959c8626122e67129ffe6575a0
21.1
63
0.578281
false
false
false
false
uphold/uphold-sdk-ios
refs/heads/master
Source/Model/Transaction/Merchant.swift
mit
1
import Foundation import ObjectMapper /// Denomination model. public class Merchant: Mappable { /// The city of the merchant. public private(set) final var city: String? /// The country of the merchant. public private(set) final var country: String? /// The name of the merchant. public private(set) final var name: String? /// The state of the merchant. public private(set) final var state: String? /// The zip code of the merchant. public private(set) final var zipCode: String? /** Constructor. - parameter city: The city of the merchant. - parameter country: The country of the merchant. - parameter name: The name of the merchant. - parameter state: The state of the merchant. - parameter zipCode: The zipCode of the merchant. */ public init(city: String, country: String, name: String, state: String, zipCode: String) { self.city = city self.country = country self.name = name self.state = state self.zipCode = zipCode } // MARK: Required by the ObjectMapper. /** Constructor. - parameter map: Mapping data object. */ required public init?(map: Map) { } /** Maps the JSON to the Object. - parameter map: The object to map. */ public func mapping(map: Map) { city <- map["city"] country <- map["country"] name <- map["name"] state <- map["state"] zipCode <- map["zipCode"] } }
9a9c472a2710f6d46742233f120c6acb
23.612903
94
0.606815
false
false
false
false
cam-hop/APIUtility
refs/heads/master
RxSwiftFluxDemo/RxSwiftFluxDemo/Model/SubcriberDataSource.swift
mit
1
// // SubcriberDataSource.swift // DemoApp // // Created by DUONG VANHOP on 2017/06/14. // Copyright © 2017年 DUONG VANHOP. All rights reserved. // import UIKit import RxSwift import RxCocoa final class SubcriberDataSource: NSObject { weak var tableView: UITableView? let subcribers = Variable<[Subcriber]>([]) fileprivate let subcriberStore: SubcriberStore = .shared func register(tableView: UITableView) { tableView.dataSource = self tableView.delegate = self tableView.tableFooterView = UIView() tableView.registerCell(cell: SubcriberCell.self) self.tableView = tableView observeStore() } private func observeStore() { subcriberStore.subcribers.asObservable() .subscribe(onNext: { [unowned self] elements in self.subcribers.value = elements self.tableView?.reloadData() }) .addDisposableTo(rx_disposeBag) } } extension SubcriberDataSource: UITableViewDataSource { func numberOfSections(in tableView: UITableView) -> Int { return 1 } func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return subcribers.value.count } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(type: SubcriberCell.self) cell.configure(subcriber: subcribers.value[indexPath.row]) return cell } } extension SubcriberDataSource: UITableViewDelegate { func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat { return 60.5 } } extension SubcriberDataSource: UIScrollViewDelegate { func scrollViewDidEndDragging(_ scrollView: UIScrollView, willDecelerate decelerate: Bool) { } }
54fd647083428adc034994018d850acc
26.441176
100
0.684352
false
false
false
false
tectijuana/patrones
refs/heads/master
Bloque1SwiftArchivado/PracticasSwift/OrtegaAshley/Practica1.swift
gpl-3.0
1
// "Instituto Tecnologico de Tijuana", // "Semestre Enero-Junio 2017", // "Patrones de Diseño", // "Ortega Rodriguez Ashley Karina 12211430", // "Pasar de grados a radianes usando multiplos de 10 grados. Desde 0 grados hasta 360 grados" import Foundation print("Pasar de grados a radianes usando multiplos de 10 grados. Desde 0 grados hasta 360 grados") // "Declaracion de variables" var pi:Float=Float.pi print("Valor de Pi= \(pi)") var radianes:Float=180 print("Pi Radianes = \(radianes)") print("Para obtener los radianes, se multiplica los grados que se desean convertir por pi y se divine entre pi radianes(180)") print("0 Grados= ",(pi*0)/radianes) print("10 Grados= ",(pi*10)/radianes) print("20 Grados= ",(pi*20)/radianes) print("30 Grados= ",(pi*30)/radianes) print("40 Grados= ",(pi*40)/radianes) print("50 Grados= ",(pi*50)/radianes) print("60 Grados= ",(pi*60)/radianes) print("70 Grados= ",(pi*70)/radianes) print("80 Grados= ",(pi*80)/radianes) print("90 Grados= ",(pi*90)/radianes) print("100 Grados= ",(pi*100)/radianes) print("110 Grados= ",(pi*110)/radianes) print("120 Grados= ",(pi*120)/radianes) print("130 Grados= ",(pi*130)/radianes) print("140 Grados= ",(pi*140)/radianes) print("150 Grados= ",(pi*150)/radianes) print("160 Grados= ",(pi*160)/radianes) print("170 Grados= ",(pi*170)/radianes) print("180 Grados= ",(pi*180)/radianes) print("190 Grados= ",(pi*190)/radianes) print("200 Grados= ",(pi*200)/radianes) print("210 Grados= ",(pi*210)/radianes) print("220 Grados= ",(pi*220)/radianes) print("230 Grados= ",(pi*230)/radianes) print("240 Grados= ",(pi*240)/radianes) print("250 Grados= ",(pi*250)/radianes) print("260 Grados= ",(pi*260)/radianes) print("270 Grados= ",(pi*270)/radianes) print("280 Grados= ",(pi*280)/radianes) print("290 Grados= ",(pi*290)/radianes) print("300 Grados= ",(pi*300)/radianes) print("310 Grados= ",(pi*310)/radianes) print("320 Grados= ",(pi*320)/radianes) print("330 Grados= ",(pi*330)/radianes) print("340 Grados= ",(pi*340)/radianes) print("350 Grados= ",(pi*350)/radianes) print("360 Grados= ",(pi*360)/radianes)
db8ce900da235a9d913fa1eb4d624644
37.648148
126
0.691423
false
false
false
false
wibosco/ASOS-Consumer
refs/heads/master
ASOSConsumer/Networking/Media/MediaAPIManager.swift
mit
1
// // MediaAPIManager.swift // ASOSConsumer // // Created by William Boles on 03/03/2016. // Copyright © 2016 Boles. All rights reserved. // import UIKit import CoreData class MediaAPIManager: APIManager { //MARK: - Retrieval class func retrieveMediaAsset(media: Media, completion:((media: Media, mediaImage: UIImage?) -> Void)?) { let url = NSURL(string: media.remoteURL!)! let session = NSURLSession.sharedSession() let callBackQueue = NSOperationQueue.currentQueue()! let task = session.downloadTaskWithURL(url) { (assetLocalURL: NSURL?, response: NSURLResponse?, error: NSError?) -> Void in if (error == nil) { let imageData = NSData(contentsOfURL: assetLocalURL!) callBackQueue.addOperationWithBlock({ () -> Void in let mediaImage = UIImage(data: imageData!) if (completion != nil) { completion!(media: media, mediaImage: mediaImage) } }) } else { if ((completion) != nil) { completion!(media: media, mediaImage: nil) } } } task.resume() } }
1a90de596c8bc0ea1c383abfad0b028d
29.627907
131
0.524677
false
false
false
false
bolivarbryan/ArmyOfOnes
refs/heads/master
ArmyOfOnes/AppDelegate.swift
mit
1
// // AppDelegate.swift // ArmyOfOnes // // Created by Bryan Bolivar Martinez on 4/29/15. // Copyright (c) 2015 Bryan Bolivar Martinez. All rights reserved. // import UIKit import CoreData @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let nav = self.window!.rootViewController as! UINavigationController let master = nav.topViewController as! ViewController master.managedObjectContext = self.managedObjectContext 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 "com.development.ArmyOfOnes" in the application's documents Application Support directory. let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask) return urls[urls.count-1] as! NSURL }() lazy var managedObjectModel: NSManagedObjectModel = { // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model. let modelURL = NSBundle.mainBundle().URLForResource("ArmyOfOnes", withExtension: "momd")! return NSManagedObjectModel(contentsOfURL: modelURL)! }() lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = { // The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail. // Create the coordinator and store var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel) let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("ArmyOfOnes.sqlite") var error: NSError? = nil var failureReason = "There was an error creating or loading the application's saved data." if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil { coordinator = nil // Report any error we got. var dict = [String: AnyObject]() dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data" dict[NSLocalizedFailureReasonErrorKey] = failureReason dict[NSUnderlyingErrorKey] = error error = 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 \(error), \(error!.userInfo)") abort() } return coordinator }() lazy var managedObjectContext: NSManagedObjectContext? = { // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail. let coordinator = self.persistentStoreCoordinator if coordinator == nil { return nil } var managedObjectContext = NSManagedObjectContext() managedObjectContext.persistentStoreCoordinator = coordinator return managedObjectContext }() // MARK: - Core Data Saving support func saveContext () { if let moc = self.managedObjectContext { var error: NSError? = nil if moc.hasChanges && !moc.save(&error) { // Replace this implementation with code to handle the error appropriately. // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development. NSLog("Unresolved error \(error), \(error!.userInfo)") abort() } } } }
e48d2509ef3057dff38a9d6b829d54f8
54.245614
290
0.716577
false
false
false
false
icecoffin/GlossLite
refs/heads/master
GlossLite/Models/Realm/RealmMappedCollection.swift
mit
1
// // RealmMappedCollection.swift // GlossLite // // Created by Daniel on 28/09/16. // Copyright © 2016 icecoffin. All rights reserved. // import Foundation import RealmSwift class RealmMappedCollection<Element: Object, Transformed> { typealias Transform = (Element) -> Transformed private let realm: Realm private var results: Results<Element> private var transform: Transform private var notificationToken: NotificationToken? private var transformedCache: [Transformed] = [] var sort: SortDescriptor { didSet { transformedCache.removeAll() results = realm.objects(Element.self).sorted(byProperty: sort.property, ascending: sort.ascending) subscribeToResultsNotifications() } } var notificationBlock: ((RealmCollectionChange<Results<Element>>) -> Void)? init(realm: Realm, sort: SortDescriptor, transform: @escaping Transform) { self.realm = realm self.sort = sort self.transform = transform results = realm.objects(Element.self).sorted(byProperty: sort.property, ascending: sort.ascending) subscribeToResultsNotifications() } deinit { notificationToken?.stop() } private func subscribeToResultsNotifications() { notificationToken = results.addNotificationBlock { [unowned self] changes in switch changes { case .initial: break case .update(_, let deletions, let insertions, let modifications): self.handle(deletions: deletions) self.handle(insertions: insertions) self.handle(modifications: modifications) break case .error(let error): print(error) break } self.notificationBlock?(changes) } } private func handle(deletions: [Int]) { for index in deletions.reversed() where index < transformedCache.count { transformedCache.remove(at: index) } } private func handle(insertions: [Int]) { var count = transformedCache.count insertions.reversed().forEach { index in if index < count { transformedCache.insert(transform(results[index]), at: index) count += 1 } } } private func handle(modifications: [Int]) { let count = transformedCache.count modifications.forEach { index in if index < count { transformedCache[index] = transform(results[index]) } } } var count: Int { return results.count } func item(at index: Int) -> Transformed { assert(index <= transformedCache.count) if index < transformedCache.count { return transformedCache[index] } let transformedValue = transform(results[index]) transformedCache.append(transformedValue) return transformedValue } }
2c02b653410606f161ca3088c1922edc
25.742574
104
0.684561
false
false
false
false
TENDIGI/Obsidian-UI-iOS
refs/heads/master
src/UITableViewExtensions.swift
mit
1
// // UITableViewExtensions.swift // Alfredo // // Created by Nick Lee on 8/24/15. // Copyright (c) 2015 TENDIGI, LLC. All rights reserved. // import Foundation extension UITableView { // MARK: Nib Registration /** Registers a cell nib of the passed name, using the name as its reuse identifier - parameter name: The name of the .nib file, which will also be used as the cell's reuse identifier */ public func registerCellNib(_ name: String) { let nib = NibCache[name] ?? UINib(nibName: name, bundle: Bundle.main) NibCache[name] = nib register(nib, forCellReuseIdentifier: name) } /// Adds an empty footer view. This has the effect of hiding extra cell separators. public func addEmptyFooterView() { let frame = CGRect(origin: CGPoint.zero, size: CGSize(width: 320, height: 1)) let view = UIView(frame: frame) tableFooterView = view } // MARK: Reloading /** Reloads the passed sections, with or without animation - parameter animated: Whether or not the transition should be animated - parameter sections: The sections to reload */ public func refreshSections(_ animated: Bool = false, _ sections: [Int]) { let indexSet = NSMutableIndexSet() for index in sections { indexSet.add(index) } let animations = { () -> () in let animation: UITableViewRowAnimation = animated ? .automatic : .none self.reloadSections(indexSet as IndexSet, with: animation) } if animated { animations() } else { UIView.performWithoutAnimation(animations) } } }
5b92ca67c94a835d4dfa88ffc9e056a1
25.59375
103
0.628672
false
false
false
false
wireapp/wire-ios-sync-engine
refs/heads/develop
Source/UserSession/Search/SearchTask.swift
gpl-3.0
1
// // Wire // Copyright (C) 2017 Wire Swiss GmbH // // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see http://www.gnu.org/licenses/. // import Foundation import WireUtilities public class SearchTask { public enum Task { case search(searchRequest: SearchRequest) case lookup(userId: UUID) } public typealias ResultHandler = (_ result: SearchResult, _ isCompleted: Bool) -> Void fileprivate let transportSession: TransportSessionType fileprivate let searchContext: NSManagedObjectContext fileprivate let contextProvider: ContextProvider fileprivate let task: Task fileprivate var userLookupTaskIdentifier: ZMTaskIdentifier? fileprivate var directoryTaskIdentifier: ZMTaskIdentifier? fileprivate var teamMembershipTaskIdentifier: ZMTaskIdentifier? fileprivate var handleTaskIdentifier: ZMTaskIdentifier? fileprivate var servicesTaskIdentifier: ZMTaskIdentifier? fileprivate var resultHandlers: [ResultHandler] = [] fileprivate var result: SearchResult = SearchResult(contacts: [], teamMembers: [], addressBook: [], directory: [], conversations: [], services: []) fileprivate var tasksRemaining = 0 { didSet { // only trigger handles if decrement to 0 if oldValue > tasksRemaining { let isCompleted = tasksRemaining == 0 resultHandlers.forEach { $0(result, isCompleted) } if isCompleted { resultHandlers.removeAll() } } } } convenience init(request: SearchRequest, searchContext: NSManagedObjectContext, contextProvider: ContextProvider, transportSession: TransportSessionType) { self.init(task: .search(searchRequest: request), searchContext: searchContext, contextProvider: contextProvider, transportSession: transportSession) } convenience init(lookupUserId userId: UUID, searchContext: NSManagedObjectContext, contextProvider: ContextProvider, transportSession: TransportSessionType) { self.init(task: .lookup(userId: userId), searchContext: searchContext, contextProvider: contextProvider, transportSession: transportSession) } public init(task: Task, searchContext: NSManagedObjectContext, contextProvider: ContextProvider, transportSession: TransportSessionType) { self.task = task self.transportSession = transportSession self.searchContext = searchContext self.contextProvider = contextProvider } /// Add a result handler public func onResult(_ resultHandler : @escaping ResultHandler) { resultHandlers.append(resultHandler) } /// Cancel a previously started task public func cancel() { resultHandlers.removeAll() teamMembershipTaskIdentifier.flatMap(transportSession.cancelTask) userLookupTaskIdentifier.flatMap(transportSession.cancelTask) directoryTaskIdentifier.flatMap(transportSession.cancelTask) servicesTaskIdentifier.flatMap(transportSession.cancelTask) handleTaskIdentifier.flatMap(transportSession.cancelTask) tasksRemaining = 0 } /// Start the search task. Results will be sent to the result handlers /// added via the `onResult()` method. public func start() { performLocalSearch() performRemoteSearch() performRemoteSearchForTeamUser() performRemoteSearchForServices() performUserLookup() performLocalLookup() } } extension SearchTask { /// look up a user ID from contacts and teamMmebers locally. private func performLocalLookup() { guard case .lookup(let userId) = task else { return } tasksRemaining += 1 searchContext.performGroupedBlock { let selfUser = ZMUser.selfUser(in: self.searchContext) var options = SearchOptions() options.updateForSelfUserTeamRole(selfUser: selfUser) /// search for the local user with matching user ID and active let activeMembers = self.teamMembers(matchingQuery: "", team: selfUser.team, searchOptions: options) let teamMembers = activeMembers.filter({ $0.remoteIdentifier == userId}) let connectedUsers = self.connectedUsers(matchingQuery: "").filter({ $0.remoteIdentifier == userId}) self.contextProvider.viewContext.performGroupedBlock { let copiedTeamMembers = teamMembers.compactMap(\.user).compactMap { self.contextProvider.viewContext.object(with: $0.objectID) as? Member} let copiedConnectedUsers = connectedUsers.compactMap { self.contextProvider.viewContext.object(with: $0.objectID) as? ZMUser } let result = SearchResult(contacts: copiedConnectedUsers.map { ZMSearchUser(contextProvider: self.contextProvider, user: $0)}, teamMembers: copiedTeamMembers.compactMap(\.user).map { ZMSearchUser(contextProvider: self.contextProvider, user: $0)}, addressBook: [], directory: [], conversations: [], services: []) self.result = self.result.union(withLocalResult: result.copy(on: self.contextProvider.viewContext)) self.tasksRemaining -= 1 } } } func performLocalSearch() { guard case .search(let request) = task else { return } tasksRemaining += 1 searchContext.performGroupedBlock { var team: Team? if let teamObjectID = request.team?.objectID { team = (try? self.searchContext.existingObject(with: teamObjectID)) as? Team } let connectedUsers = request.searchOptions.contains(.contacts) ? self.connectedUsers(matchingQuery: request.normalizedQuery) : [] let teamMembers = request.searchOptions.contains(.teamMembers) ? self.teamMembers(matchingQuery: request.normalizedQuery, team: team, searchOptions: request.searchOptions) : [] let conversations = request.searchOptions.contains(.conversations) ? self.conversations(matchingQuery: request.query) : [] self.contextProvider.viewContext.performGroupedBlock { let copiedConnectedUsers = connectedUsers.compactMap({ self.contextProvider.viewContext.object(with: $0.objectID) as? ZMUser }) let searchConnectedUsers = copiedConnectedUsers.map { ZMSearchUser(contextProvider: self.contextProvider, user: $0) } let copiedteamMembers = teamMembers.compactMap({ self.contextProvider.viewContext.object(with: $0.objectID) as? Member }) let searchTeamMembers = copiedteamMembers.compactMap(\.user).map { ZMSearchUser(contextProvider: self.contextProvider, user: $0) } let result = SearchResult(contacts: searchConnectedUsers, teamMembers: searchTeamMembers, addressBook: [], directory: [], conversations: conversations, services: []) self.result = self.result.union(withLocalResult: result.copy(on: self.contextProvider.viewContext)) if request.searchOptions.contains(.addressBook) { self.result = self.result.extendWithContactsFromAddressBook(request.normalizedQuery, contextProvider: self.contextProvider) } self.tasksRemaining -= 1 } } } private func filterNonActiveTeamMembers(members: [Member]) -> [Member] { let activeConversations = ZMUser.selfUser(in: searchContext).activeConversations let activeContacts = Set(activeConversations.flatMap({ $0.localParticipants })) let selfUser = ZMUser.selfUser(in: searchContext) return members.filter({ guard let user = $0.user else { return false } return selfUser.membership?.createdBy == user || activeContacts.contains(user) }) } func teamMembers(matchingQuery query: String, team: Team?, searchOptions: SearchOptions) -> [Member] { var result = team?.members(matchingQuery: query) ?? [] if searchOptions.contains(.excludeNonActiveTeamMembers) { result = filterNonActiveTeamMembers(members: result) } if searchOptions.contains(.excludeNonActivePartners) { let query = query.strippingLeadingAtSign() let selfUser = ZMUser.selfUser(in: searchContext) let activeConversations = ZMUser.selfUser(in: searchContext).activeConversations let activeContacts = Set(activeConversations.flatMap({ $0.localParticipants })) result = result.filter({ if let user = $0.user { return user.teamRole != .partner || user.handle == query || user.membership?.createdBy == selfUser || activeContacts.contains(user) } else { return false } }) } return result } func connectedUsers(matchingQuery query: String) -> [ZMUser] { let fetchRequest = ZMUser.sortedFetchRequest(with: ZMUser.predicateForConnectedUsers(withSearch: query)) return searchContext.fetchOrAssert(request: fetchRequest) as? [ZMUser] ?? [] } func conversations(matchingQuery query: SearchRequest.Query) -> [ZMConversation] { /// TODO: use the interface with tean param? let fetchRequest = ZMConversation.sortedFetchRequest(with: ZMConversation.predicate(forSearchQuery: query.string, selfUser: ZMUser.selfUser(in: searchContext))) fetchRequest.sortDescriptors = [NSSortDescriptor(key: ZMNormalizedUserDefinedNameKey, ascending: true)] var conversations = searchContext.fetchOrAssert(request: fetchRequest) as? [ZMConversation] ?? [] if query.isHandleQuery { // if we are searching for a username only include conversations with matching displayName conversations = conversations.filter { $0.displayName.contains(query.string) } } let matchingPredicate = ZMConversation.userDefinedNamePredicate(forSearch: query.string) var matching: [ZMConversation] = [] var nonMatching: [ZMConversation] = [] // re-sort conversations without a matching userDefinedName to the end of the result list conversations.forEach { (conversation) in if matchingPredicate.evaluate(with: conversation) { matching.append(conversation) } else { nonMatching.append(conversation) } } return matching + nonMatching } } extension SearchTask { func performUserLookup() { guard case .lookup(let userId) = task, let apiVersion = BackendInfo.apiVersion else { return } tasksRemaining += 1 searchContext.performGroupedBlock { let request = type(of: self).searchRequestForUser(withUUID: userId, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: self.contextProvider.viewContext, block: { [weak self] (response) in defer { self?.tasksRemaining -= 1 } guard let contextProvider = self?.contextProvider, let payload = response.payload?.asDictionary(), let result = SearchResult(userLookupPayload: payload, contextProvider: contextProvider) else { return } if let updatedResult = self?.result.union(withDirectoryResult: result) { self?.result = updatedResult } })) request.add(ZMTaskCreatedHandler(on: self.searchContext, block: { [weak self] (taskIdentifier) in self?.userLookupTaskIdentifier = taskIdentifier })) self.transportSession.enqueueOneTime(request) } } static func searchRequestForUser(withUUID uuid: UUID, apiVersion: APIVersion) -> ZMTransportRequest { return ZMTransportRequest(getFromPath: "/users/\(uuid.transportString())", apiVersion: apiVersion.rawValue) } } extension SearchTask { func performRemoteSearch() { guard let apiVersion = BackendInfo.apiVersion, case .search(let searchRequest) = task, !searchRequest.searchOptions.isDisjoint(with: [.directory, .teamMembers, .federated]) else { return } tasksRemaining += 1 searchContext.performGroupedBlock { let request = Self.searchRequestInDirectory(withRequest: searchRequest, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: self.contextProvider.viewContext, block: { [weak self] (response) in guard let contextProvider = self?.contextProvider, let payload = response.payload?.asDictionary(), let result = SearchResult(payload: payload, query: searchRequest.query, searchOptions: searchRequest.searchOptions, contextProvider: contextProvider) else { self?.completeRemoteSearch() return } if searchRequest.searchOptions.contains(.teamMembers) { self?.performTeamMembershipLookup(on: result, searchRequest: searchRequest) } else { self?.completeRemoteSearch(searchResult: result) } })) request.add(ZMTaskCreatedHandler(on: self.searchContext, block: { [weak self] (taskIdentifier) in self?.directoryTaskIdentifier = taskIdentifier })) self.transportSession.enqueueOneTime(request) } } func performTeamMembershipLookup(on searchResult: SearchResult, searchRequest: SearchRequest) { let teamMembersIDs = searchResult.teamMembers.compactMap(\.remoteIdentifier) guard let apiVersion = BackendInfo.apiVersion, let teamID = ZMUser.selfUser(in: contextProvider.viewContext).team?.remoteIdentifier, !teamMembersIDs.isEmpty else { completeRemoteSearch(searchResult: searchResult) return } let request = type(of: self).fetchTeamMembershipRequest(teamID: teamID, teamMemberIDs: teamMembersIDs, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: contextProvider.viewContext, block: { [weak self] (response) in guard let contextProvider = self?.contextProvider, let rawData = response.rawData, let payload = MembershipListPayload(rawData) else { self?.completeRemoteSearch() return } var updatedResult = searchResult updatedResult.extendWithMembershipPayload(payload: payload) updatedResult.filterBy(searchOptions: searchRequest.searchOptions, query: searchRequest.query.string, contextProvider: contextProvider) self?.completeRemoteSearch(searchResult: updatedResult) })) request.add(ZMTaskCreatedHandler(on: self.searchContext, block: { [weak self] (taskIdentifier) in self?.teamMembershipTaskIdentifier = taskIdentifier })) self.transportSession.enqueueOneTime(request) } func completeRemoteSearch(searchResult: SearchResult? = nil) { defer { tasksRemaining -= 1 } if let searchResult = searchResult { result = result.union(withDirectoryResult: searchResult) } } static func searchRequestInDirectory(withRequest searchRequest: SearchRequest, fetchLimit: Int = 10, apiVersion: APIVersion) -> ZMTransportRequest { var queryItems = [URLQueryItem]() queryItems.append(URLQueryItem(name: "q", value: searchRequest.query.string)) if let searchDomain = searchRequest.searchDomain { queryItems.append(URLQueryItem(name: "domain", value: searchDomain)) } queryItems.append(URLQueryItem(name: "size", value: String(fetchLimit))) var url = URLComponents() url.path = "/search/contacts" url.queryItems = queryItems let path = url.string?.replacingOccurrences(of: "+", with: "%2B") ?? "" return ZMTransportRequest(getFromPath: path, apiVersion: apiVersion.rawValue) } static func fetchTeamMembershipRequest(teamID: UUID, teamMemberIDs: [UUID], apiVersion: APIVersion) -> ZMTransportRequest { let path = "/teams/\(teamID.transportString())/get-members-by-ids-using-post" let payload = ["user_ids": teamMemberIDs.map { $0.transportString() }] return ZMTransportRequest(path: path, method: .methodPOST, payload: payload as ZMTransportData, apiVersion: apiVersion.rawValue) } } extension SearchTask { func performRemoteSearchForTeamUser() { guard let apiVersion = BackendInfo.apiVersion, case .search(let searchRequest) = task, searchRequest.searchOptions.contains(.directory) else { return } tasksRemaining += 1 searchContext.performGroupedBlock { let request = type(of: self).searchRequestInDirectory(withHandle: searchRequest.query.string, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: self.contextProvider.viewContext, block: { [weak self] (response) in defer { self?.tasksRemaining -= 1 } guard let contextProvider = self?.contextProvider, let payload = response.payload?.asArray(), let userPayload = (payload.first as? ZMTransportData)?.asDictionary() else { return } guard let handle = userPayload["handle"] as? String, let name = userPayload["name"] as? String, let id = userPayload["id"] as? String else { return } let document = ["handle": handle, "name": name, "id": id] let documentPayload = ["documents": [document]] guard let result = SearchResult(payload: documentPayload, query: searchRequest.query, searchOptions: searchRequest.searchOptions, contextProvider: contextProvider) else { return } if let user = result.directory.first, !user.isSelfUser { if let prevResult = self?.result { // prepend result to prevResult only if it doesn't contain it if !prevResult.directory.contains(user) { self?.result = SearchResult( contacts: prevResult.contacts, teamMembers: prevResult.teamMembers, addressBook: prevResult.addressBook, directory: result.directory + prevResult.directory, conversations: prevResult.conversations, services: prevResult.services ) } } else { self?.result = result } } })) request.add(ZMTaskCreatedHandler(on: self.searchContext, block: { [weak self] (taskIdentifier) in self?.handleTaskIdentifier = taskIdentifier })) self.transportSession.enqueueOneTime(request) } } static func searchRequestInDirectory(withHandle handle: String, apiVersion: APIVersion) -> ZMTransportRequest { var handle = handle.lowercased() if handle.hasPrefix("@") { handle = String(handle[handle.index(after: handle.startIndex)...]) } var url = URLComponents() url.path = "/users" url.queryItems = [URLQueryItem(name: "handles", value: handle)] let urlStr = url.string?.replacingOccurrences(of: "+", with: "%2B") ?? "" return ZMTransportRequest(getFromPath: urlStr, apiVersion: apiVersion.rawValue) } } extension SearchTask { func performRemoteSearchForServices() { guard let apiVersion = BackendInfo.apiVersion, case .search(let searchRequest) = task, searchRequest.searchOptions.contains(.services) else { return } tasksRemaining += 1 searchContext.performGroupedBlock { let selfUser = ZMUser.selfUser(in: self.searchContext) guard let teamIdentifier = selfUser.team?.remoteIdentifier else { return } let request = type(of: self).servicesSearchRequest(teamIdentifier: teamIdentifier, query: searchRequest.query.string, apiVersion: apiVersion) request.add(ZMCompletionHandler(on: self.contextProvider.viewContext, block: { [weak self] (response) in defer { self?.tasksRemaining -= 1 } guard let contextProvider = self?.contextProvider, let payload = response.payload?.asDictionary(), let result = SearchResult(servicesPayload: payload, query: searchRequest.query.string, contextProvider: contextProvider) else { return } if let updatedResult = self?.result.union(withServiceResult: result) { self?.result = updatedResult } })) request.add(ZMTaskCreatedHandler(on: self.searchContext, block: { [weak self] (taskIdentifier) in self?.servicesTaskIdentifier = taskIdentifier })) self.transportSession.enqueueOneTime(request) } } static func servicesSearchRequest(teamIdentifier: UUID, query: String, apiVersion: APIVersion) -> ZMTransportRequest { var url = URLComponents() url.path = "/teams/\(teamIdentifier.transportString())/services/whitelisted" let trimmedQuery = query.trimmingCharacters(in: .whitespacesAndNewlines) if !trimmedQuery.isEmpty { url.queryItems = [URLQueryItem(name: "prefix", value: trimmedQuery)] } let urlStr = url.string?.replacingOccurrences(of: "+", with: "%2B") ?? "" return ZMTransportRequest(getFromPath: urlStr, apiVersion: apiVersion.rawValue) } }
97fbf90628d3a75b8ffbcc77d585e777
40.891003
188
0.608929
false
false
false
false
YOCKOW/SwiftCGIResponder
refs/heads/main
Sources/CGIResponder/Environment.swift
mit
1
/* ************************************************************************************************* Environment.swift © 2017-2021 YOCKOW. Licensed under MIT License. See "LICENSE.txt" for more information. ************************************************************************************************ */ import Foundation import NetworkGear import TemporaryFile import yExtensions /// Represents an abstraction for an environment where the CGI program is executed. /// /// This class is expected to be used for the purpose of some tests. public final class Environment { /// Represents environment variables. public class Variables { private var _variables: [String: String] fileprivate init(_ variables: [String: String]) { _variables = variables } /// Accesses the environment variable for `name` public subscript(_ name: String) -> String? { get { return self._variables[name] } set { self._variables[name] = newValue } } /// Returns the names of environment variables public var names: Dictionary<String, String>.Keys { return self._variables.keys } /// Remove a value for `name` @discardableResult public func removeValue(forName name: String) -> String? { guard let value = self[name] else { return nil } self[name] = nil return value } internal final class _Virtual: Variables {} private final class _Process: Variables { init() { super.init(ProcessInfo.processInfo.environment) } override subscript(name: String) -> String? { get { return super[name] } set { let result: CInt = newValue.map({ setenv(name, $0, 1) }) ?? unsetenv(name) guard result == 0 else { switch errno { case EINVAL: fatalError("`\(name)` is invalid for environment variable name.") case ENOMEM: fatalError("Unable to allocate memory for the environment.") default: fatalError("Unable to set environment variable named \(name).") } } super[name] = newValue } } } /// Represents the variable names and their values in the environment /// from which the process was launched. public static let `default`: Variables = _Process() internal static func virtual(_ initialVariables: [String: String]) -> Variables { return _Virtual(initialVariables) } } internal let standardInput: AnyFileHandle internal let standardOutput: AnyFileHandle internal let standardError: AnyFileHandle /// Current environment variables. public let variables: Variables private init<STDIN, STDOUT, STDERR>( standardInput: STDIN, standardOutput: STDOUT, standardError: STDERR, variables: Variables ) where STDIN: FileHandleProtocol, STDOUT: FileHandleProtocol, STDERR: FileHandleProtocol { self.standardInput = AnyFileHandle(standardInput) self.standardOutput = AnyFileHandle(standardOutput) self.standardError = AnyFileHandle(standardError) self.variables = variables } /// Default environment. public static let `default`: Environment = .init( standardInput: FileHandle.standardInput, standardOutput: FileHandle.standardOutput, standardError: FileHandle.standardError, variables: .default ) internal static func virtual<STDIN, STDOUT, STDERR>( standardInput: STDIN, standardOutput: STDOUT, standardError: STDERR, variables: Variables ) -> Environment where STDIN: FileHandleProtocol, STDOUT: FileHandleProtocol, STDERR: FileHandleProtocol { return .init( standardInput: standardInput, standardOutput: standardOutput, standardError: standardError, variables: variables ) } internal static func virtual<STDIN, STDOUT>( standardInput: STDIN, standardOutput: STDOUT, variables: Variables ) -> Environment where STDIN: FileHandleProtocol, STDOUT: FileHandleProtocol { return .init( standardInput: standardInput, standardOutput: standardOutput, standardError: FileHandle.standardError, variables: variables ) } internal static func virtual<STDIN>( standardInput: STDIN, variables: Variables ) -> Environment where STDIN: FileHandleProtocol { return .init( standardInput: standardInput, standardOutput: FileHandle.standardOutput, standardError: FileHandle.standardError, variables: variables ) } internal static func virtual(variables: Variables) -> Environment { return .init( standardInput: FileHandle.standardInput, standardOutput: FileHandle.standardOutput, standardError: FileHandle.standardError, variables: variables ) } } /// Represents environment variables. public typealias EnvironmentVariables = Environment.Variables /// Represents the client. /// This is a kind of wrapper of the standard input and some environment variables. public final class Client { private let _environment: Environment fileprivate init(environment: Environment) { _environment = environment } /// The client who is trying to access the server. @available(*, deprecated, message: "Use `Environment.default.client` instead.") public static let client: Client = Client(environment: .default) } extension Environment { /// The client information under this environment. public var client: Client { return Client(environment: self) } } extension Client { private var _environmentVariables: Environment.Variables { return _environment.variables } /// Returns the Boolean value that indicates whether or not connection is secure. public var connectionIsSecure: Bool { guard let https = _environmentVariables["HTTPS"] else { return false } return https.lowercased() == "on" } /// Retuns client's content-length if request method is "POST" or something. public var contentLength: Int? { return _environmentVariables["CONTENT_LENGTH"].flatMap(Int.init) } /// Retuns client's content-type if request method is "POST" or something. public var contentType: ContentType? { return _environmentVariables["CONTENT_TYPE"].flatMap(ContentType.init) } /// Returns hostname of the client. /// If there is no value for `REMOTE_HOST` in environment variables, /// reverse DNS lookup will be tried internally. public var hostname: Domain? { if let remoteHost = _environmentVariables["REMOTE_HOST"] { return Domain(remoteHost, options:.loose) } guard let ip = self.ipAddress else { return nil } return ip.domain // reverse lookup } /// Returns an instance of `IPAddress` generated from the value of `REMOTE_ADDR`. public var ipAddress: IPAddress? { return _environmentVariables["REMOTE_ADDR"].flatMap(IPAddress.init) } } extension Client { /// Represents the client's request. public final class Request { private let _client: Client private var _standardInput: AnyFileHandle { return _client._environment.standardInput } private var _environmentVariables: EnvironmentVariables { return _client._environmentVariables } fileprivate init(client: Client) { self._client = client } } /// The client's request. public var request: Request { return Request(client: self) } } extension Client.Request { /// An array of `HTTPCookieItem`s generated from the value of `HTTP_COOKIE` public func cookies(removingPercentEncoding: Bool = true) -> [HTTPCookieItem]? { guard let cookiesString = _environmentVariables["HTTP_COOKIE"] else { return nil } var result:[HTTPCookieItem] = [] let pairStrings = cookiesString.split(separator: ";").map { $0.trimmingUnicodeScalars(in: .whitespaces) } for pairString in pairStrings { guard let item = HTTPCookieItem( string: pairString, removingPercentEncoding: removingPercentEncoding ) else { return nil } result.append(item) } return result } /// Returns an instance of `FormData`. /// - parameter temporaryDirectory: Temporary directory that will contain uploaded files temporarily /// /// ## Important notes /// * Calling this method more than once will return meaningless iterator. /// * The uploaded files may be lost unless copying them to another location, /// because, the temporary directory will be removed at the end of program. public func formData( savingUploadedFilesIn temporaryDirectory: TemporaryDirectory ) throws -> FormData { guard let clientContentType = _client.contentType, clientContentType.type == .multipart && clientContentType.subtype == "form-data", let clientContentTypeParameters = clientContentType.parameters, let boundary = clientContentTypeParameters["boundary"], !boundary.isEmpty else { throw FormData.Error.invalidRequest } let clientStringEncoding: String.Encoding = ({ guard let charset = clientContentTypeParameters["charset"] else { return .utf8 } guard let encoding = String.Encoding(ianaCharacterSetName: charset) else { return .utf8 } return encoding })() return try FormData(input: _standardInput, boundary: boundary, stringEncoding: clientStringEncoding, temporaryDirectory: temporaryDirectory) } /// Returns hostname of the client's request. public var hostname: Domain? { return _environmentVariables["HTTP_HOST"].flatMap{ Domain($0, options: .loose) } } /// An array of ETags generated from the value of `HTTP_IF_MATCH` public var ifMatch: HTTPETagList? { guard let ifMatchString = _environmentVariables["HTTP_IF_MATCH"] else { return nil } return try? HTTPETagList(ifMatchString) } /// A date generated from the value of `HTTP_IF_MODIFIED_SINCE` public var ifModifiedSince: Date? { return _environmentVariables["HTTP_IF_MODIFIED_SINCE"].flatMap(DateFormatter.rfc1123.date(from:)) } /// An array of ETags generated from the value of `HTTP_IF_NONE_MATCH` public var ifNoneMatch: HTTPETagList? { guard let ifNoneMatchString = _environmentVariables["HTTP_IF_NONE_MATCH"] else { return nil } return try? HTTPETagList(ifNoneMatchString) } /// A date generated from the value of `HTTP_IF_UNMODIFIED_SINCE` public var ifUnmodifiedSince: Date? { return _environmentVariables["HTTP_IF_UNMODIFIED_SINCE"].flatMap(DateFormatter.rfc1123.date(from:)) } /// An instance of `HTTPMethod` generated from the value of `REQUEST_METHOD` public var method: HTTPMethod? { return _environmentVariables["REQUEST_METHOD"].flatMap(HTTPMethod.init) } /// The value of "REQUEST_URI". public var path: String? { return _environmentVariables["REQUEST_URI"] } /// The value of "PATH_INFO". public var pathInfo: String? { return _environmentVariables["PATH_INFO"] } /// Retuns array of `URLQueryItem` generated from "QUERY_STRING" and /// posted data (if content type is "application/x-www-form-urlencoded"). /// Inadequate items may be returned if other functions have already read the standard input. public var queryItems: [URLQueryItem]? { do { func _parse(_ string: String) throws -> [URLQueryItem] { func _replaced<S>(_ string: S) -> String where S: StringProtocol { return string.replacingOccurrences(of: "+", with: " ") } var result: [URLQueryItem] = [] let splitted = string.split { $0 == "&" || $0 == ";" } for item in splitted { let (name_raw, nilable_value_raw) = item.splitOnce(separator:"=") guard let name = _replaced(name_raw).removingPercentEncoding else { throw NSError(domain: "Invalid name: \(name_raw)", code: -1) } if let value_raw = nilable_value_raw.map({ _replaced($0) }) { guard let value = value_raw.removingPercentEncoding else { throw NSError(domain: "Invalid value: \(value_raw)", code: -1) } result.append(.init(name: name, value: value)) } else { result.append(.init(name: name, value: nil)) } } return result } let queryString = self.queryString ?? "" var result = try _parse(queryString) if let method = self.method, method == .post, let type = self._client.contentType, type.type == .application, type.subtype == "x-www-form-urlencoded", let size = self._client.contentLength, size > 0 { let inputData = try self._standardInput.read(upToCount: size) if let string = inputData.flatMap({ String(data: $0, encoding: .utf8) }) { result.append(contentsOf: try _parse(string)) } } return result } catch { // TODO: Handle errors in some way. return nil } } /// The value of "QUERY_STRING". public var queryString: String? { guard let query = _environmentVariables["QUERY_STRING"] else { return nil } if query.isEmpty { return self.uri?.last == "?" ? "" : nil } return query } /// The value of "HTTP_REFERER". public var referer: String? { return _environmentVariables["HTTP_REFERER"] } /// The alias of `var referer: String? { get }`. @inlinable public var referrer: String? { return referer } /// The value of "REQUEST_URI" public var uri: String? { return _environmentVariables["REQUEST_URI"] } /// The User Agent. public var userAgent: String? { return _environmentVariables["HTTP_USER_AGENT"] } } /// Represents server (information). public class Server { private let _environment: Environment fileprivate init(environment: Environment) { _environment = environment } @available(*, deprecated, message: "Use `Environment.default.server` instead.") public static let server = Server(environment: .default) } extension Environment { /// The server information under this environment. public var server: Server { return Server(environment: self) } } extension Server { private var _environmentVariables: Environment.Variables { return _environment.variables } /// Returns server's hostname public var hostname: Domain? { if let serverHost = _environmentVariables["SERVER_NAME"] { return Domain(serverHost, options: .loose) } guard let ip = self.ipAddress else { return nil } return ip.domain // reverse lookup } /// Returns server's IP address. public var ipAddress: IPAddress? { return _environmentVariables["SERVER_ADDR"].flatMap(IPAddress.init(string:)) } /// Server's port. public var port: CSocketPortNumber? { return _environmentVariables["SERVER_PORT"].flatMap(CSocketPortNumber.init) } /// Returns the value of environment variable for "SCRIPT_NAME". public var scriptName: String? { return _environmentVariables["SCRIPT_NAME"] } /// Returns string of server software. public var software: String? { return _environmentVariables["SERVER_SOFTWARE"] } }
d403f6766e10727ec7a8d9bc83d3c5a7
30.789583
103
0.663805
false
false
false
false
Johnykutty/SwiftLint
refs/heads/master
Source/SwiftLintFramework/Models/Command.swift
mit
2
// // Command.swift // SwiftLint // // Created by JP Simard on 8/29/15. // Copyright © 2015 Realm. All rights reserved. // import Foundation #if !os(Linux) private extension Scanner { func scanUpToString(_ string: String) -> String? { var result: NSString? = nil let success = scanUpTo(string, into: &result) if success { return result?.bridge() } return nil } func scanString(string: String) -> String? { var result: NSString? = nil let success = scanString(string, into: &result) if success { return result?.bridge() } return nil } } #endif public struct Command { public enum Action: String { case enable case disable fileprivate func inverse() -> Action { switch self { case .enable: return .disable case .disable: return .enable } } } public enum Modifier: String { case previous case this case next } internal let action: Action internal let ruleIdentifiers: [String] internal let line: Int internal let character: Int? private let modifier: Modifier? public init(action: Action, ruleIdentifiers: [String], line: Int = 0, character: Int? = nil, modifier: Modifier? = nil) { self.action = action self.ruleIdentifiers = ruleIdentifiers self.line = line self.character = character self.modifier = modifier } public init?(string: NSString, range: NSRange) { let scanner = Scanner(string: string.substring(with: range)) _ = scanner.scanString(string: "swiftlint:") guard let actionAndModifierString = scanner.scanUpToString(" ") else { return nil } let actionAndModifierScanner = Scanner(string: actionAndModifierString) guard let actionString = actionAndModifierScanner.scanUpToString(":"), let action = Action(rawValue: actionString), let lineAndCharacter = string.lineAndCharacter(forCharacterOffset: NSMaxRange(range)) else { return nil } self.action = action ruleIdentifiers = scanner.string.bridge() .substring(from: scanner.scanLocation + 1) .components(separatedBy: .whitespaces) line = lineAndCharacter.line character = lineAndCharacter.character let hasModifier = actionAndModifierScanner.scanString(string: ":") != nil // Modifier if hasModifier { let modifierString = actionAndModifierScanner.string.bridge() .substring(from: actionAndModifierScanner.scanLocation) modifier = Modifier(rawValue: modifierString) } else { modifier = nil } } internal func expand() -> [Command] { guard let modifier = modifier else { return [self] } switch modifier { case .previous: return [ Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line - 1), Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line - 1, character: Int.max) ] case .this: return [ Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line), Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line, character: Int.max) ] case .next: return [ Command(action: action, ruleIdentifiers: ruleIdentifiers, line: line + 1), Command(action: action.inverse(), ruleIdentifiers: ruleIdentifiers, line: line + 1, character: Int.max) ] } } }
949a7b3566b19bafedcf70999a8e5251
30.362903
99
0.580098
false
false
false
false
cwaffles/Soulcast
refs/heads/master
Soulcast/SoulPlayer.swift
mit
1
import UIKit import TheAmazingAudioEngine let soulPlayer = SoulPlayer() protocol SoulPlayerDelegate: AnyObject { func didStartPlaying(_ soul:Soul) func didFinishPlaying(_ soul:Soul) func didFailToPlay(_ soul:Soul) } class SoulPlayer: NSObject { fileprivate var tempSoul: Soul? fileprivate var player: AEAudioFilePlayer? static var playing = false fileprivate var subscribers:[SoulPlayerDelegate] = [] func startPlaying(_ soul:Soul!) { guard !SoulPlayer.playing else{ reset() startPlaying(soul) return } tempSoul = soul let filePath = URL(fileURLWithPath: soul.localURL! as String) do { player = try AEAudioFilePlayer(url: filePath) audioController?.addChannels([player!]) player?.removeUponFinish = true SoulPlayer.playing = true sendStartMessage(soul) player?.completionBlock = { self.reset() self.sendFinishMessage(soul) } } catch { assert(false); sendFailMessage(soul) print("oh noes! playAudioAtPath fail") return } } func lastSoul() -> Soul? { return tempSoul } func sendStartMessage(_ soul:Soul) { for eachSubscriber in subscribers { eachSubscriber.didStartPlaying(soul) } } func sendFinishMessage(_ soul:Soul) { for eachSubscriber in subscribers { eachSubscriber.didFinishPlaying(soul) } } func sendFailMessage(_ soul:Soul) { for eachSubscriber in subscribers { eachSubscriber.didFailToPlay(soul) } } func reset() { if player != nil { audioController?.removeChannels([player!]) SoulPlayer.playing = false } } func subscribe(_ subscriber:SoulPlayerDelegate) { var contains = false for eachSubscriber in subscribers { if eachSubscriber === subscriber { contains = true break } } if !contains { subscribers.append(subscriber) } } func unsubscribe(_ subscriber:SoulPlayerDelegate) { if let removalIndex = subscribers.index(where: {$0 === subscriber}) { subscribers.remove(at: removalIndex) } } }
98c8aae5745e0e0458dcacaa3ca04191
20.959184
73
0.649164
false
false
false
false
tinypass/piano-sdk-for-ios
refs/heads/master
Sources/Composer/Composer/Models/ExperienceExecuteEventParams.swift
apache-2.0
1
import Foundation @objcMembers public class ExperienceExecuteEventParams: NSObject { fileprivate(set) public var accessList: Array<XpAccessItem> fileprivate(set) public var user: User? = nil init?(dict: [String: Any]?) { if dict == nil { return nil } accessList = Array<XpAccessItem>() if let accessListArray = dict!["accessList"] as? [Any] { for item in accessListArray { if let xpAccessItemDict = item as? [String: Any] { accessList.append(XpAccessItem(dict: xpAccessItemDict)) } } } if let userDict = dict!["user"] as? [String: Any] { user = User(dict: userDict) } } }
c96519eac5c25753dfbd1dd0b7e38f5f
26.785714
75
0.53856
false
false
false
false
jaften/calendar-Swift-2.0-
refs/heads/master
CVCalendar Demo/CVCalendar/CVCalendarWeekView.swift
mit
2
// // CVCalendarWeekView.swift // CVCalendar // // Created by E. Mozharovsky on 12/26/14. // Copyright (c) 2014 GameApp. All rights reserved. // import UIKit public final class CVCalendarWeekView: UIView { // MARK: - Non public properties private var interactiveView: UIView! public override var frame: CGRect { didSet { if let calendarView = calendarView { if calendarView.calendarMode == CalendarMode.WeekView { updateInteractiveView() } } } } private var touchController: CVCalendarTouchController { return calendarView.touchController } // MARK: - Public properties public weak var monthView: CVCalendarMonthView! public var dayViews: [CVCalendarDayView]! public var index: Int! public var weekdaysIn: [Int : [Int]]? public var weekdaysOut: [Int : [Int]]? public var utilizable = false /// Recovery service. public var calendarView: CVCalendarView! { get { var calendarView: CVCalendarView! if let monthView = monthView, let activeCalendarView = monthView.calendarView { calendarView = activeCalendarView } return calendarView } } // MARK: - Initialization public init(monthView: CVCalendarMonthView, index: Int) { self.monthView = monthView self.index = index if let size = monthView.calendarView.view.weekViewSize { super.init(frame: CGRectMake(0, CGFloat(index) * size.height, size.width, size.height)) } else { super.init(frame: CGRectZero) } // Get weekdays in. let weeksIn = self.monthView!.weeksIn! self.weekdaysIn = weeksIn[self.index!] // Get weekdays out. if let weeksOut = self.monthView!.weeksOut { if self.weekdaysIn?.count < 7 { if weeksOut.count > 1 { let daysOut = 7 - self.weekdaysIn!.count var result: [Int : [Int]]? for weekdaysOut in weeksOut { if weekdaysOut.count == daysOut { let manager = calendarView.manager let key = weekdaysOut.keys.first! let value = weekdaysOut[key]![0] if value > 20 { if self.index == 0 { result = weekdaysOut break } } else if value < 10 { if self.index == manager.monthDateRange(self.monthView!.date!).countOfWeeks - 1 { result = weekdaysOut break } } } } self.weekdaysOut = result! } else { self.weekdaysOut = weeksOut[0] } } } self.createDayViews() } public override init(frame: CGRect) { super.init(frame: frame) } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } public func mapDayViews(body: (DayView) -> ()) { if let dayViews = dayViews { for dayView in dayViews { body(dayView) } } } } // MARK: - Interactive view setup & management extension CVCalendarWeekView { public func updateInteractiveView() { safeExecuteBlock({ let mode = self.monthView!.calendarView!.calendarMode! if mode == .WeekView { if let interactiveView = self.interactiveView { interactiveView.frame = self.bounds interactiveView.removeFromSuperview() self.addSubview(interactiveView) } else { self.interactiveView = UIView(frame: self.bounds) self.interactiveView.backgroundColor = .clearColor() let tapRecognizer = UITapGestureRecognizer(target: self, action: "didTouchInteractiveView:") let pressRecognizer = UILongPressGestureRecognizer(target: self, action: "didPressInteractiveView:") pressRecognizer.minimumPressDuration = 0.3 self.interactiveView.addGestureRecognizer(pressRecognizer) self.interactiveView.addGestureRecognizer(tapRecognizer) self.addSubview(self.interactiveView) } } }, collapsingOnNil: false, withObjects: monthView, monthView?.calendarView) } public func didPressInteractiveView(recognizer: UILongPressGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) let state: UIGestureRecognizerState = recognizer.state switch state { case .Began: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Started)) case .Changed: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Changed)) case .Ended: touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Range(.Ended)) default: break } } public func didTouchInteractiveView(recognizer: UITapGestureRecognizer) { let location = recognizer.locationInView(self.interactiveView) touchController.receiveTouchLocation(location, inWeekView: self, withSelectionType: .Single) } } // MARK: - Content fill & reload extension CVCalendarWeekView { public func createDayViews() { dayViews = [CVCalendarDayView]() for i in 1...7 { let dayView = CVCalendarDayView(weekView: self, weekdayIndex: i) safeExecuteBlock({ self.dayViews!.append(dayView) }, collapsingOnNil: true, withObjects: dayViews) addSubview(dayView) } } public func reloadDayViews() { if let size = calendarView.view.dayViewSize, let dayViews = dayViews { let _/*hSpace*/ = calendarView.appearance.spaceBetweenDayViews! for (index, dayView) in dayViews.enumerate() { let hSpace = calendarView.appearance.spaceBetweenDayViews! let x = CGFloat(index) * CGFloat(size.width + hSpace) + hSpace/2 dayView.frame = CGRectMake(x, 0, size.width, size.height) dayView.reloadContent() } } } } // MARK: - Safe execution extension CVCalendarWeekView { public func safeExecuteBlock(block: Void -> Void, collapsingOnNil collapsing: Bool, withObjects objects: AnyObject?...) { for object in objects { if object == nil { if collapsing { fatalError("Object { \(object) } must not be nil!") } else { return } } } block() } }
baac04e8e7c50747b5c420082b232c1a
33.363229
125
0.529496
false
false
false
false
IvanVorobei/RequestPermission
refs/heads/master
Example/SPPermission/SPPermission/Frameworks/SPPermission/Dialog/Style/SPPermissionStyleShadow.swift
mit
2
// The MIT License (MIT) // Copyright © 2017 Ivan Vorobei ([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 extension SPPermissionStyle.Shadow { static func setShadowOffsetForLabel(_ label: UILabel, blurRadius: CGFloat = 0, widthOffset: CGFloat = 0, heightOffset: CGFloat, opacity: CGFloat) { label.layer.shadowRadius = blurRadius label.layer.shadowOffset = CGSize( width: widthOffset, height: heightOffset ) label.layer.shadowOpacity = Float(opacity) } }
977c6168c3ba48c0cc6c1ce56a6c0a29
45.705882
151
0.737406
false
false
false
false
myteeNatanwit/webview4
refs/heads/master
webview4/ViewController.swift
mit
1
// // ViewController.swift // webview2 // // Created by Michael Tran on 10/11/2015. // Copyright © 2015 intcloud. All rights reserved. // import UIKit class ViewController: UIViewController, UIWebViewDelegate { @IBOutlet weak var webview: UIWebView! @IBOutlet weak var ios_label: UILabel! override func viewDidLoad() { super.viewDidLoad() webview.delegate = self; // this line is to link with the UIWebViewDelegate protocol for bridging purpose. - line 1 webview.scrollView.bounces = false; // block your webview from bouncing so it works as an app. - line 2 let localfilePath = NSBundle.mainBundle().URLForResource("index3.html", withExtension: "", subdirectory: "www"); // load file index.html in www - line 3 let request = NSURLRequest(URL: localfilePath!); // get the request to the file - line 4 //let request = NSURLRequest(URL: NSURL(string:"http://www.google.com")!); webview.loadRequest(request); // load it on the webview - line 5 } @IBAction func btn1_onclick(sender: UIButton) { ios_label.text = call_js("js_show_data", param: "this is text from IOS"); } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } // Callback when the webpage is finished loading func webViewDidFinishLoad(web: UIWebView){ // looking for the current URL let currentURL = web.request?.URL?.absoluteString; print("html content loaded! " + currentURL!); } // this is the main function to trap JS call via document.location either by click or js function call func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType nType: UIWebViewNavigationType) -> Bool { //the request.URL?.scheme is the first part of the document.location before the first ':'. It is originally http, or https, or file. in Js can be anything predefined ie aaa bbb, in this case we use 'bridge:' print("scheme is : " + request.URL!.scheme); if (request.URL?.scheme == bridge_theme) { myrecord = process_scheme((request.URL?.absoluteString)!); switch myrecord.function { case "ios_alert":alert("Bridging" , message: myrecord.param); case "ios_popup": pop_new_page(myrecord.param); case "reset": do_clear_label(); case "exchange" : do_exchange(myrecord.param); default : print("dont know function name: \(myrecord.function)") } return false; } return true; } func do_exchange(txt: String) { ios_label.text = "got this from JS: " + txt; _ = call_js("js_show_data", param: "back to JS: Hi there I got your package"); } func do_clear_label() { ios_label.text = "have been reset to this text"; } // popup a screen on top of main screen func pop_new_page(txt: String) { //create webview let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height )) // format txt to NSURL let full_path = NSURL (string: txt); // detect the protocol let scheme = full_path!.scheme; //get filename put of it let filename = full_path!.lastPathComponent; // get path out of it let pathPrefix = txt.stringByDeletingLastPathComponent; print(pathPrefix + " " + filename!); let root_dir = ""; //it is local file var myurl = NSBundle.mainBundle().URLForResource( filename, withExtension: "", subdirectory: root_dir + pathPrefix); //or a link? if (scheme == "http") || (scheme == "https") { myurl = full_path; } let requestObj = NSURLRequest(URL: myurl!); myWebView.loadRequest(requestObj); // add the webview into the uiviewcontroller let screen_name = "popup"; // load uiview from nib let viewController = popup(nibName: screen_name, bundle: nil); viewController.view.addSubview(myWebView); viewController.view.sendSubviewToBack(myWebView); // slide in or popup if navigationController != nil { self.navigationController?.pushViewController(viewController, animated: true) } else { presentViewController(viewController, animated: true, completion: nil); } } // run javascript on the page with result = call_js("js_fn", param:"rarameter"); func call_js(function_name: String, param: String) -> String{ var result = ""; var full_path = function_name + "('" + param + "')"; print("Run javascript: \(full_path)"); result = webview.stringByEvaluatingJavaScriptFromString(full_path)!; return result; } }
3af334a0ad2766b3ddc3e6eb87db4318
36.347826
208
0.604773
false
false
false
false
codesman/toolbox
refs/heads/mac
Sources/VaporToolbox/Fetch.swift
mit
1
import Console public final class Fetch: Command { public let id = "fetch" public let signature: [Argument] = [ Option(name: "clean", help: ["Cleans the project before fetching."]) ] public let help: [String] = [ "Fetches the application's dependencies." ] public let console: ConsoleProtocol public init(console: ConsoleProtocol) { self.console = console } public func run(arguments: [String]) throws { if arguments.options["clean"]?.bool == true { let clean = Clean(console: console) try clean.run(arguments: arguments) } do { let ls = try console.backgroundExecute("ls .") if !ls.contains("Packages") { console.warning("No Packages folder, fetch may take a while...") } } catch ConsoleError.subexecute(_) { // do nothing } let depBar = console.loadingBar(title: "Fetching Dependencies") depBar.start() do { _ = try console.backgroundExecute("swift package fetch") depBar.finish() } catch ConsoleError.subexecute(_, let message) { depBar.fail() if message.contains("dependency graph could not be satisfied because an update") { console.info("Try cleaning your project first.") } else if message.contains("The dependency graph could not be satisfied") { console.info("Check your dependencies' Package.swift files to see where the conflict is.") } throw ToolboxError.general(message.trim()) } } }
e95e886926b68f1d86d07a40896a884f
30.903846
106
0.58047
false
false
false
false
mmremann/Hackathon
refs/heads/master
PushIt/PushIt/Model/DDPWeek.swift
gpl-2.0
1
// // DDPWeek.swift // PushIt // // Created by Mann, Josh (US - Denver) on 9/25/15. // Copyright © 2015 Mann, Josh (US - Denver). All rights reserved. // import UIKit class DDPWeek: NSObject { var max:NSNumber? var startDate:NSDate? var endDate:NSDate? var day:[DDPDay]? //Memberwise initalizer init(dict:[String:AnyObject]) { super.init() self.updateWithDictionary(dict) } //MARK: NSCoding func updateWithDictionary(dict:[String:AnyObject]) { guard let newMax = dict["max"] as? NSNumber, let newStartDate = dict["startDate"] as? NSDate, let newEndDate = dict["endDate"] as? NSDate else { print("Error reading Challenge Dict") return } max = newMax startDate = newStartDate endDate = newEndDate // create 7 days //days } func dictionaryRepresentation() -> [String:AnyObject]? { let dict:[String:AnyObject]? = nil // create json dictionary return dict; } }
019974ed358c4c02d3b12575a956e045
21.64
67
0.548587
false
false
false
false
S7Vyto/TouchVK
refs/heads/master
TouchVK/TouchVK/Entities/News.swift
apache-2.0
1
// // News.swift // TouchVK // // Created by Sam on 08/02/2017. // Copyright © 2017 Semyon Vyatkin. All rights reserved. // import Foundation import Realm import RealmSwift enum NewsType { case none, post, photo, photoTag, wallPhoto, friend, note, audio, video } class News: Object, NewsParser { dynamic var type: String = "" dynamic var date: TimeInterval = 0 dynamic var text: String? required init() { super.init() } required init(value: Any, schema: RLMSchema) { super.init(value: value, schema: schema) } required init(realm: RLMRealm, schema: RLMObjectSchema) { super.init(realm: realm, schema: schema) } required init(_ jsonDict: ParserService.JSONDict) { self.type = jsonDict["type"] as! String self.date = jsonDict["date"] as! TimeInterval self.text = jsonDict["text"] as? String super.init() } }
adb71abea1831a79dc5ff269800a0f2e
26.393939
104
0.64823
false
false
false
false
onekiloparsec/KPCJumpBarControl
refs/heads/master
KPCJumpBarControlDemoTreeController/ViewControllerWithTree.swift
mit
1
// // ViewController.swift // KPCJumpBarControlDemo // // Created by Cédric Foellmi on 09/05/16. // Copyright © 2016 onekiloparsec. All rights reserved. // import Cocoa import KPCJumpBarControl class ViewControllerWithTree: NSViewController, JumpBarControlDelegate { @IBOutlet weak var outlineView: NSOutlineView! var outlineViewDataSource: ItemOutlineViewDataSource! var outlineViewDelegate: ItemOutlineViewDelegate! @IBOutlet weak var jumpBar: JumpBarControl! @IBOutlet weak var selectedItemTitle: NSTextField? = nil @IBOutlet weak var selectedItemIcon: NSImageView? = nil @IBOutlet weak var selectedItemIndexPath: NSTextField? = nil @IBOutlet var treeController: NSTreeController! @objc var nodes: [OutlineNode] = [] @objc var selectionIndexPaths: [IndexPath] = [] var swap: Bool = true override func viewDidLoad() { super.viewDidLoad() self.outlineViewDataSource = ItemOutlineViewDataSource() self.outlineViewDelegate = ItemOutlineViewDelegate({ (notification) in let outlineView = notification.object as! NSOutlineView let indexes = outlineView.selectedRowIndexes print("selected! \(indexes)") // let windowCtlr = outlineView.window!.windowController as! MainWindowController // self.selectedIndexPaths = [IndexPath(index: <#T##IndexPath.Element#>)] }) self.outlineView.dataSource = self.outlineViewDataSource self.outlineView.delegate = self.outlineViewDelegate self.selectedItemIcon?.image = nil self.selectedItemTitle?.stringValue = "" self.selectedItemIndexPath?.stringValue = "" self.treeController = NSTreeController() self.treeController.childrenKeyPath = "outlineChildren" // see OutlineNode self.treeController.leafKeyPath = "isLeaf" self.treeController.avoidsEmptySelection = false self.treeController.preservesSelection = true self.treeController.selectsInsertedObjects = true self.treeController.alwaysUsesMultipleValuesMarker = false self.treeController.objectClass = OutlineNode.classForCoder() self.treeController.isEditable = true self.treeController.bind(NSBindingName.content, to: self, withKeyPath: "nodes", options: nil) self.treeController.bind(NSBindingName.selectionIndexPaths, to: self, withKeyPath: "selectionIndexPaths", options: nil) self.outlineView.bind(NSBindingName.content, to: self.treeController, withKeyPath: "arrangedObjects", options: nil) self.outlineView.bind(NSBindingName.selectionIndexPaths, to: self.treeController, withKeyPath: "selectionIndexPaths", options: nil) self.jumpBar.delegate = self try! self.jumpBar.bindItemsTree(to: self.treeController) let rootNode = OutlineNode("root1") rootNode.childNodes.append(OutlineNode("first child", icon: NSImage(named: NSImage.Name(rawValue: "Star")))) let secondChildNode = OutlineNode("second child", icon: NSImage(named: NSImage.Name(rawValue: "Polygon"))) secondChildNode.childNodes.append(OutlineNode("down there", icon: NSImage(named: NSImage.Name(rawValue: "Rectangle")))) rootNode.childNodes.append(secondChildNode) rootNode.childNodes.append(OutlineNode("third child", icon: NSImage(named: NSImage.Name(rawValue: "Triangle")))) self.treeController.addObject(rootNode) let answer = self.treeController.setSelectionIndexPath(IndexPath(arrayLiteral: 0, 0)) self.outlineView.expandItem(self.outlineView.item(atRow: 0)) print("Selected ? \(answer)") } // MARK: - JumpBarControlDelegate func jumpBarControl(_ jumpBar: JumpBarControl, willOpenMenuAtIndexPath indexPath: IndexPath, withItems items: [JumpBarItemProtocol]) { print(#function) } func jumpBarControl(_ jumpBar: JumpBarControl, didOpenMenuAtIndexPath indexPath: IndexPath, withItems items: [JumpBarItemProtocol]) { print(#function) } func jumpBarControl(_ jumpBar: JumpBarControl, willSelectItems items: [JumpBarItemProtocol], atIndexPaths indexPaths: [IndexPath]) { print(#function) } func jumpBarControl(_ jumpBar: JumpBarControl, didSelectItems items: [JumpBarItemProtocol], atIndexPaths indexPaths: [IndexPath]) { print(#function) self.selectedItemIcon?.image = (items.count == 1) ? items.first!.icon : nil self.selectedItemTitle?.stringValue = (items.count == 1) ? items.first!.title : "(multiple selection)" self.selectedItemIndexPath?.stringValue = (items.count == 1) ? "IndexPath: \(indexPaths.first!.description)" : "(multiple selection)" self.treeController.setSelectionIndexPaths(indexPaths) } }
7f069ec460f78c6f836a685b865e5696
43.07563
141
0.655291
false
false
false
false
CoderZZF/DYZB
refs/heads/master
DYZB/DYZB/Classes/Main/Model/AnchorModel.swift
apache-2.0
1
// // AnchorModel.swift // DYZB // // Created by zhangzhifu on 2017/3/17. // Copyright © 2017年 seemygo. All rights reserved. // import UIKit class AnchorModel: NSObject { // 房间ID var room_id : Int = 0 // 房间图片对应的URLString var vertical_src : String = "" // 判断是手机直播还是电脑直播 // 0表示电脑直播, 1表示手机直播 var isVertical : Int = 0 // 房间名称 var room_name : String = "" // 主播昵称 var nickname : String = "" // 在线人数 var online : Int = 0 // 所在城市 var anchor_city : String = "" init(dict : [String : Any]) { super.init() setValuesForKeys(dict) } override func setValue(_ value: Any?, forUndefinedKey key: String) { } }
6570337833a2d73a92b7efa1d5316a58
18.722222
72
0.560563
false
false
false
false
fmasutti/ZendeskSupportClient
refs/heads/master
ZedeskSupportClient/ZedeskSupportClient/ZendeskAPIManager/ZendeskAPIManager.swift
mit
1
// // ZendeskAPIManager.swift // ZedeskSupportClient // // Created by Frantiesco Masutti on 08/10/17. // Copyright © 2017 Frantiesco Masutti. All rights reserved. // import Foundation import UIKit import Alamofire final class ZendeskAPIManager { static let sharedInstance = ZendeskAPIManager() public private(set) var client:ClientInfo! var defaultItensPerPage:Int = 20 private init() { self.client = ClientInfo.defaultClient() } private func defaultAuthorizationHeader() -> [String:String] { let credentialData = "\(self.client.email):\(self.client.password)".data(using: String.Encoding.utf8)! let base64Credentials = credentialData.base64EncodedString(options: []) let headers = ["Authorization": "Basic \(base64Credentials)"] return headers } private func defaultPagedParameters(paged:Int?) -> Parameters{ if let paged = paged { if paged < 100 { return ["per_page":paged] } } return ["per_page":defaultItensPerPage] } // MARK: - External methods func changeClient(newClient:ClientInfo) { self.client = newClient } // MARK: - Get List of TicketModel From ZendeskAPI. /// Request from ZendeskAPI list of tickets for current Client defined for this Singleton. /// - parameter perPageTickets: The number of itens per page. `self.defaultItensPerPage`. /// - parameter specificPageURL: The url if want to request date of a specific page. /// - parameter successBlock: Escaping block that will return a list with tickets from client. /// - parameter errorBlock: Escaping block that will return if something went wrong during the request. func getTickets(perPageTickets:Int?, specificPageURL:String?, successBlock: @escaping (Tickets) -> (), errorBlock: @escaping (Error?) -> ()) { let urlString:String if let specificPageURL = specificPageURL { urlString = specificPageURL }else { urlString = "https://\(self.client.subdomain).zendesk.com/api/v2/views/\(self.client.clientId)/tickets.json" } let parameters = self.defaultPagedParameters(paged: perPageTickets) Alamofire.request(urlString, method: .get, parameters: parameters, encoding: URLEncoding.default, headers:self.defaultAuthorizationHeader()).validate().responseJSON { response in switch response.result { case .success: if let jsonReturn = response.result.value as? [String:Any] { let tickets = Tickets(jsonObject: jsonReturn) successBlock(tickets) } else { errorBlock(response.error) } case .failure(let error): errorBlock(error) } } } }
c9674d5a9c8127af33eb2b58431b2244
38.144737
186
0.619496
false
false
false
false
kellyi/LeapDemoSwift
refs/heads/master
LeapDemoSwift/GameScene.swift
mit
1
// // GameScene.swift // LeapDemoSwift // // Created by Kelly Innes on 10/27/15. // Copyright (c) 2015 Kelly Innes. All rights reserved. // import SpriteKit class GameScene: SKScene { let rightHand = SKSpriteNode(imageNamed: "righthand") let leftHand = SKSpriteNode(imageNamed: "lefthand") let ball = SKSpriteNode(imageNamed: "ball") override func didMove(to view: SKView) { self.backgroundColor = SKColor.gray //rightHand.position = CGPoint(x: (self.size.width/2) + 500, y: self.size.height/2) rightHand.xScale = 0.1 rightHand.yScale = 0.1 rightHand.physicsBody = SKPhysicsBody(rectangleOf: CGSize(width: rightHand.size.width, height: rightHand.size.height)) rightHand.physicsBody?.collisionBitMask = 0 rightHand.physicsBody?.categoryBitMask = 1 rightHand.physicsBody?.contactTestBitMask = 1 leftHand.xScale = 0.1 leftHand.yScale = 0.1 //leftHand.position = CGPoint(x: (self.size.width/2) - 500, y: self.size.height/2) leftHand.physicsBody?.collisionBitMask = 0 leftHand.physicsBody?.categoryBitMask = 1 leftHand.physicsBody?.contactTestBitMask = 1 ball.xScale = 0.1 ball.yScale = 0.1 ball.position = CGPoint(x: self.size.width/2, y: self.size.height/2) ball.physicsBody = SKPhysicsBody(circleOfRadius: ball.size.width/2) ball.physicsBody?.categoryBitMask = 0 ball.physicsBody?.collisionBitMask = 1 ball.physicsBody?.contactTestBitMask = 1 ball.physicsBody?.affectedByGravity = false addChild(rightHand) addChild(leftHand) addChild(ball) } override func update(_ currentTime: TimeInterval) { updateHandPositions() } func updateHandPositions() { let newRightHandPosition = LeapMotionManager.sharedInstance.rightHandPosition as LeapVector var newRightHandX = newRightHandPosition.x var newRightHandY = newRightHandPosition.y if newRightHandX > 225.0 { newRightHandX = 225.0 } else if newRightHandX < -225.0 { newRightHandX = -225.0 } if newRightHandY < 100.0 { newRightHandY = 100.0 } else if newRightHandY > 500.0 { newRightHandY = 500.0 } rightHand.position = CGPoint(x: self.size.width/2 + CGFloat(newRightHandX), y: self.size.height/2 + CGFloat(newRightHandY/2)) let newLeftHandPosition = LeapMotionManager.sharedInstance.leftHandPosition as LeapVector var newLeftHandX = newLeftHandPosition.x var newLeftHandY = newLeftHandPosition.y if newLeftHandX > 225.0 { newLeftHandX = 225.0 } else if newLeftHandX < -225.0 { newLeftHandX = -225.0 } if newLeftHandY < 100.0 { newLeftHandY = 100.0 } else if newLeftHandY > 500.0 { newLeftHandY = 500.0 } leftHand.position = CGPoint(x: self.size.width/2 + CGFloat(newLeftHandX), y: self.size.height/2 + CGFloat(newLeftHandY/2)) } }
a8f879cf96200445bc71227ed98b91c0
36.819277
133
0.635234
false
false
false
false
nalck/Barliman
refs/heads/master
cocoa/Barliman/SemanticsWindowController.swift
mit
1
// // SemanticsWindowController.swift // Barliman // // Created by William Byrd on 5/29/16. // Copyright © 2016 William E. Byrd. // Released under MIT License (see LICENSE file) import Cocoa class SemanticsWindowController: NSWindowController { // Making evaluationRulesView a weak reference seems to cause a runtime error. Why? @IBOutlet var evaluationRulesView: NSTextView! var editorWindowController: EditorWindowController? override var windowNibName: String? { return "SemanticsWindowController" } func textDidChange(_ notification: Notification) { // NSTextView text changed print("@@@@@@@@@@@@@@@@@@@ semantics textDidChange") editorWindowController!.setupRunCodeFromEditPaneTimer() } override func windowDidLoad() { super.windowDidLoad() // Implement this method to handle any initialization after your window controller's window has been loaded from its nib file. // from http://stackoverflow.com/questions/19801601/nstextview-with-smart-quotes-disabled-still-replaces-quotes evaluationRulesView.isAutomaticQuoteSubstitutionEnabled = false loadInterpreterCode("interp") } func loadInterpreterCode(_ interpFileName: String) { // get the path to the application's bundle, so we can load the interpreter file let bundle = Bundle.main let interp_path: NSString? = bundle.path(forResource: interpFileName, ofType: "scm", inDirectory: "mk-and-rel-interp") as NSString? let path = URL(fileURLWithPath: interp_path as! String) // from http://stackoverflow.com/questions/24097826/read-and-write-data-from-text-file do { let text = try NSString(contentsOf: path, encoding: String.Encoding.utf8.rawValue) evaluationRulesView.textStorage?.setAttributedString(NSAttributedString(string: text as String)) } catch { print("Oh noes! Can't load interpreter for Semantics Window!") } } @IBAction func loadFullMiniSchemeWithMatch(_ sender: NSMenuItem) { loadInterpreterCode("interp") print("@@@@ loaded FullMiniSchemeWithMatch interpreter from popup menu") editorWindowController!.setupRunCodeFromEditPaneTimer() } @IBAction func loadCallByValueLambdaCalculus(_ sender: NSMenuItem) { loadInterpreterCode("cbv-lc") print("@@@@ loaded CallByValueLambdaCalculus interpreter from popup menu") editorWindowController!.setupRunCodeFromEditPaneTimer() } @IBAction func loadDynamicallyScopedMiniSchemeWithMatch(_ sender: NSMenuItem) { loadInterpreterCode("interp-dynamic") print("@@@@ loaded DynamicallyScopedMiniSchemeWithMatch interpreter from popup menu") editorWindowController!.setupRunCodeFromEditPaneTimer() } func getInterpreterCode() -> String { return (evaluationRulesView.textStorage?.string)! } func cleanup() { // application is about to quit -- clean up! } }
fddc78aff2e6293d1720fdaab2b086e5
35.290698
139
0.67959
false
false
false
false
mollifier/kancolle-ac-calculator
refs/heads/master
kancolle-ac-calculator/StageCreater.swift
mit
1
// // StageCreater.swift // kancolle-ac-calculator // // Created by mollifier on 2016/06/07. // // import Foundation class StageCreater { private static let _stages: [Stage] = [ Stage(areaNumber: 1, stageNumber: 1, stageType: .Normal, cost: 150), Stage(areaNumber: 1, stageNumber: 1, stageType: .Pursuit, cost: 100), Stage(areaNumber: 1, stageNumber: 2, stageType: .Normal, cost: 200), Stage(areaNumber: 1, stageNumber: 2, stageType: .Pursuit, cost: 100), Stage(areaNumber: 1, stageNumber: 3, stageType: .Normal, cost: 240), Stage(areaNumber: 1, stageNumber: 3, stageType: .Pursuit, cost: 150), Stage(areaNumber: 1, stageNumber: 4, stageType: .Normal, cost: 280), Stage(areaNumber: 1, stageNumber: 4, stageType: .Pursuit, cost: 150), Stage(areaNumber: 2, stageNumber: 1, stageType: .Normal, cost: 240), Stage(areaNumber: 2, stageNumber: 1, stageType: .Pursuit, cost: 150), Stage(areaNumber: 2, stageNumber: 2, stageType: .Normal, cost: 260), Stage(areaNumber: 2, stageNumber: 2, stageType: .Pursuit, cost: 150), Stage(areaNumber: 2, stageNumber: 3, stageType: .Normal, cost: 280), Stage(areaNumber: 2, stageNumber: 3, stageType: .Pursuit, cost: 200), Stage(areaNumber: 2, stageNumber: 4, stageType: .Normal, cost: 300), Stage(areaNumber: 2, stageNumber: 4, stageType: .Pursuit, cost: 200), Stage(areaNumber: 3, stageNumber: 1, stageType: .Normal, cost: 360), Stage(areaNumber: 3, stageNumber: 1, stageType: .Pursuit, cost: 150), Stage(areaNumber: 3, stageNumber: 2, stageType: .Normal, cost: 390), Stage(areaNumber: 3, stageNumber: 2, stageType: .Pursuit, cost: 150), Stage(areaNumber: 3, stageNumber: 3, stageType: .Normal, cost: 420), Stage(areaNumber: 3, stageNumber: 3, stageType: .Pursuit, cost: 200), Stage(areaNumber: 3, stageNumber: 4, stageType: .Normal, cost: 450), Stage(areaNumber: 3, stageNumber: 4, stageType: .Pursuit, cost: 200), ] static func areaCount() -> Int { return 3 } static func stages() -> [Stage] { return self._stages } static func stages(areaNumber: Int) -> [Stage] { return self.stages().filter { (s) in s.areaNumber == areaNumber } } static func stages(stageType: Stage.StageType) -> [Stage] { return self.stages().filter { (s) in s.stageType == stageType } } static func stages(areaNumber: Int, stageType: Stage.StageType) -> [Stage] { return self.stages().filter { (s) in s.areaNumber == areaNumber && s.stageType == stageType } } }
08ae6d0d9bf52e3b7d312c763a0fbf29
43.633333
101
0.632188
false
false
false
false
hejunbinlan/SwiftGraphics
refs/heads/develop
SwiftGraphicsPlayground/Bitmap.swift
bsd-2-clause
4
// // Bitmap.swift // SwiftGraphics // // Created by Jonathan Wight on 1/17/15. // Copyright (c) 2015 schwa.io. All rights reserved. // import SwiftGraphics public struct Bitmap { public let size: UIntSize public let bitsPerComponent: UInt public let bitsPerPixel: UInt public let bytesPerRow: UInt public let ptr: UnsafeMutablePointer<Void> public var bytesPerPixel: UInt { return bitsPerPixel / 8 } public init(size:UIntSize, bitsPerComponent:UInt, bitsPerPixel:UInt, bytesPerRow:UInt, ptr:UnsafeMutablePointer <Void>) { self.size = size self.bitsPerComponent = bitsPerComponent self.bitsPerPixel = bitsPerPixel self.bytesPerRow = bytesPerRow self.ptr = ptr } public subscript (index:UIntPoint) -> UInt32 { assert(index.x < size.width) assert(index.y < size.height) let offset = index.y * bytesPerRow + index.x * bytesPerPixel let offsetPointer = ptr.advancedBy(Int(offset)) return UnsafeMutablePointer <UInt32> (offsetPointer).memory } }
fb48d0317b5250e6f4bb797c3744bf71
29.027778
125
0.677151
false
false
false
false
EclipseSoundscapes/EclipseSoundscapes
refs/heads/master
EclipseSoundscapes/Views/ParallaxView.swift
gpl-3.0
1
// // ParallaxView.swift // EclipseSoundscapes // // Created by Arlindo Goncalves on 8/28/17. // // Copyright © 2017 Arlindo Goncalves. // 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/]. // // For Contact email: [email protected] import UIKit final class ParallaxView: UIView { override var backgroundColor: UIColor? { didSet { panningView.backgroundColor = backgroundColor } } fileprivate var heightLayoutConstraint = NSLayoutConstraint() fileprivate var bottomLayoutConstraint = NSLayoutConstraint() fileprivate var containerLayoutConstraint = NSLayoutConstraint() fileprivate var containerView = UIView() fileprivate var panningView = UIView() required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(frame: CGRect) { super.init(frame: frame) containerView.translatesAutoresizingMaskIntoConstraints = false self.addSubview(containerView) containerLayoutConstraint = containerView.anchor(nil, left: leftAnchor, bottom: bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: CGFloat.leastNonzeroMagnitude).last! panningView = UIView() panningView.translatesAutoresizingMaskIntoConstraints = false containerView.addSubview(panningView) let contraints = panningView.anchor(nil, left: containerView.leftAnchor, bottom: containerView.bottomAnchor, right: rightAnchor, topConstant: 0, leftConstant: 0, bottomConstant: 0, rightConstant: 0, widthConstant: 0, heightConstant: CGFloat.leastNonzeroMagnitude) bottomLayoutConstraint = contraints[1] heightLayoutConstraint = contraints.last! } func scrollViewDidScroll(scrollView: UIScrollView) { containerLayoutConstraint.constant = scrollView.contentInset.top let offsetY = -(scrollView.contentOffset.y + scrollView.contentInset.top) bottomLayoutConstraint.constant = offsetY >= 0 ? 0 : -offsetY / 2 heightLayoutConstraint.constant = max(offsetY + scrollView.contentInset.top, scrollView.contentInset.top) } }
bd9e84170940095bb1f482bc53c400e0
40.623188
271
0.716226
false
false
false
false
hooman/swift
refs/heads/main
stdlib/public/Platform/Platform.swift
apache-2.0
4
//===----------------------------------------------------------------------===// // // 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 // //===----------------------------------------------------------------------===// import SwiftShims import SwiftOverlayShims #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) //===----------------------------------------------------------------------===// // MacTypes.h //===----------------------------------------------------------------------===// public var noErr: OSStatus { return 0 } /// The `Boolean` type declared in MacTypes.h and used throughout Core /// Foundation. /// /// The C type is a typedef for `unsigned char`. @frozen public struct DarwinBoolean : ExpressibleByBooleanLiteral { @usableFromInline var _value: UInt8 @_transparent public init(_ value: Bool) { self._value = value ? 1 : 0 } /// The value of `self`, expressed as a `Bool`. @_transparent public var boolValue: Bool { return _value != 0 } /// Create an instance initialized to `value`. @_transparent public init(booleanLiteral value: Bool) { self.init(value) } } extension DarwinBoolean : CustomReflectable { /// Returns a mirror that reflects `self`. public var customMirror: Mirror { return Mirror(reflecting: boolValue) } } extension DarwinBoolean : CustomStringConvertible { /// A textual representation of `self`. public var description: String { return self.boolValue.description } } extension DarwinBoolean : Equatable { @_transparent public static func ==(lhs: DarwinBoolean, rhs: DarwinBoolean) -> Bool { return lhs.boolValue == rhs.boolValue } } @_transparent public // COMPILER_INTRINSIC func _convertBoolToDarwinBoolean(_ x: Bool) -> DarwinBoolean { return DarwinBoolean(x) } @_transparent public // COMPILER_INTRINSIC func _convertDarwinBooleanToBool(_ x: DarwinBoolean) -> Bool { return x.boolValue } #endif //===----------------------------------------------------------------------===// // sys/errno.h //===----------------------------------------------------------------------===// public var errno : Int32 { get { return _swift_stdlib_getErrno() } set(val) { return _swift_stdlib_setErrno(val) } } //===----------------------------------------------------------------------===// // stdio.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(PS4) public var stdin : UnsafeMutablePointer<FILE> { get { return __stdinp } set { __stdinp = newValue } } public var stdout : UnsafeMutablePointer<FILE> { get { return __stdoutp } set { __stdoutp = newValue } } public var stderr : UnsafeMutablePointer<FILE> { get { return __stderrp } set { __stderrp = newValue } } public func dprintf(_ fd: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in vdprintf(Int32(fd), format, va_args) } } public func snprintf(ptr: UnsafeMutablePointer<Int8>, _ len: Int, _ format: UnsafePointer<Int8>, _ args: CVarArg...) -> Int32 { return withVaList(args) { va_args in return vsnprintf(ptr, len, format, va_args) } } #elseif os(OpenBSD) public var stdin: UnsafeMutablePointer<FILE> { return _swift_stdlib_stdin() } public var stdout: UnsafeMutablePointer<FILE> { return _swift_stdlib_stdout() } public var stderr: UnsafeMutablePointer<FILE> { return _swift_stdlib_stderr() } #elseif os(Windows) public var stdin: UnsafeMutablePointer<FILE> { return __acrt_iob_func(0) } public var stdout: UnsafeMutablePointer<FILE> { return __acrt_iob_func(1) } public var stderr: UnsafeMutablePointer<FILE> { return __acrt_iob_func(2) } public var STDIN_FILENO: Int32 { return _fileno(stdin) } public var STDOUT_FILENO: Int32 { return _fileno(stdout) } public var STDERR_FILENO: Int32 { return _fileno(stderr) } #endif //===----------------------------------------------------------------------===// // fcntl.h //===----------------------------------------------------------------------===// public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_stdlib_open(path, oflag, 0) } #if os(Windows) public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: Int32 ) -> Int32 { return _swift_stdlib_open(path, oflag, mode) } #else public func open( _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_stdlib_open(path, oflag, mode) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32 ) -> Int32 { return _swift_stdlib_openat(fd, path, oflag, 0) } public func openat( _ fd: Int32, _ path: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t ) -> Int32 { return _swift_stdlib_openat(fd, path, oflag, mode) } public func fcntl( _ fd: Int32, _ cmd: Int32 ) -> Int32 { return _swift_stdlib_fcntl(fd, cmd, 0) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ value: Int32 ) -> Int32 { return _swift_stdlib_fcntl(fd, cmd, value) } public func fcntl( _ fd: Int32, _ cmd: Int32, _ ptr: UnsafeMutableRawPointer ) -> Int32 { return _swift_stdlib_fcntlPtr(fd, cmd, ptr) } // !os(Windows) #endif #if os(Windows) public var S_IFMT: Int32 { return Int32(0xf000) } public var S_IFREG: Int32 { return Int32(0x8000) } public var S_IFDIR: Int32 { return Int32(0x4000) } public var S_IFCHR: Int32 { return Int32(0x2000) } public var S_IFIFO: Int32 { return Int32(0x1000) } public var S_IREAD: Int32 { return Int32(0x0100) } public var S_IWRITE: Int32 { return Int32(0x0080) } public var S_IEXEC: Int32 { return Int32(0x0040) } #else public var S_IFMT: mode_t { return mode_t(0o170000) } public var S_IFIFO: mode_t { return mode_t(0o010000) } public var S_IFCHR: mode_t { return mode_t(0o020000) } public var S_IFDIR: mode_t { return mode_t(0o040000) } public var S_IFBLK: mode_t { return mode_t(0o060000) } public var S_IFREG: mode_t { return mode_t(0o100000) } public var S_IFLNK: mode_t { return mode_t(0o120000) } public var S_IFSOCK: mode_t { return mode_t(0o140000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_IFWHT: mode_t { return mode_t(0o160000) } #endif public var S_IRWXU: mode_t { return mode_t(0o000700) } public var S_IRUSR: mode_t { return mode_t(0o000400) } public var S_IWUSR: mode_t { return mode_t(0o000200) } public var S_IXUSR: mode_t { return mode_t(0o000100) } public var S_IRWXG: mode_t { return mode_t(0o000070) } public var S_IRGRP: mode_t { return mode_t(0o000040) } public var S_IWGRP: mode_t { return mode_t(0o000020) } public var S_IXGRP: mode_t { return mode_t(0o000010) } public var S_IRWXO: mode_t { return mode_t(0o000007) } public var S_IROTH: mode_t { return mode_t(0o000004) } public var S_IWOTH: mode_t { return mode_t(0o000002) } public var S_IXOTH: mode_t { return mode_t(0o000001) } public var S_ISUID: mode_t { return mode_t(0o004000) } public var S_ISGID: mode_t { return mode_t(0o002000) } public var S_ISVTX: mode_t { return mode_t(0o001000) } #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var S_ISTXT: mode_t { return S_ISVTX } public var S_IREAD: mode_t { return S_IRUSR } public var S_IWRITE: mode_t { return S_IWUSR } public var S_IEXEC: mode_t { return S_IXUSR } #endif #endif //===----------------------------------------------------------------------===// // ioctl.h //===----------------------------------------------------------------------===// #if !os(Windows) public func ioctl( _ fd: CInt, _ request: UInt, _ value: CInt ) -> CInt { return _swift_stdlib_ioctl(fd, request, value) } public func ioctl( _ fd: CInt, _ request: UInt, _ ptr: UnsafeMutableRawPointer ) -> CInt { return _swift_stdlib_ioctlPtr(fd, request, ptr) } public func ioctl( _ fd: CInt, _ request: UInt ) -> CInt { return _swift_stdlib_ioctl(fd, request, 0) } // !os(Windows) #endif //===----------------------------------------------------------------------===// // unistd.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func fork() -> Int32 { fatalError("unavailable function can't be called") } @available(*, unavailable, message: "Please use threads or posix_spawn*()") public func vfork() -> Int32 { fatalError("unavailable function can't be called") } #endif //===----------------------------------------------------------------------===// // signal.h //===----------------------------------------------------------------------===// #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(5, to: sig_t.self) } #elseif os(OpenBSD) public var SIG_DFL: sig_t? { return nil } public var SIG_IGN: sig_t { return unsafeBitCast(1, to: sig_t.self) } public var SIG_ERR: sig_t { return unsafeBitCast(-1, to: sig_t.self) } public var SIG_HOLD: sig_t { return unsafeBitCast(3, to: sig_t.self) } #elseif os(Linux) || os(FreeBSD) || os(PS4) || os(Android) || os(Haiku) public typealias sighandler_t = __sighandler_t public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Cygwin) public typealias sighandler_t = _sig_func_ptr public var SIG_DFL: sighandler_t? { return nil } public var SIG_IGN: sighandler_t { return unsafeBitCast(1, to: sighandler_t.self) } public var SIG_ERR: sighandler_t { return unsafeBitCast(-1, to: sighandler_t.self) } public var SIG_HOLD: sighandler_t { return unsafeBitCast(2, to: sighandler_t.self) } #elseif os(Windows) public var SIG_DFL: _crt_signal_t? { return nil } public var SIG_IGN: _crt_signal_t { return unsafeBitCast(1, to: _crt_signal_t.self) } public var SIG_ERR: _crt_signal_t { return unsafeBitCast(-1, to: _crt_signal_t.self) } #elseif os(WASI) // No signals support on WASI yet, see https://github.com/WebAssembly/WASI/issues/166. #else internal var _ignore = _UnsupportedPlatformError() #endif //===----------------------------------------------------------------------===// // semaphore.h //===----------------------------------------------------------------------===// #if !os(Windows) #if os(OpenBSD) public typealias Semaphore = UnsafeMutablePointer<sem_t?> #else public typealias Semaphore = UnsafeMutablePointer<sem_t> #endif /// The value returned by `sem_open()` in the case of failure. public var SEM_FAILED: Semaphore? { #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) // The value is ABI. Value verified to be correct for OS X, iOS, watchOS, tvOS. return Semaphore(bitPattern: -1) #elseif os(Linux) || os(FreeBSD) || os(OpenBSD) || os(PS4) || os(Android) || os(Cygwin) || os(Haiku) || os(WASI) // The value is ABI. Value verified to be correct on Glibc. return Semaphore(bitPattern: 0) #else _UnsupportedPlatformError() #endif } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32 ) -> Semaphore? { return _stdlib_sem_open2(name, oflag) } public func sem_open( _ name: UnsafePointer<CChar>, _ oflag: Int32, _ mode: mode_t, _ value: CUnsignedInt ) -> Semaphore? { return _stdlib_sem_open4(name, oflag, mode, value) } #endif //===----------------------------------------------------------------------===// // Misc. //===----------------------------------------------------------------------===// // Some platforms don't have `extern char** environ` imported from C. #if os(macOS) || os(iOS) || os(watchOS) || os(tvOS) || os(FreeBSD) || os(OpenBSD) || os(PS4) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return _swift_stdlib_getEnviron() } #elseif os(Linux) public var environ: UnsafeMutablePointer<UnsafeMutablePointer<CChar>?> { return __environ } #endif
6cc81602a0d6a3031e3aa232b792477c
27.866972
127
0.596377
false
false
false
false
melsomino/unified-ios
refs/heads/master
Unified/Library/Ui/Layout/LayoutLayered.swift
mit
1
// // Created by Власов М.Ю. on 07.06.16. // Copyright (c) 2016 Tensor. All rights reserved. // import Foundation import UIKit public class LayoutLayered: LayoutItem { let content: [LayoutItem] init(_ content: [LayoutItem]) { self.content = content } public override var visible: Bool { return content.contains({ $0.visible }) } public override var fixedSize: Bool { return content.contains({ $0.fixedSize }) } public override func createViews(inSuperview superview: UIView) { for item in content { item.createViews(inSuperview: superview) } } public override func collectFrameItems(inout items: [LayoutFrameItem]) { for item in content { item.collectFrameItems(&items) } } public override func measureMaxSize(bounds: CGSize) -> CGSize { var maxSize = CGSizeZero for item in content { let itemSize = item.measureMaxSize(bounds) maxSize.width = max(maxSize.width, itemSize.width) maxSize.height = max(maxSize.height, itemSize.height) } return maxSize } public override func measureSize(bounds: CGSize) -> CGSize { var size = CGSizeZero for item in content { let itemSize = item.measureSize(bounds) size.width = max(size.width, itemSize.width) size.height = max(size.height, itemSize.height) } return size } public override func layout(bounds: CGRect) -> CGRect { for item in content { item.layout(bounds) } return bounds } }
814752985fe8dc155535d1714b3dce1d
20.179104
73
0.707541
false
false
false
false
macmade/AtomicKit
refs/heads/main
AtomicKit/Source/DispatchedBool.swift
mit
1
/******************************************************************************* * The MIT License (MIT) * * Copyright (c) 2017 Jean-David Gadina - www.xs-labs.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. ******************************************************************************/ import Foundation /** * Thread-safe value wrapper for `Bool`, using dispatch queues to achieve * synchronization. * This class is KVO-compliant. You may observe its `value` property to be * notified of changes. This is applicable to Cocoa bindings. * * - seealso: DispatchedValueWrapper */ @objc public class DispatchedBool: NSObject, DispatchedValueWrapper { /** * The wrapped value type, `Bool`. */ public typealias ValueType = Bool /** * Initializes a dispatched value object. * This initializer will use the main queue for synchronization. * * - parameter value: The initial `Bool` value. */ public required convenience init( value: ValueType ) { self.init( value: value, queue: DispatchQueue.main ) } /** * Initializes a dispatched value object. * * - parameter value: The initial `Bool` value. * - parameter queue: The queue to use to achieve synchronization. */ public required init( value: ValueType = false, queue: DispatchQueue = DispatchQueue.main ) { self._value = DispatchedValue< ValueType >( value: value, queue: queue ) } /** * The wrapped `Bool` value. * This property is KVO-compliant. */ @objc public dynamic var value: ValueType { get { return self._value.get() } set( value ) { self.willChangeValue( forKey: "value" ) self._value.set( value ) self.didChangeValue( forKey: "value" ) } } /** * Atomically gets the wrapped `Bool` value. * The getter will be executed on the queue specified in the initialzer. * * - returns: The actual `Bool` value. */ public func get() -> ValueType { return self.value } /** * Atomically sets the wrapped `Bool` value. * The setter will be executed on the queue specified in the initialzer. * * -parameter value: The `Bool` value to set. */ public func set( _ value: ValueType ) { self.value = value } /** * Atomically executes a closure on the wrapped `Bool` value. * The closure will be passed the actual value of the wrapped `Bool` value, * and is guaranteed to be executed atomically, on the queue specified in * the initialzer. * * -parameter closure: The close to execute. */ public func execute( closure: ( ValueType ) -> Swift.Void ) { self._value.execute( closure: closure ) } /** * Atomically executes a closure on the wrapped `Bool` value, returning some * value. * The closure will be passed the actual value of the wrapped `Bool` value, * and is guaranteed to be executed atomically, on the queue specified in * the initialzer. * * -parameter closure: The close to execute, returning some value. */ public func execute< R >( closure: ( ValueType ) -> R ) -> R { return self._value.execute( closure: closure ) } private var _value: DispatchedValue< ValueType > }
53f93152b4b72ad809550eac286520c0
32.917293
95
0.618488
false
false
false
false
ljshj/actor-platform
refs/heads/master
actor-sdk/sdk-core-ios/ActorSDK/Sources/Controllers/Content/Conversation/Cell/AABubbleContactCell.swift
mit
1
// // Copyright (c) 2014-2016 Actor LLC. <https://actor.im> // import Foundation import AddressBookUI import MessageUI public class AABubbleContactCell: AABubbleCell, ABNewPersonViewControllerDelegate, MFMailComposeViewControllerDelegate, UINavigationControllerDelegate { private let avatar = AAAvatarView() private let name = UILabel() private let contact = UILabel() private var bindedRecords = [String]() private let tapView = UIView() public init(frame: CGRect) { super.init(frame: frame, isFullSize: false) name.font = UIFont.mediumSystemFontOfSize(17) contact.font = UIFont.systemFontOfSize(15) tapView.backgroundColor = UIColor.clearColor() contentView.addSubview(avatar) contentView.addSubview(name) contentView.addSubview(contact) contentView.addSubview(tapView) contentInsets = UIEdgeInsets(top: 1, left: 1, bottom: 1, right: 1) tapView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(AABubbleContactCell.contactDidTap))) tapView.userInteractionEnabled = true } public required init(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } func contactDidTap() { if let m = bindedMessage { if let c = m.content as? ACContactContent { let menuBuilder = AAMenuBuilder() let phones = c.getPhones() for i in 0..<phones.size() { let p = phones.getWithInt(i) as! String menuBuilder.add(p, closure: { () -> () in if let url = NSURL(string: "tel:\(p)") { if !UIApplication.sharedApplication().openURL(url) { self.controller.alertUser("ErrorUnableToCall") } } else { self.controller.alertUser("ErrorUnableToCall") } }) } let emails = c.getEmails() for i in 0..<emails.size() { let e = emails.getWithInt(i) as! String menuBuilder.add(e, closure: { () -> () in let emailController = MFMailComposeViewController() emailController.delegate = self emailController.setToRecipients([e]) self.controller.presentViewController(emailController, animated: true, completion: nil) }) } menuBuilder.add(AALocalized("ProfileAddToContacts"), closure: { () -> () in let add = ABNewPersonViewController() add.newPersonViewDelegate = self let person: ABRecordRef = ABPersonCreate().takeRetainedValue() let name = c.getName().trim() let nameParts = name.componentsSeparatedByString(" ") ABRecordSetValue(person, kABPersonFirstNameProperty, nameParts[0], nil) if (nameParts.count >= 2) { let lastName = name.substringFromIndex(nameParts[0].endIndex).trim() ABRecordSetValue(person, kABPersonLastNameProperty, lastName, nil) } if (phones.size() > 0) { let phonesValues: ABMultiValueRef = ABMultiValueCreateMutable(UInt32(kABMultiStringPropertyType)).takeRetainedValue() for i in 0..<phones.size() { let p = phones.getWithInt(i) as! String ABMultiValueAddValueAndLabel(phonesValues, p.replace(" ", dest: ""), kABPersonPhoneMainLabel, nil) } ABRecordSetValue(person, kABPersonPhoneProperty, phonesValues, nil) } if (emails.size() > 0) { let phonesValues: ABMultiValueRef = ABMultiValueCreateMutable(UInt32(kABMultiStringPropertyType)).takeRetainedValue() for i in 0..<emails.size() { let p = emails.getWithInt(i) as! String ABMultiValueAddValueAndLabel(phonesValues, p.replace(" ", dest: ""), kABPersonPhoneMainLabel, nil) } ABRecordSetValue(person, kABPersonEmailProperty, phonesValues, nil) } add.displayedPerson = person self.controller.presentViewController(AANavigationController(rootViewController: add), animated: true, completion: nil) }) controller.showActionSheet(menuBuilder.items, cancelButton: "AlertCancel", destructButton: nil, sourceView: tapView, sourceRect: tapView.bounds, tapClosure: menuBuilder.tapClosure) } } } public func newPersonViewController(newPersonView: ABNewPersonViewController, didCompleteWithNewPerson person: ABRecord?) { newPersonView.dismissViewControllerAnimated(true, completion: nil) } public func mailComposeController(controller: MFMailComposeViewController, didFinishWithResult result: MFMailComposeResult, error: NSError?) { controller.dismissViewControllerAnimated(true, completion: nil) } public override func bind(message: ACMessage, receiveDate: jlong, readDate: jlong, reuse: Bool, cellLayout: AACellLayout, setting: AACellSetting) { let contactLayout = cellLayout as! AAContactCellLayout // Always update bubble insets if (isOut) { bindBubbleType(.TextOut, isCompact: false) bubbleInsets = UIEdgeInsets( top: AABubbleCell.bubbleTop, left: 0 + (AADevice.isiPad ? 16 : 0), bottom: AABubbleCell.bubbleBottom, right: 4 + (AADevice.isiPad ? 16 : 0)) contentInsets = UIEdgeInsets( top: AABubbleCell.bubbleContentTop, left: 6, bottom: AABubbleCell.bubbleContentBottom, right: 10) name.textColor = ActorSDK.sharedActor().style.chatTextOutColor } else { bindBubbleType(.TextIn, isCompact: false) bubbleInsets = UIEdgeInsets( top: AABubbleCell.bubbleTop, left: 4 + (AADevice.isiPad ? 16 : 0), bottom: AABubbleCell.bubbleBottom, right: 0 + (AADevice.isiPad ? 16 : 0)) contentInsets = UIEdgeInsets( top: (isGroup ? 18 : 0) + AABubbleCell.bubbleContentTop, left: 13, bottom: AABubbleCell.bubbleContentBottom, right: 10) name.textColor = ActorSDK.sharedActor().style.chatTextInColor } name.text = contactLayout.name var s = "" for i in contactLayout.records { if (s != ""){ s += "\n" } s += i } contact.text = s contact.numberOfLines = contactLayout.records.count bindedRecords = contactLayout.records avatar.bind(contactLayout.name, id: 0, avatar: nil) } public override func layoutContent(maxWidth: CGFloat, offsetX: CGFloat) { // Convenience let insets = fullContentInsets let contentWidth = self.contentView.frame.width let height = max(44, bindedRecords.count * 18 + 22) layoutBubble(200, contentHeight: CGFloat(height)) if (isOut) { avatar.frame = CGRectMake(contentWidth - insets.right - 200, insets.top, 46, 46) tapView.frame = CGRectMake(contentWidth - insets.left - 200, insets.top, 200, CGFloat(height)) } else { avatar.frame = CGRectMake(insets.left, insets.top, 44, 44) tapView.frame = CGRectMake(insets.left, insets.top, 200, CGFloat(height)) } name.frame = CGRectMake(avatar.right + 6, insets.top, 200 - 58, 22) contact.frame = CGRectMake(avatar.right + 6, insets.top + 22, 200 - 58, 200) contact.sizeToFit() } } public class AAContactCellLayout: AACellLayout { let name: String let records: [String] init(name: String, records: [String], date: Int64, layouter: AABubbleLayouter) { self.name = name self.records = records let height = max(44, records.count * 18 + 22) + 12 super.init(height: CGFloat(height), date: date, key: "location", layouter: layouter) } } public class AABubbleContactCellLayouter: AABubbleLayouter { public func isSuitable(message: ACMessage) -> Bool { if (!ActorSDK.sharedActor().enableExperimentalFeatures) { return false } if (message.content is ACContactContent) { return true } return false } public func cellClass() -> AnyClass { return AABubbleContactCell.self } public func buildLayout(peer: ACPeer, message: ACMessage) -> AACellLayout { let content = message.content as! ACContactContent var records = [String]() for i in 0..<content.getPhones().size() { records.append(content.getPhones().getWithInt(i) as! String) } for i in 0..<content.getEmails().size() { records.append(content.getEmails().getWithInt(i) as! String) } return AAContactCellLayout(name: content.getName(), records: records, date: Int64(message.date), layouter: self) } }
563de2e14ca00caeddad51be070bb99c
42.245614
196
0.569632
false
false
false
false
xuyunan/YNWebViewController
refs/heads/master
YNWebViewController/YNWebViewController.swift
mit
1
// // YNWebViewController.swift // YNWebViewController // // Created by Tommy on 15/12/15. // Copyright © 2015年 [email protected]. All rights reserved. // import UIKit public class YNWebViewController: UIViewController, UIWebViewDelegate { public var request: URLRequest public var webView = UIWebView() public var delegate: UIWebViewDelegate? public lazy var backBarButtonItem: UIBarButtonItem = { // for cocoapods let bundle = Bundle(for: YNWebViewController.self) let backImage = UIImage(named: "YNWebViewControllerBack.png", in: bundle, compatibleWith: nil) let item = UIBarButtonItem(image: backImage, style: .plain, target: self, action: #selector(YNWebViewController.goBackTapped(_:))) item.width = 18 return item }() public lazy var forwardBarButtonItem: UIBarButtonItem = { // for cocoapods let bundle = Bundle(for: YNWebViewController.self) let nextImage = UIImage(named: "YNWebViewControllerNext.png", in: bundle, compatibleWith: nil) let item = UIBarButtonItem(image: nextImage, style: .plain, target: self, action: #selector(YNWebViewController.goForwardTapped(_:))) item.width = 18 return item }() public lazy var refreshBarButtonItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: .refresh, target: self, action: #selector(YNWebViewController.reloadTapped(_:))) return item }() public lazy var stopBarButtonItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(YNWebViewController.stopTapped(_:))) return item }() public lazy var actionBarButtonItem: UIBarButtonItem = { let item = UIBarButtonItem(barButtonSystemItem: .action, target: self, action: #selector(YNWebViewController.actionButtonTapped(_:))) return item }() convenience public init(url: URL) { self.init(request: URLRequest(url: url)) } public init(request: URLRequest) { self.request = request super.init(nibName: nil, bundle: nil) } required public init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override public func viewDidLoad() { super.viewDidLoad() self.navigationController?.isToolbarHidden = false webView.frame = UIScreen.main.bounds webView.scalesPageToFit = true webView.loadRequest(request) webView.delegate = self view.addSubview(webView) } public func updateToolbarItems() { self.backBarButtonItem.isEnabled = self.webView.canGoBack self.forwardBarButtonItem.isEnabled = self.webView.canGoForward let refreshStopBarButtonItem = self.webView.isLoading ? self.stopBarButtonItem : self.refreshBarButtonItem; let fixedSpace = UIBarButtonItem(barButtonSystemItem: .fixedSpace, target: nil, action: nil) let flexibleSpace = UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil) let items = [fixedSpace, self.backBarButtonItem, flexibleSpace, self.forwardBarButtonItem, flexibleSpace, refreshStopBarButtonItem, flexibleSpace, self.actionBarButtonItem, fixedSpace] self.toolbarItems = items self.navigationController!.toolbar.barStyle = self.navigationController!.navigationBar.barStyle self.navigationController!.toolbar.tintColor = self.navigationController!.navigationBar.tintColor } public func goBackTapped(_ sender: UIBarButtonItem) { self.webView.goBack() } public func goForwardTapped(_ sender: UIBarButtonItem) { self.webView.goForward() } public func reloadTapped(_ sender: UIBarButtonItem) { self.webView.reload() } public func stopTapped(_ sender: UIBarButtonItem) { self.webView.stopLoading() self.updateToolbarItems() } func actionButtonTapped(_ sender: UIBarButtonItem) { let requestURL = self.webView.request!.url ?? self.request.url if let url = requestURL { let activityItems = [YNWebViewControllerActivitySafari(), YNWebViewControllerActivityChrome()] if url.absoluteString.hasPrefix("file:///") { let dc = UIDocumentInteractionController(url: url) dc.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true) } else { let activityController = UIActivityViewController(activityItems:[url] , applicationActivities: activityItems) self.present(activityController, animated: true, completion: nil) } } } // MARK: - UIWebViewDelegate public func webViewDidStartLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = true self.updateToolbarItems() delegate?.webViewDidStartLoad?(webView) } public func webViewDidFinishLoad(_ webView: UIWebView) { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.updateToolbarItems() self.navigationItem.title = webView.stringByEvaluatingJavaScript(from: "document.title") ?? "title" delegate?.webViewDidFinishLoad?(webView) } public func webView(_ webView: UIWebView, didFailLoadWithError error: Error) { UIApplication.shared.isNetworkActivityIndicatorVisible = false self.updateToolbarItems() delegate?.webView?(webView, didFailLoadWithError: error) } public func webView(_ webView: UIWebView, shouldStartLoadWith request: URLRequest, navigationType: UIWebViewNavigationType) -> Bool { return (delegate?.webView?(webView, shouldStartLoadWith: request, navigationType: navigationType)) ?? true } public override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } deinit { self.webView.stopLoading() self.webView.delegate = nil UIApplication.shared.isNetworkActivityIndicatorVisible = false } }
d3a7fd208d7412ea7eab2decdd6efe3f
38.377358
192
0.680562
false
false
false
false
manuelCarlos/AutoLayout-park
refs/heads/master
alternateViews/alternateViews/Views/LandscapeView.swift
mit
1
// // LandscapeView.swift // alternateViews // // Created by Manuel Lopes on 11/05/16. // import UIKit class LandscapeView: UIView { override init(frame: CGRect) { super.init(frame: frame) setup() } required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) setup() } convenience init() { self.init(frame: CGRect.zero) } private func setup() { let margins = self.layoutMarginsGuide backgroundColor = #colorLiteral(red: 1, green: 1, blue: 1, alpha: 1) let title: UILabel = setupTitle() let pic = setUpProfilePic() let plus = makeButtonWithTitle("+", fontSize: 20) let back = makeButtonWithTitle("<", fontSize: 20) addSubview(title) addSubview(pic) addSubview(plus) addSubview(back) NSLayoutConstraint.activate([ title.centerXAnchor.constraint(equalTo: centerXAnchor), title.centerYAnchor.constraint(equalTo: centerYAnchor), pic.centerXAnchor.constraint(equalTo: centerXAnchor), pic.topAnchor.constraint(equalTo: title.bottomAnchor,constant: 10), pic.bottomAnchor.constraint(equalTo: margins.bottomAnchor, constant: -50), plus.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20), plus.trailingAnchor.constraint(equalTo: margins.trailingAnchor, constant: -20), back.topAnchor.constraint(equalTo: margins.topAnchor, constant: 20), back.leadingAnchor.constraint(equalTo: margins.leadingAnchor, constant: 20) ]) } // equivalent to viweWillAppear() override func willMove(toSuperview newSuperview: UIView?) { super.willMove(toSuperview: newSuperview) // nothing here for now } // equivalente to viewWillLayoutSubviews() and viewDidLayoutSubviews() override func layoutSubviews() { super.layoutSubviews() // nothing here for now } private func setUpProfilePic() -> UIImageView { let pic = UIImageView(image: UIImage(named: "me")) pic.translatesAutoresizingMaskIntoConstraints = false pic.contentMode = .scaleAspectFit return pic } private func setupTitle() -> UILabel { let lab = UILabel() lab.text = "Mr. Fox in Landscape" lab.font = UIFont.systemFont(ofSize: 60) lab.translatesAutoresizingMaskIntoConstraints = false return lab } private func makeButtonWithTitle(_ title: String, fontSize: Int) -> UIButton { let button = UIButton(type: .system) button.tintColor = #colorLiteral(red: 1, green: 0, blue: 0, alpha: 1) button.setTitle(title, for: UIControlState()) button.titleLabel?.font = .boldSystemFont(ofSize: CGFloat(fontSize)) button.translatesAutoresizingMaskIntoConstraints = false return button } }
59561988383fd768921df46b1fdb1629
30.393617
87
0.639444
false
false
false
false
RMKitty/DYZB
refs/heads/master
DYZB/DYZB/Classes/Home/Controller/HomeViewController.swift
mit
1
// // HomeViewController.swift // DYZB // // Created by Kitty on 2017/4/20. // Copyright © 2017年 RM. All rights reserved. // import UIKit private let kTitleViewH : CGFloat = 40 class HomeViewController: UIViewController { // MARK: - 标题 fileprivate lazy var pageTitleView: PageTitleView = { [weak self] in let titleFram = CGRect(x: 0, y: kStatusBarH + kNavigationBarH, width: kScreenW, height: kTitleViewH) let titles = ["推荐", "游戏", "娱乐", "趣玩"] let titleView = PageTitleView(frame: titleFram, titles: titles) titleView.delegate = self return titleView }() // MARK: - 内容 fileprivate lazy var pageContentView : PageContentView = {[weak self] in let contentH = kScreenH - kStatusBarH - kNavigationBarH - kTitleViewH - kTabbarH let contentFrame = CGRect(x: 0, y: kStatusBarH + kNavigationBarH + kTitleViewH, width: kScreenW, height: contentH) var childVcs = [UIViewController]() childVcs.append(RecommendViewController()) for _ in 0..<3 { let vc = UIViewController() vc.view.backgroundColor = UIColor(r: CGFloat(arc4random_uniform(255)), g: CGFloat(arc4random_uniform(255)), b: CGFloat(arc4random_uniform(255))) childVcs.append(vc) } let contentView = PageContentView(frame: contentFrame, childVcs: childVcs, parsentViewController: self) contentView.delegate = self return contentView }() override func viewDidLoad() { super.viewDidLoad() setupUI() } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } } extension HomeViewController { fileprivate func setupUI() { automaticallyAdjustsScrollViewInsets = false setupNavigationBar() //添加TitleView view.addSubview(pageTitleView) // MARK: - 内容View view.addSubview(pageContentView) pageContentView.backgroundColor = UIColor.red } private func setupNavigationBar() { navigationItem.leftBarButtonItem = UIBarButtonItem.init(imageName: "logo") let size = CGSize.init(width: 40, height: 40) let historyItem = UIBarButtonItem.init(imageName: "image_my_history", highImage: "image_my_history_click", size: size) let searchItem = UIBarButtonItem.init(imageName: "btn_search", highImage: "btn_search_clicked", size: size) let qarcodeItem = UIBarButtonItem.init(imageName: "Image_scan", highImage: "Image_scan_click", size: size) navigationItem.rightBarButtonItems = [historyItem, searchItem, qarcodeItem] } } // MARK: - PageTitleViewDelegate extension HomeViewController: PageTitleViewDelegate { func pagetTitleView(titleView: PageTitleView, selectedIndex: Int) { pageContentView.setCurrentIndex(currentIndex: selectedIndex) } } // MARK: - PageContentViewDelegate extension HomeViewController : PageContentViewDelegate { func pageContentView(contentView: PageContentView, progress: CGFloat, sourceIndex: Int, targetIndex: Int) { pageTitleView.setTitleViewProgess(progress: progress, sourceIndex: sourceIndex, targetIndex: targetIndex) } }
95116109a262a845ee87f8f4f88036a8
34.086022
156
0.670549
false
false
false
false
oleander/bitbar
refs/heads/master
Sources/BitBar/Title.swift
mit
1
import Parser import BonMot import Async import Plugin final class Title: MenuBase { private let ago = Pref.UpdatedTimeAgo() private let runInTerminal = Pref.RunInTerminal() private var numberOfPrefs = 0 internal var hasLoaded: Bool = false init(prefs: [NSMenuItem]) { super.init() self.numberOfPrefs = 4 self.delegate = self add(submenu: NSMenuItem.separator(), at: 0) add(submenu: ago, at: 1) add(submenu: runInTerminal, at: 2) add(submenu: Pref.Preferences(prefs: prefs), at: 3) } // Only keep pref menus func set(menus: [NSMenuItem]) { reset() for (index, menu) in menus.enumerated() { add(submenu: menu, at: index) } ago.reset() hasLoaded = true } required init(coder decoder: NSCoder) { fatalError("init(coder:) has not been implemented") } private func reset() { guard numberOfPrefs < numberOfItems else { return } for _ in numberOfPrefs..<numberOfItems { remove(at: 0) } } }
6fc555f10a3d8243d8a9b7e734265015
21.545455
55
0.65625
false
false
false
false
EricHein/Swift3.0Practice2016
refs/heads/master
00.ScratchWork/PermanentDataStorage/PermanentDataStorage/ViewController.swift
gpl-3.0
1
// // ViewController.swift // PermanentDataStorage // // Created by Eric H on 14/10/2016. // Copyright © 2016 FabledRealm. All rights reserved. // import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() //UserDefaults.standard.set("Eric", forKey:"name") let nameObject = UserDefaults.standard.object(forKey: "name") if let name = nameObject as? String{ print(name) } //let array = [1,2,3,4,5] //UserDefaults.standard.set(array, forKey: "array") let arrayObjects = UserDefaults.standard.object(forKey: "array") if let arr = arrayObjects as? NSArray { print(arr) } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() } }
41d773938c548327838b35f701e0f790
18.9375
72
0.53814
false
false
false
false
paulgriffiths/macvideopoker
refs/heads/master
VideoPokerTests/CardCounterTests.swift
gpl-3.0
1
// // CardCounterTests.swift // VideoPoker // // Created by Paul Griffiths on 5/9/15. // Copyright (c) 2015 Paul Griffiths. All rights reserved. // import Cocoa import XCTest class CardCounterTests: XCTestCase { let counter = CardCounter(cardList: CardList(cards: Cards.ThreeClubs.card, Cards.FiveHearts.card, Cards.FiveDiamonds.card, Cards.SixSpades.card, Cards.SixHearts.card, Cards.NineHearts.card, Cards.NineClubs.card, Cards.NineSpades.card, Cards.JackDiamonds.card, Cards.QueenSpades.card, Cards.KingDiamonds.card, Cards.AceSpades.card, Cards.AceClubs.card)) func testCountForRank() { XCTAssertEqual(2, counter.countForRank(.Ace)) XCTAssertEqual(0, counter.countForRank(.Two)) XCTAssertEqual(1, counter.countForRank(.Three)) XCTAssertEqual(0, counter.countForRank(.Four)) XCTAssertEqual(2, counter.countForRank(.Five)) XCTAssertEqual(2, counter.countForRank(.Six)) XCTAssertEqual(0, counter.countForRank(.Seven)) XCTAssertEqual(0, counter.countForRank(.Eight)) XCTAssertEqual(3, counter.countForRank(.Nine)) XCTAssertEqual(0, counter.countForRank(.Ten)) XCTAssertEqual(1, counter.countForRank(.Jack)) XCTAssertEqual(1, counter.countForRank(.Queen)) XCTAssertEqual(1, counter.countForRank(.King)) } func testContainsRank() { XCTAssertTrue(counter.containsRank(.Ace)) XCTAssertFalse(counter.containsRank(.Two)) XCTAssertTrue(counter.containsRank(.Three)) XCTAssertFalse(counter.containsRank(.Four)) XCTAssertTrue(counter.containsRank(.Five)) XCTAssertTrue(counter.containsRank(.Six)) XCTAssertFalse(counter.containsRank(.Seven)) XCTAssertFalse(counter.containsRank(.Eight)) XCTAssertTrue(counter.containsRank(.Nine)) XCTAssertFalse(counter.containsRank(.Ten)) XCTAssertTrue(counter.containsRank(.Jack)) XCTAssertTrue(counter.containsRank(.Queen)) XCTAssertTrue(counter.containsRank(.King)) } func testNumRanks() { XCTAssertEqual(8, counter.numRanks) } func testCountForSuit() { XCTAssertEqual(3, counter.countForSuit(.Clubs)) XCTAssertEqual(3, counter.countForSuit(.Hearts)) XCTAssertEqual(4, counter.countForSuit(.Spades)) XCTAssertEqual(3, counter.countForSuit(.Diamonds)) } func testContainsSuit() { XCTAssertTrue(counter.containsSuit(.Clubs)) XCTAssertTrue(counter.containsSuit(.Hearts)) XCTAssertTrue(counter.containsSuit(.Spades)) XCTAssertTrue(counter.containsSuit(.Diamonds)) } func testNumSuits() { XCTAssertEqual(4, counter.numSuits) } func testNumberRankByCount() { for (index, count) in [0, 4, 3, 1, 0, 0, 0].enumerate() { XCTAssertEqual(count, counter.numberRankByCount(index)) } } func testHasRankCountWhenPresent() { for index in 1...3 { XCTAssertTrue(counter.containsRankCount(index)) } } func testHasRankCountWhenNotPresent() { for index in 4...6 { XCTAssertFalse(counter.containsRankCount(index)) } } func testHighestRankByCountWhenPresent() { for (index, expectedRank) in [Rank.King, Rank.Ace, Rank.Nine].enumerate() { if let rank = counter.highestRankByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testHighestRankByCountWhenNotPresent() { for index in 4...6 { if counter.highestRankByCount(index) != nil { XCTFail("rank found when not expected") } } } func testSecondHighestRankByCountWhenPresent() { for (index, expectedRank) in [Rank.Queen, Rank.Six].enumerate() { if let rank = counter.secondHighestRankByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testSecondHighestRankByCountWhenNotPresent() { for index in 3...6 { if counter.secondHighestRankByCount(index) != nil { XCTFail("rank found when not expected") } } } func testLowestRankByCountWhenPresent() { for (index, expectedRank) in [Rank.Three, Rank.Five, Rank.Nine].enumerate() { if let rank = counter.lowestRankByCount(index + 1) { XCTAssertEqual(expectedRank, rank) } else { XCTFail("expected rank count not found") } } } func testLowestRankByCountWhenNotPresent() { for index in 4...6 { if counter.lowestRankByCount(index) != nil { XCTFail("rank found when not expected") } } } func testRankRangeByCountWhenPresent() { for (index, expectedRange) in [13 - 3, 14 - 5, 9 - 9].enumerate() { if let range = counter.rankRangeByCount(index + 1) { XCTAssertEqual(expectedRange, range) } else { XCTFail("expected range not found") } } } func testRankRangeByCountWhenNotPresent() { for index in 4...6 { if counter.rankRangeByCount(index) != nil { XCTFail("range found when not expected") } } } func testRankScoreByCountWhenPresent() { func sCmpt(rank: Rank, index: Int) -> Int { return rank.value * Int(pow(Double(Rank.numberOfRanks), Double(index))) } let expectedScores = [ (sCmpt(Rank.King, index: 3) + sCmpt(Rank.Queen, index: 2) + sCmpt(Rank.Jack, index: 1) + sCmpt(Rank.Three, index: 0)), (sCmpt(Rank.Ace, index: 2) + sCmpt(Rank.Six, index: 1) + sCmpt(Rank.Five, index: 0)), (sCmpt(Rank.Nine, index: 0)) ] for (index, expectedScore) in expectedScores.enumerate() { if let score = counter.rankScoreByCount(index + 1) { XCTAssertEqual(expectedScore, score) } else { XCTFail("expected score not found") } } } func testRankScoreByCountWhenNotPresent() { for index in 4...6 { if counter.rankScoreByCount(index) != nil { XCTFail("score found when not expected") } } } func testNoCardsNotStraight() { let sc = CardCounter(cardList: CardList()) XCTAssertFalse(sc.isStraight) } func testOneCardStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.NineDiamonds)) XCTAssertTrue(sc.isStraight) } func testTwoCardStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.SevenClubs, Cards.EightDiamonds)) XCTAssertTrue(sc.isStraight) } func testTwoCardNotStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.SevenClubs, Cards.NineDiamonds)) XCTAssertFalse(sc.isStraight) } func testTwoCardWheelStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.AceHearts, Cards.TwoSpades)) XCTAssertTrue(sc.isStraight) } func testTwoCardNotWheelStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.AceHearts, Cards.ThreeSpades)) XCTAssertFalse(sc.isStraight) } func testThreeCardStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.SevenClubs, Cards.EightDiamonds, Cards.NineSpades)) XCTAssertTrue(sc.isStraight) } func testThreeCardNotStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.SevenClubs, Cards.NineDiamonds, Cards.NineSpades)) XCTAssertFalse(sc.isStraight) } func testThreeCardWheelStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.AceHearts, Cards.TwoSpades, Cards.ThreeClubs)) XCTAssertTrue(sc.isStraight) } func testThreeCardNotWheelStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.AceHearts, Cards.ThreeSpades, Cards.ThreeDiamonds)) XCTAssertFalse(sc.isStraight) } func testFourCardStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.SevenClubs, Cards.EightDiamonds, Cards.NineSpades, Cards.TenClubs)) XCTAssertTrue(sc.isStraight) } func testFourCardWheelStraight() { let sc = CardCounter(cardList: CardList(cards: Cards.AceHearts, Cards.TwoSpades, Cards.ThreeClubs, Cards.FourDiamonds)) XCTAssertTrue(sc.isStraight) } }
21b380e93a9cec72dc3f23a5242e774e
33.7393
130
0.615927
false
true
false
false
hovansuit/FoodAndFitness
refs/heads/master
FoodAndFitness/Controllers/FoodDetail/FoodDetailViewModel.swift
mit
1
// // FoodDetailViewModel.swift // FoodAndFitness // // Created by Mylo Ho on 4/15/17. // Copyright © 2017 SuHoVan. All rights reserved. // import UIKit import RealmSwift import RealmS struct UserFoodParams { var userId: Int var foodId: Int var weight: Int var meal: String } final class FoodDetailViewModel { var food: Food var activity: HomeViewController.AddActivity init(food: Food, activity: HomeViewController.AddActivity) { self.food = food self.activity = activity } func dataForHeaderView() -> MealHeaderView.Data? { return MealHeaderView.Data(title: food.name, detail: nil, image: activity.image) } func save(weight: Int, completion: @escaping Completion) { guard let user = User.me else { let error = NSError(message: Strings.Errors.tokenError) completion(.failure(error)) return } let params = UserFoodParams(userId: user.id, foodId: food.id, weight: weight, meal: activity.title) FoodServices.save(params: params, completion: completion) } func dataForInformationFood() -> InformationFoodCell.Data { let maxValue = Double(food.carbs + food.protein + food.fat) let carbs = Double(food.carbs).percent(max: maxValue) let protein = Double(food.protein).percent(max: maxValue) let fat = Double(food.fat).percent(max: maxValue) return InformationFoodCell.Data(carbs: Int(carbs), protein: Int(protein), fat: Int(fat)) } func dataForSaveUserFood() -> SaveUserFoodCell.Data? { let `default` = food.weight let calories = food.calories return SaveUserFoodCell.Data(default: "\(`default`)", calories: "\(calories)") } }
ea78c658b9909f2cb48742bf1b1364f2
30.303571
107
0.661152
false
false
false
false
mnito/alt-file
refs/heads/master
io/functions/fileGetString.swift
mit
1
#if os(OSX) || os(iOS) || os(watchOS) || os(tvOS) import Darwin #else import Glibc #endif public func fileGetString(path: String) -> String? { let file = LineReader(path: path) var str = "" for line in file { str += line } if(str == "") { return nil } return str }
2601993a7c84db439eb3dd264db38a55
16.176471
52
0.589041
false
false
false
false
darjeelingsteve/uistackview_adaptivity
refs/heads/master
CountiesModel/Sources/FavouritesController.swift
mit
1
// // FavouritesController.swift // CountiesModel // // Created by Stephen Anthony on 20/01/2020. // Copyright © 2020 Darjeeling Apps. All rights reserved. // import Foundation /// The object responsible for managing the list of the user's favourite /// counties. public final class FavouritesController { /// The shared instance of `FavouritesController`. public static let shared = FavouritesController() /// The notification posted when the user adds or removes a favourite /// county. public static let favouriteCountiesDidChangeNotification = NSNotification.Name("FavouriteCountiesDidChange") private static let favouriteCountiesKey = "FavouriteCounties" /// The counties that the user has chosen as their favourites. public var favouriteCounties: [County] { let counties = (ubiquitousKeyValueStore.array(forKey: FavouritesController.favouriteCountiesKey) as? [String])?.compactMap({ Country.unitedKingdom.county(forName: $0) }) return counties ?? [] } private let ubiquitousKeyValueStore: UbiquitousKeyValueStorageProviding /// Initialises a new `FavouritesController` backed by the given ubiquitous /// key-value store. /// - Parameter ubiquitousKeyValueStore: The ubiquitous key-value store used /// to persist the user's favourite counties. init(ubiquitousKeyValueStore: UbiquitousKeyValueStorageProviding = NSUbiquitousKeyValueStore.default) { self.ubiquitousKeyValueStore = ubiquitousKeyValueStore NotificationCenter.default.addObserver(self, selector: #selector(favouritesDidUpdateExternally(_:)), name: NSUbiquitousKeyValueStore.didChangeExternallyNotification, object: ubiquitousKeyValueStore) } /// Adds the given county to the user's favourites. /// - Parameter county: The county to add to the user's favourites. public func add(county: County) { guard favouriteCounties.firstIndex(of: county) == nil else { return } ubiquitousKeyValueStore.set((favouriteCounties + [county]).sorted().countyNames, forKey: FavouritesController.favouriteCountiesKey) NotificationCenter.default.post(name: FavouritesController.favouriteCountiesDidChangeNotification, object: self) } /// Removes the given county from the user's favourites. /// - Parameter county: The county to remove from the user's favourites. public func remove(county: County) { guard let countyIndex = favouriteCounties.firstIndex(of: county) else { return } var mutableFavourites = favouriteCounties mutableFavourites.remove(at: countyIndex) ubiquitousKeyValueStore.set(mutableFavourites.countyNames, forKey: FavouritesController.favouriteCountiesKey) NotificationCenter.default.post(name: FavouritesController.favouriteCountiesDidChangeNotification, object: self) } /// Synchronises the receiver's ubiquitous key-value store. public func synchronise() { _ = ubiquitousKeyValueStore.synchronize() } @objc private func favouritesDidUpdateExternally(_ notification: Notification) { NotificationCenter.default.post(name: FavouritesController.favouriteCountiesDidChangeNotification, object: self) } } protocol UbiquitousKeyValueStorageProviding: AnyObject { func set(_ anObject: Any?, forKey aKey: String) func array(forKey aKey: String) -> [Any]? func synchronize() -> Bool } extension NSUbiquitousKeyValueStore: UbiquitousKeyValueStorageProviding {} private extension Array where Element == County { var countyNames: [String] { return map { $0.name } } }
8771e5793bdc6fd72a6f7f3cd784cfd0
43.975904
177
0.721404
false
false
false
false
Tomikes/eidolon
refs/heads/master
Kiosk/Bid Fulfillment/RegistrationEmailViewController.swift
mit
6
import UIKit import Swift_RAC_Macros import ReactiveCocoa class RegistrationEmailViewController: UIViewController, RegistrationSubController, UITextFieldDelegate { @IBOutlet var emailTextField: TextField! @IBOutlet var confirmButton: ActionButton! let finishedSignal = RACSubject() lazy var viewModel: GenericFormValidationViewModel = { let emailIsValidSignal = self.emailTextField.rac_textSignal().map(stringIsEmailAddress) return GenericFormValidationViewModel(isValidSignal: emailIsValidSignal, manualInvocationSignal: self.emailTextField.returnKeySignal(), finishedSubject: self.finishedSignal) }() lazy var bidDetails: BidDetails! = { self.navigationController!.fulfillmentNav().bidDetails }() override func viewDidLoad() { super.viewDidLoad() emailTextField.text = bidDetails.newUser.email RAC(bidDetails, "newUser.email") <~ emailTextField.rac_textSignal().takeUntil(viewWillDisappearSignal()) confirmButton.rac_command = viewModel.command emailTextField.becomeFirstResponder() } func textField(textField: UITextField, shouldChangeCharactersInRange range: NSRange, replacementString string: String) -> Bool { // Allow delete if (string.isEmpty) { return true } // the API doesn't accept spaces return string != " " } class func instantiateFromStoryboard(storyboard: UIStoryboard) -> RegistrationEmailViewController { return storyboard.viewControllerWithID(.RegisterEmail) as! RegistrationEmailViewController } }
3b57480d387aaceda431e603bbb870cb
38.35
181
0.748412
false
false
false
false
mmsaddam/TheMovie
refs/heads/master
TheMovie/HTTPClient.swift
mit
1
// // HTTPClient.swift // TheMovie // // Created by Md. Muzahidul Islam on 7/16/16. // Copyright © 2016 iMuzahid. All rights reserved. // import UIKit class HTTPClient: NSObject { // downlaod image for specific url func downloadImage(url: String) -> (UIImage?) { let aUrl = NSURL(string: url) if let data = NSData(contentsOfURL: aUrl!){ return UIImage(data: data) }else{ return nil } } // Request for the JSON func httpRequest(url: String, completion:(data: NSData?) -> (Void)){ let requestURL: NSURL = NSURL(string: url)! let urlRequest: NSMutableURLRequest = NSMutableURLRequest(URL: requestURL) let session = NSURLSession.sharedSession() let task = session.dataTaskWithRequest(urlRequest) { (data, response, error) -> Void in let httpResponse = response as! NSHTTPURLResponse let statusCode = httpResponse.statusCode if (statusCode == 200) { completion(data: data) }else{ completion(data: nil) } } task.resume() } }
dd6cde2780ef4324b700da81a836f110
20
78
0.619963
false
false
false
false
mrdepth/EVEUniverse
refs/heads/master
Legacy/Neocom/Neocom/MarketQuickbarPresenter.swift
lgpl-2.1
2
// // MarketQuickbarPresenter.swift // Neocom // // Created by Artem Shimanski on 11/5/18. // Copyright © 2018 Artem Shimanski. All rights reserved. // import Foundation import Futures import CloudData import TreeController class MarketQuickbarPresenter: TreePresenter { typealias View = MarketQuickbarViewController typealias Interactor = MarketQuickbarInteractor typealias Presentation = Tree.Item.FetchedResultsController<Tree.Item.NamedFetchedResultsSection<Tree.Item.InvType>> weak var view: View? lazy var interactor: Interactor! = Interactor(presenter: self) var content: Interactor.Content? var presentation: Presentation? var loading: Future<Presentation>? required init(view: View) { self.view = view } func configure() { view?.tableView.register([Prototype.TreeSectionCell.default, Prototype.InvTypeCell.charge, Prototype.InvTypeCell.default, Prototype.InvTypeCell.module, Prototype.InvTypeCell.ship]) interactor.configure() applicationWillEnterForegroundObserver = NotificationCenter.default.addNotificationObserver(forName: UIApplication.willEnterForegroundNotification, object: nil, queue: .main) { [weak self] (note) in self?.applicationWillEnterForeground() } } private var applicationWillEnterForegroundObserver: NotificationObserver? func presentation(for content: Interactor.Content) -> Future<Presentation> { let treeController = view?.treeController return Services.storage.performBackgroundTask { context -> Future<Presentation> in guard let typeIDs = context.marketQuickItems()?.map ({ $0.typeID }), !typeIDs.isEmpty else { throw NCError.noResults } return Services.sde.performBackgroundTask { context -> Presentation in let controller = context.managedObjectContext .from(SDEInvType.self) .filter((\SDEInvType.typeID).in(typeIDs)) .sort(by: \SDEInvType.group?.category?.categoryName, ascending: true) .sort(by: \SDEInvType.typeName, ascending: true) .select( Tree.Item.InvType.propertiesToFetch + [(\SDEInvType.group?.category?.categoryName).as(String.self, name: "categoryName")]) .fetchedResultsController(sectionName: (\SDEInvType.group?.category?.categoryName).as(String.self, name: "categoryName")) try controller.performFetch() return Presentation(controller, treeController: treeController) } } } func didSelect<T: TreeItem>(item: T) -> Void { guard let item = item as? Tree.Item.InvType, let type = item.type, let view = view else {return} Router.SDE.invTypeInfo(.type(type)).perform(from: view) } }
f30484cf3ca5623598580ef0c5af3744
35.166667
200
0.748848
false
false
false
false
NativeNCreative/AidKit
refs/heads/master
Example/AidKit/MenuTableViewController.swift
mit
1
// // MenuTableViewController.swift // AidKit // // Created by Stein, Maxwell on 7/31/17. // Copyright © 2017 NativeNCreative. All rights reserved. // import UIKit import AidKit fileprivate let reuseIdentifier = String(describing: MenuTableViewCell.self) final class MenuTableViewCell: UITableViewCell { let isEnabledSwitch = UISwitch() var identifier: ComponentId? required init?(coder aDecoder: NSCoder) { super.init(coder: aDecoder) } override init(style: UITableViewCellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) selectionStyle = .none addSubview(isEnabledSwitch) isEnabledSwitch.translatesAutoresizingMaskIntoConstraints = false isEnabledSwitch.centerYAnchor.constraint(equalTo: centerYAnchor).isActive = true isEnabledSwitch.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10).isActive = true isEnabledSwitch.addTarget(self, action: #selector(tappedSwitch(_:)), for: .valueChanged) } @objc func tappedSwitch(_ sender: UISwitch) { // 2. Configure it if let identifier = identifier, let component = AKManager.shared.componentFor(identifier), var configurable = component.configurable { configurable.isOn = sender.isOn AKManager.shared.setConfiguration(configurable, identifier) } } func setup(with identifier: ComponentId) { textLabel?.text = identifier.rawValue self.identifier = identifier let configuration = AKManager.shared.configuration(identifier) isEnabledSwitch.isOn = configuration?.isOn ?? false } } protocol MenuCellToggled { func updateDisplayedCells() } final class MenuTableViewController: UITableViewController { let items = [ComponentId.recorder, ComponentId.visualizer, ComponentId.debugger] override func viewDidLoad() { super.viewDidLoad() // 1. Register your components AKManager.shared.registerNativeComponents() tableView.register(MenuTableViewCell.self, forCellReuseIdentifier: reuseIdentifier) title = "Configuration" navigationItem.leftBarButtonItem = UIBarButtonItem(title: "Cancel", style: .done, target: self, action: #selector(closeView)) navigationItem.rightBarButtonItem = UIBarButtonItem(title: "Confirm", style: .done, target: self, action: #selector(startAidKit)) } override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: reuseIdentifier) if let menuCell = cell as? MenuTableViewCell { menuCell.setup(with: items[indexPath.row]) } return cell ?? UITableViewCell() } // MARK: - Table view data source override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { return items.count } @objc func closeView() { dismiss(animated: true, completion: nil) } @objc func startAidKit() { closeView() // 3. Start AidKit Debugging AKManager.shared.start() } }
8862497c639c6a96e78ebc888a55c119
31.969388
137
0.691427
false
true
false
false
TheDarkCode/Example-Swift-Apps
refs/heads/master
Exercises and Basic Principles/azure-search-basics/azure-search-basics/AZSMapAnnotation.swift
mit
1
// // AZSMapAnnotation.swift // azure-search-basics // // Created by Mark Hamilton on 3/14/16. // Copyright © 2016 dryverless. All rights reserved. // import Foundation import MapKit class AZSMapAnnotation: NSObject, MKAnnotation { private var _coordinate: CLLocationCoordinate2D? var coordinate: CLLocationCoordinate2D { get { if let coord: CLLocationCoordinate2D = _coordinate { return coord } else { return CLLocationCoordinate2D() } } // set { // // if let newCoord = newValue as! CLLocationCoordinate2D where newCoord != nil { // // self._coordinate = newCoord // // } // // } } init(coordinate: CLLocationCoordinate2D) { self._coordinate = coordinate } }
2b9d3dbe3de5d65bfa312fc69c5eb409
19.9
91
0.465517
false
false
false
false
proxyco/RxBluetoothKit
refs/heads/master
Source/Observable+QueueSubscribeOn.swift
mit
1
// The MIT License (MIT) // // Copyright (c) 2016 Polidea // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. import Foundation import RxSwift /// Queue which is used for queueing subscriptions for queueSubscribeOn operator. class SerializedSubscriptionQueue { let scheduler: ImmediateSchedulerType let lock = NSLock() // First element on queue is curently subscribed and not completed // observable. All others are queued for subscription when the first // one is finished. var queue: [DelayedObservableType] = [] /** Creates a queue in which subscriptions will be executed sequentially after previous ones have finished. - parameter scheduler: Scheduler on which subscribption will be scheduled */ init(scheduler: ImmediateSchedulerType) { self.scheduler = scheduler } // Queue subscription for a queue. If observable is inserted // into empty queue it's subscribed immediately. Otherwise // it waits for completion from other observables. func queueSubscription(observable: DelayedObservableType) { lock.lock(); defer { lock.unlock() } let execute = queue.isEmpty queue.append(observable) if execute { // Observable is scheduled immidiately queue.first?.delayedSubscribe(scheduler) } } func unsubscribe(observable: DelayedObservableType) { lock.lock(); defer { lock.unlock() } // Find index of observable which should be unsubscribed // and remove it from queue if let index = queue.indexOf({ $0 === observable }) { queue.removeAtIndex(index) // If first item was unsubscribed, subscribe on next one // if available if index == 0 { queue.first?.delayedSubscribe(scheduler) } } } } protocol DelayedObservableType: class { func delayedSubscribe(scheduler: ImmediateSchedulerType) } class QueueSubscribeOn<Element>: Cancelable, ObservableType, ObserverType, DelayedObservableType { typealias E = Element let source: Observable<Element> let queue: SerializedSubscriptionQueue var observer: AnyObserver<Element>? let serialDisposable = SerialDisposable() var isDisposed: Int32 = 0 var disposed: Bool { return isDisposed == 1 } init(source: Observable<Element>, queue: SerializedSubscriptionQueue) { self.source = source self.queue = queue } // All event needs to be passed to original observer // if subscription was not disposed. If stream is completed // cleanup should occur. func on(event: Event<Element>) { guard !disposed else { return } observer?.on(event) if event.isStopEvent { dispose() } } // Part of producer implementation. We need to make sure that we can optimize // scheduling of a work (taken from RxSwift source code) func subscribe<O: ObserverType where O.E == Element>(observer: O) -> Disposable { if !CurrentThreadScheduler.isScheduleRequired { return run(observer) } else { return CurrentThreadScheduler.instance.schedule(()) { _ in return self.run(observer) } } } // After original subscription we need to place it on queue for delayed execution if required. func run<O: ObserverType where O.E == Element>(observer: O) -> Disposable { self.observer = observer.asObserver() queue.queueSubscription(self) return self } // Delayed subscription must be called after original subscription so that observer will be stored by that time. func delayedSubscribe(scheduler: ImmediateSchedulerType) { let cancelDisposable = SingleAssignmentDisposable() serialDisposable.disposable = cancelDisposable cancelDisposable.disposable = scheduler.schedule(()) { self.serialDisposable.disposable = self.source.subscribe(self) return NopDisposable.instance } } // When this observable is disposed we need to remove it from queue to let other // observables to be able to subscribe. We are doing it on the same thread as // subscription. func dispose() { if OSAtomicCompareAndSwap32(0, 1, &isDisposed) { queue.scheduler.schedule(()) { self.queue.unsubscribe(self) self.serialDisposable.dispose() return NopDisposable.instance } } } } extension ObservableType { // swiftlint:disable missing_docs /** Store subscription in queue on which it will be executed sequentially. Subscribe method is called only when there are no registered subscription on queue or last running observable completed its stream or was disposed before that event. - parameter queue: Queue on which scheduled subscriptions will be executed in sequentially. - returns: The source which will be subscribe when queue is empty or previous observable was completed or disposed. */ @warn_unused_result(message="http://git.io/rxs.uo") func queueSubscribeOn(queue: SerializedSubscriptionQueue) -> Observable<E> { return QueueSubscribeOn(source: self.asObservable(), queue: queue).asObservable() } // swiftlint:enable missing_docs }
98f588bdc05bc09c462a66903c87f599
37.560241
120
0.686143
false
false
false
false
CPRTeam/CCIP-iOS
refs/heads/master
Pods/EFQRCode/Source/EFQRCodeGenerator.swift
gpl-3.0
2
// // EFQRCodeGenerator.swift // EFQRCode // // Created by EyreFree on 17/1/24. // // Copyright (c) 2017 EyreFree <[email protected]> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. #if canImport(CoreImage) import CoreImage #else import CoreGraphics import swift_qrcodejs #endif // EFQRCode+Create @objcMembers public class EFQRCodeGenerator: NSObject { // MARK: - Parameters // Content of QR Code private var content: String? { didSet { imageQRCode = nil imageCodes = nil } } public func setContent(content: String) { self.content = content } // Encoding of the content private var contentEncoding: String.Encoding = .utf8 { didSet { imageQRCode = nil imageCodes = nil } } public func setContentEncoding(encoding: String.Encoding) { self.contentEncoding = encoding } // Mode of QR Code private var mode: EFQRCodeMode = .none { didSet { imageQRCode = nil } } public func setMode(mode: EFQRCodeMode) { self.mode = mode } // Error-tolerant rate // L 7% // M 15% // Q 25% // H 30%(Default) private var inputCorrectionLevel: EFInputCorrectionLevel = .h { didSet { imageQRCode = nil imageCodes = nil } } public func setInputCorrectionLevel(inputCorrectionLevel: EFInputCorrectionLevel) { self.inputCorrectionLevel = inputCorrectionLevel } // Size of QR Code private var size: EFIntSize = EFIntSize(width: 256, height: 256) { didSet { imageQRCode = nil } } public func setSize(size: EFIntSize) { self.size = size } // Magnification of QRCode compare with the minimum size, // (Parameter size will be ignored if magnification is not nil). private var magnification: EFIntSize? { didSet { imageQRCode = nil } } public func setMagnification(magnification: EFIntSize?) { self.magnification = magnification } // backgroundColor private var backgroundColor: CGColor = CGColor.white()! { didSet { imageQRCode = nil } } // foregroundColor private var foregroundColor: CGColor = CGColor.black()! { didSet { imageQRCode = nil } } #if canImport(CoreImage) @nonobjc public func setColors(backgroundColor: CIColor, foregroundColor: CIColor) { self.backgroundColor = backgroundColor.cgColor() ?? CGColor.white()! self.foregroundColor = foregroundColor.cgColor() ?? CGColor.black()! } #endif public func setColors(backgroundColor: CGColor, foregroundColor: CGColor) { self.backgroundColor = backgroundColor self.foregroundColor = foregroundColor } // Icon in the middle of QR Code private var icon: CGImage? = nil { didSet { imageQRCode = nil } } // Size of icon private var iconSize: EFIntSize? = nil { didSet { imageQRCode = nil } } public func setIcon(icon: CGImage?, size: EFIntSize?) { self.icon = icon self.iconSize = size } // Watermark private var watermark: CGImage? = nil { didSet { imageQRCode = nil } } // Mode of watermark private var watermarkMode: EFWatermarkMode = .scaleAspectFill { didSet { imageQRCode = nil } } public func setWatermark(watermark: CGImage?, mode: EFWatermarkMode? = nil) { self.watermark = watermark if let mode = mode { self.watermarkMode = mode } } // Offset of foreground point private var foregroundPointOffset: CGFloat = 0 { didSet { imageQRCode = nil } } public func setForegroundPointOffset(foregroundPointOffset: CGFloat) { self.foregroundPointOffset = foregroundPointOffset } // Alpha 0 area of watermark will transparent private var allowTransparent: Bool = true { didSet { imageQRCode = nil } } public func setAllowTransparent(allowTransparent: Bool) { self.allowTransparent = allowTransparent } // Shape of foreground point private var pointShape: EFPointShape = .square { didSet { imageQRCode = nil } } public func setPointShape(pointShape: EFPointShape) { self.pointShape = pointShape } private var ignoreTiming: Bool = false { didSet { imageQRCode = nil } } public func setIgnoreTiming(ignoreTiming: Bool) { self.ignoreTiming = ignoreTiming } // Cache private var imageCodes: [[Bool]]? private var imageQRCode: CGImage? private var minSuitableSize: EFIntSize! // MARK: - Init public init( content: String, size: EFIntSize = EFIntSize(width: 256, height: 256) ) { self.content = content self.size = size } /// Final QRCode image public func generate() -> CGImage? { if nil == imageQRCode { imageQRCode = createImageQRCode() } return imageQRCode } // MARK: - Draw private func createImageQRCode() -> CGImage? { var finalSize = self.size let finalBackgroundColor = getBackgroundColor() let finalForegroundColor = getForegroundColor() let finalIcon = self.icon let finalIconSize = self.iconSize let finalWatermark = self.watermark let finalWatermarkMode = self.watermarkMode // Get QRCodes from image guard let codes = generateCodes() else { return nil } // If magnification is not nil, reset finalSize if let tryMagnification = magnification { finalSize = EFIntSize( width: tryMagnification.width * codes.count, height: tryMagnification.height * codes.count ) } var result: CGImage? if let context = createContext(size: finalSize) { // Cache size minSuitableSize = EFIntSize( width: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.width.cgFloat) ?? finalSize.width, height: minSuitableSizeGreaterThanOrEqualTo(size: finalSize.height.cgFloat) ?? finalSize.height ) // Watermark if let tryWatermark = finalWatermark { // Draw background with watermark drawWatermarkImage( context: context, image: tryWatermark, colorBack: finalBackgroundColor, mode: finalWatermarkMode, size: finalSize.cgSize ) // Draw QR Code if let tryFrontImage = createQRCodeImageTransparent( codes: codes, colorBack: finalBackgroundColor, colorFront: finalForegroundColor, size: minSuitableSize) { context.draw(tryFrontImage, in: CGRect(origin: .zero, size: finalSize.cgSize)) } } else { // Draw background without watermark let colorCGBack = finalBackgroundColor context.setFillColor(colorCGBack) context.fill(CGRect(origin: .zero, size: finalSize.cgSize)) // Draw QR Code if let tryImage = createQRCodeImage( codes: codes, colorBack: finalBackgroundColor, colorFront: finalForegroundColor, size: minSuitableSize) { context.draw(tryImage, in: CGRect(origin: .zero, size: finalSize.cgSize)) } } // Add icon if let tryIcon = finalIcon { var finalIconSizeWidth = finalSize.width.cgFloat * 0.2 var finalIconSizeHeight = finalSize.height.cgFloat * 0.2 if let tryFinalIconSize = finalIconSize { finalIconSizeWidth = tryFinalIconSize.width.cgFloat finalIconSizeHeight = tryFinalIconSize.height.cgFloat } let maxLength = [CGFloat(0.2), 0.3, 0.4, 0.5][inputCorrectionLevel.rawValue] * finalSize.width.cgFloat if finalIconSizeWidth > maxLength { finalIconSizeWidth = maxLength print("Warning: icon width too big, it has been changed.") } if finalIconSizeHeight > maxLength { finalIconSizeHeight = maxLength print("Warning: icon height too big, it has been changed.") } let iconSize = EFIntSize(width: Int(finalIconSizeWidth), height: Int(finalIconSizeHeight)) drawIcon( context: context, icon: tryIcon, size: iconSize ) } result = context.makeImage() } // Mode apply switch mode { case .grayscale: if let tryModeImage = result?.grayscale { result = tryModeImage } case .binarization(let threshold): if let tryModeImage = result?.binarization( threshold: threshold, foregroundColor: foregroundColor, backgroundColor: backgroundColor) { result = tryModeImage } case .none: break } return result } private func getForegroundColor() -> CGColor { switch mode { case .binarization: return CGColor.black()! default: return foregroundColor } } private func getBackgroundColor() -> CGColor { switch mode { case .binarization: return CGColor.white()! default: return backgroundColor } } #if canImport(CoreImage) /// Create Colorful QR Image private func createQRCodeImage( codes: [[Bool]], colorBack: CIColor, colorFront: CIColor, size: EFIntSize) -> CGImage? { guard let colorCGFront = colorFront.cgColor() else { return nil } return createQRCodeImage(codes: codes, colorFront: colorCGFront, size: size) } #endif private func createQRCodeImage( codes: [[Bool]], colorBack colorCGBack: CGColor? = nil, colorFront colorCGFront: CGColor, size: EFIntSize) -> CGImage? { let codeSize = codes.count let scaleX = size.width.cgFloat / CGFloat(codeSize) let scaleY = size.height.cgFloat / CGFloat(codeSize) if scaleX < 1.0 || scaleY < 1.0 { print("Warning: Size too small.") } var points = [CGPoint]() if let locations = getAlignmentPatternLocations(version: getVersion(size: codeSize - 2)) { for indexX in locations { for indexY in locations { let finalX = indexX + 1 let finalY = indexY + 1 if !((finalX == 7 && finalY == 7) || (finalX == 7 && finalY == (codeSize - 8)) || (finalX == (codeSize - 8) && finalY == 7)) { points.append(CGPoint(x: finalX, y: finalY)) } } } } var result: CGImage? if let context = createContext(size: size) { // Point context.setFillColor(colorCGFront) for indexY in 0 ..< codeSize { for indexX in 0 ..< codeSize where codes[indexX][indexY] { // CTM-90 let indexXCTM = indexY let indexYCTM = codeSize - indexX - 1 let isStaticPoint = isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) drawPoint( context: context, rect: CGRect( x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset, y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset, width: scaleX - 2 * foregroundPointOffset, height: scaleY - 2 * foregroundPointOffset ), isStatic: isStaticPoint ) } } result = context.makeImage() } return result } #if canImport(CoreImage) /// Create Colorful QR Image private func createQRCodeImageTransparent( codes: [[Bool]], colorBack: CIColor, colorFront: CIColor, size: EFIntSize) -> CGImage? { guard let colorCGBack = colorBack.cgColor(), let colorCGFront = colorFront.cgColor() else { return nil } return createQRCodeImageTransparent(codes: codes, colorBack: colorCGBack, colorFront: colorCGFront, size: size) } #endif private func createQRCodeImageTransparent( codes: [[Bool]], colorBack colorCGBack: CGColor, colorFront colorCGFront: CGColor, size: EFIntSize) -> CGImage? { let codeSize = codes.count let scaleX = size.width.cgFloat / CGFloat(codeSize) let scaleY = size.height.cgFloat / CGFloat(codeSize) if scaleX < 1.0 || scaleY < 1.0 { print("Warning: Size too small.") } let pointMinOffsetX = scaleX / 3 let pointMinOffsetY = scaleY / 3 let pointWidthOriX = scaleX let pointWidthOriY = scaleY let pointWidthMinX = scaleX - 2 * pointMinOffsetX let pointWidthMinY = scaleY - 2 * pointMinOffsetY // Get AlignmentPatternLocations first var points = [CGPoint]() if let locations = getAlignmentPatternLocations(version: getVersion(size: codeSize - 2)) { for indexX in locations { for indexY in locations { let finalX = indexX + 1 let finalY = indexY + 1 if !((finalX == 7 && finalY == 7) || (finalX == 7 && finalY == (codeSize - 8)) || (finalX == (codeSize - 8) && finalY == 7)) { points.append(CGPoint(x: finalX, y: finalY)) } } } } var finalImage: CGImage? if let context = createContext(size: size) { // Back point context.setFillColor(colorCGBack) for indexY in 0 ..< codeSize { for indexX in 0 ..< codeSize where !codes[indexX][indexY] { // CTM-90 let indexXCTM = indexY let indexYCTM = codeSize - indexX - 1 if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) { drawPoint( context: context, rect: CGRect( x: CGFloat(indexXCTM) * scaleX, y: CGFloat(indexYCTM) * scaleY, width: pointWidthOriX, height: pointWidthOriY ), isStatic: true ) } else { drawPoint( context: context, rect: CGRect( x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX, y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY, width: pointWidthMinX, height: pointWidthMinY ) ) } } } // Front point context.setFillColor(colorCGFront) for indexY in 0 ..< codeSize { for indexX in 0 ..< codeSize where codes[indexX][indexY] { // CTM-90 let indexXCTM = indexY let indexYCTM = codeSize - indexX - 1 if isStatic(x: indexX, y: indexY, size: codeSize, APLPoints: points) { drawPoint( context: context, rect: CGRect( x: CGFloat(indexXCTM) * scaleX + foregroundPointOffset, y: CGFloat(indexYCTM) * scaleY + foregroundPointOffset, width: pointWidthOriX - 2 * foregroundPointOffset, height: pointWidthOriY - 2 * foregroundPointOffset ), isStatic: true ) } else { drawPoint( context: context, rect: CGRect( x: CGFloat(indexXCTM) * scaleX + pointMinOffsetX, y: CGFloat(indexYCTM) * scaleY + pointMinOffsetY, width: pointWidthMinX, height: pointWidthMinY ) ) } } } finalImage = context.makeImage() } return finalImage } // MARK: - Pre #if canImport(CoreImage) private func drawWatermarkImage( context: CGContext, image: CGImage, colorBack: CIColor, mode: EFWatermarkMode, size: CGSize) { drawWatermarkImage(context: context, image: image, colorBack: colorBack.cgColor(), mode: mode, size: size) } #endif private func drawWatermarkImage( context: CGContext, image: CGImage, colorBack: CGColor?, mode: EFWatermarkMode, size: CGSize) { // BGColor if let tryColor = colorBack { context.setFillColor(tryColor) context.fill(CGRect(origin: .zero, size: size)) } if allowTransparent { guard let codes = generateCodes() else { return } if let tryCGImage = createQRCodeImage( codes: codes, colorBack: getBackgroundColor(), colorFront: getForegroundColor(), size: minSuitableSize ) { context.draw(tryCGImage, in: CGRect(origin: .zero, size: size)) } } // Image var finalSize = size var finalOrigin = CGPoint.zero let imageSize = CGSize(width: image.width, height: image.height) switch mode { case .bottom: finalSize = imageSize finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: 0) case .bottomLeft: finalSize = imageSize finalOrigin = .zero case .bottomRight: finalSize = imageSize finalOrigin = CGPoint(x: size.width - imageSize.width, y: 0) case .center: finalSize = imageSize finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: (size.height - imageSize.height) / 2.0) case .left: finalSize = imageSize finalOrigin = CGPoint(x: 0, y: (size.height - imageSize.height) / 2.0) case .right: finalSize = imageSize finalOrigin = CGPoint(x: size.width - imageSize.width, y: (size.height - imageSize.height) / 2.0) case .top: finalSize = imageSize finalOrigin = CGPoint(x: (size.width - imageSize.width) / 2.0, y: size.height - imageSize.height) case .topLeft: finalSize = imageSize finalOrigin = CGPoint(x: 0, y: size.height - imageSize.height) case .topRight: finalSize = imageSize finalOrigin = CGPoint(x: size.width - imageSize.width, y: size.height - imageSize.height) case .scaleAspectFill: let scale = max(size.width / imageSize.width, size.height / imageSize.height) finalSize = CGSize(width: imageSize.width * scale, height: imageSize.height * scale) finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0) case .scaleAspectFit: let scale = max(imageSize.width / size.width, imageSize.height / size.height) finalSize = CGSize(width: imageSize.width / scale, height: imageSize.height / scale) finalOrigin = CGPoint(x: (size.width - finalSize.width) / 2.0, y: (size.height - finalSize.height) / 2.0) case .scaleToFill: break } context.draw(image, in: CGRect(origin: finalOrigin, size: finalSize)) } private func drawIcon(context: CGContext, icon: CGImage, size: EFIntSize) { context.draw( icon, in: CGRect( origin: CGPoint( x: CGFloat(context.width - size.width) / 2.0, y: CGFloat(context.height - size.height) / 2.0 ), size: size.cgSize ) ) } private func fillDiamond(context: CGContext, rect: CGRect) { // shrink rect edge let drawingRect = rect.insetBy(dx: -2, dy: -2) // create path let path = CGMutablePath() // Bezier Control Point let controlPoint = CGPoint(x: drawingRect.midX , y: drawingRect.midY) // Bezier Start Point let startPoint = CGPoint(x: drawingRect.minX, y: drawingRect.midY) // the other point of diamond let otherPoints = [CGPoint(x: drawingRect.midX, y: drawingRect.maxY), CGPoint(x: drawingRect.maxX, y: drawingRect.midY), CGPoint(x: drawingRect.midX, y: drawingRect.minY)] path.move(to: startPoint) for point in otherPoints { path.addQuadCurve(to: point, control: controlPoint) } path.addQuadCurve(to: startPoint, control: controlPoint) context.addPath(path) context.fillPath() } private func drawPoint(context: CGContext, rect: CGRect, isStatic: Bool = false) { switch pointShape { case .circle: context.fillEllipse(in: rect) case .diamond: if isStatic { context.fill(rect) } else { fillDiamond(context: context, rect: rect) } case .square: context.fill(rect) } } private func createContext(size: EFIntSize) -> CGContext? { return CGContext( data: nil, width: size.width, height: size.height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue ) } // MARK: - Data #if canImport(CoreImage) private func getPixels() -> [[EFUIntPixel]]? { guard let finalContent = content else { return nil } let finalInputCorrectionLevel = inputCorrectionLevel let finalContentEncoding = contentEncoding guard let tryQRImagePixels = CIImage .generateQRCode(finalContent, using: finalContentEncoding, inputCorrectionLevel: finalInputCorrectionLevel)? .cgImage()?.pixels() else { print("Warning: Content too large.") return nil } return tryQRImagePixels } #endif // Get QRCodes from pixels private func getCodes(pixels: [[EFUIntPixel]]) -> [[Bool]] { let codes: [[Bool]] = pixels.indices.map { indexY in pixels[0].indices.map { indexX in let pixel = pixels[indexY][indexX] return pixel.red == 0 && pixel.green == 0 && pixel.blue == 0 } } return codes } // Get QRCodes from pixels private func generateCodes() -> [[Bool]]? { if let tryImageCodes = imageCodes { return tryImageCodes } func fetchPixels() -> [[Bool]]? { #if canImport(CoreImage) // Get pixels from image guard let tryQRImagePixels = getPixels() else { return nil } // Get QRCodes from image return getCodes(pixels: tryQRImagePixels) #else let level = inputCorrectionLevel.qrErrorCorrectLevel return content.flatMap { return QRCode($0, errorCorrectLevel: level, withBorder: true)?.imageCodes } #endif } imageCodes = fetchPixels() return imageCodes } // Special Points of QRCode private func isStatic(x: Int, y: Int, size: Int, APLPoints: [CGPoint]) -> Bool { // Empty border if x == 0 || y == 0 || x == (size - 1) || y == (size - 1) { return true } // Finder Patterns if (x <= 8 && y <= 8) || (x <= 8 && y >= (size - 9)) || (x >= (size - 9) && y <= 8) { return true } if !ignoreTiming { // Timing Patterns if x == 7 || y == 7 { return true } } // Alignment Patterns return APLPoints.contains { point in x >= Int(point.x - 2) && x <= Int(point.x + 2) && y >= Int(point.y - 2) && y <= Int(point.y + 2) } } // Alignment Pattern Locations // http://stackoverflow.com/questions/13238704/calculating-the-position-of-qr-code-alignment-patterns private func getAlignmentPatternLocations(version: Int) -> [Int]? { if version == 1 { return nil } let divs = 2 + version / 7 let size = getSize(version: version) let total_dist = size - 7 - 6 let divisor = 2 * (divs - 1) // Step must be even, for alignment patterns to agree with timing patterns let step = (total_dist + divisor / 2 + 1) / divisor * 2 // Get the rounding right var coords = [6] // divs-2 down to 0, inclusive coords += ( 0...(divs - 2) ).lazy.map { i in size - 7 - (divs - 2 - i) * step } return coords } // QRCode version private func getVersion(size: Int) -> Int { return (size - 21) / 4 + 1 } // QRCode size private func getSize(version: Int) -> Int { return 17 + 4 * version } /// Recommand magnification public func minMagnificationGreaterThanOrEqualTo(size: CGFloat) -> Int? { guard let codes = generateCodes() else { return nil } let finalWatermark = watermark let baseMagnification = max(1, Int(size / CGFloat(codes.count))) for offset in 0 ... 3 { let tempMagnification = baseMagnification + offset if CGFloat(Int(tempMagnification) * codes.count) >= size { if finalWatermark == nil { return tempMagnification } else if tempMagnification % 3 == 0 { return tempMagnification } } } return nil } public func maxMagnificationLessThanOrEqualTo(size: CGFloat) -> Int? { guard let codes = generateCodes() else { return nil } let finalWatermark = watermark let baseMagnification = max(1, Int(size / CGFloat(codes.count))) for offset in [0, -1, -2, -3] { let tempMagnification = baseMagnification + offset if tempMagnification <= 0 { return finalWatermark == nil ? 1 : 3 } if CGFloat(tempMagnification * codes.count) <= size { if finalWatermark == nil { return tempMagnification } else if tempMagnification % 3 == 0 { return tempMagnification } } } return nil } // Calculate suitable size private func minSuitableSizeGreaterThanOrEqualTo(size: CGFloat) -> Int? { guard let codes = generateCodes() else { return nil } let baseSuitableSize = Int(size) for offset in codes.indices { let tempSuitableSize = baseSuitableSize + offset if tempSuitableSize % codes.count == 0 { return tempSuitableSize } } return nil } }
6d63590f74e84be70b6d9a0938b460cc
33.543478
120
0.534365
false
false
false
false
kickstarter/ios-ksapi
refs/heads/master
KsApi/models/lenses/BackingLenses.swift
apache-2.0
1
import Prelude extension Backing { public enum lens { public static let amount = Lens<Backing, Int>( view: { $0.amount }, set: { Backing(amount: $0, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let backer = Lens<Backing, User?>( view: { $0.backer }, set: { Backing(amount: $1.amount, backer: $0, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let backerId = Lens<Backing, Int>( view: { $0.backerId }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $0, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let id = Lens<Backing, Int>( view: { $0.id }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $0, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let locationId = Lens<Backing, Int?>( view: { $0.locationId }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $0, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let pledgedAt = Lens<Backing, TimeInterval>( view: { $0.pledgedAt }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $0, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let projectCountry = Lens<Backing, String>( view: { $0.projectCountry }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $0, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let projectId = Lens<Backing, Int>( view: { $0.projectId }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $0, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let reward = Lens<Backing, Reward?>( view: { $0.reward }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $0, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let rewardId = Lens<Backing, Int?>( view: { $0.rewardId }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $0, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let sequence = Lens<Backing, Int>( view: { $0.sequence }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $0, shippingAmount: $1.shippingAmount, status: $1.status) } ) public static let shippingAmount = Lens<Backing, Int?>( view: { $0.shippingAmount }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $0, status: $1.status) } ) public static let status = Lens<Backing, Status>( view: { $0.status }, set: { Backing(amount: $1.amount, backer: $1.backer, backerId: $1.backerId, id: $1.id, locationId: $1.locationId, pledgedAt: $1.pledgedAt, projectCountry: $1.projectCountry, projectId: $1.projectId, reward: $1.reward, rewardId: $1.rewardId, sequence: $1.sequence, shippingAmount: $1.shippingAmount, status: $0) } ) } }
f02dafe08b5cae8e42f8bcc94e2501e4
51.091743
110
0.645474
false
false
false
false
thatseeyou/iOSSDKExamples
refs/heads/master
Pages/UITextChcker.xcplaygroundpage/Contents.swift
mit
1
/*: # UITextChecker 다음과 같은 기능을 제공 * 오타찾기 * 자동완성 * 단어등록 */ import Foundation import UIKit UITextChecker.availableLanguages() /*: ### 오타찾기 : rangeOfMisspelledWordInString */ func ex1() { let textChecker = UITextChecker() let document = "I loev you" let language = "en_US" print("\(document.characters.count)") let rangeOfMisspelled = textChecker.rangeOfMisspelledWordInString(document, range: NSMakeRange(0, document.characters.count), startingAt: 0, wrap: false, language: language) if rangeOfMisspelled.location == NSNotFound { print("Not Found") } else { print(rangeOfMisspelled) textChecker.guessesForWordRange(rangeOfMisspelled, inString: document, language: language) } } /*: ### 자동완성 : completionsForPartialWordRange */ func ex2() { let textChecker = UITextChecker() let document = "lov" let language = "en_US" let completions = textChecker.completionsForPartialWordRange(NSMakeRange(0, document.characters.count), inString: document, language: language) if let completions = completions as? [String] { print(completions) } else { print("No completions") } } ex1() ex2()
5b2899be2c8823952947b15724a499e7
20
177
0.684211
false
false
false
false
Bouke/HAP
refs/heads/master
Sources/HAP/Base/Predefined/Services/Service.Fan.swift
mit
1
import Foundation extension Service { open class Fan: Service { public init(characteristics: [AnyCharacteristic] = []) { var unwrapped = characteristics.map { $0.wrapped } powerState = getOrCreateAppend( type: .powerState, characteristics: &unwrapped, generator: { PredefinedCharacteristic.powerState() }) name = get(type: .name, characteristics: unwrapped) rotationDirection = get(type: .rotationDirection, characteristics: unwrapped) rotationSpeed = get(type: .rotationSpeed, characteristics: unwrapped) super.init(type: .fan, characteristics: unwrapped) } // MARK: - Required Characteristics public let powerState: GenericCharacteristic<Bool> // MARK: - Optional Characteristics public let name: GenericCharacteristic<String>? public let rotationDirection: GenericCharacteristic<Enums.RotationDirection>? public let rotationSpeed: GenericCharacteristic<Float>? } }
e59087d99dd2eec5f536a2e8736f288e
41.52
89
0.65381
false
false
false
false
blockchain/My-Wallet-V3-iOS
refs/heads/master
Modules/FeatureAuthentication/Sources/FeatureAuthenticationUI/EmailLogin/Credentials/WalletPairingReducer.swift
lgpl-3.0
1
// Copyright © Blockchain Luxembourg S.A. All rights reserved. import ComposableArchitecture import DIKit import FeatureAuthenticationDomain import ToolKit // MARK: - Type public enum WalletPairingAction: Equatable { case approveEmailAuthorization case authenticate(String, autoTrigger: Bool = false) case authenticateDidFail(LoginServiceError) case authenticateWithTwoFactorOTP(String) case authenticateWithTwoFactorOTPDidFail(LoginServiceError) case decryptWalletWithPassword(String) case didResendSMSCode(Result<EmptyValue, SMSServiceError>) case didSetupSessionToken(Result<EmptyValue, SessionTokenServiceError>) case handleSMS case needsEmailAuthorization case pollWalletIdentifier case resendSMSCode case setupSessionToken case startPolling case twoFactorOTPDidVerified case none } enum WalletPairingCancelations { struct WalletIdentifierPollingTimerId: Hashable {} struct WalletIdentifierPollingId: Hashable {} } // MARK: - Properties struct WalletPairingState: Equatable { var emailAddress: String var emailCode: String? var walletGuid: String var password: String init( emailAddress: String = "", emailCode: String? = nil, walletGuid: String = "", password: String = "" ) { self.emailAddress = emailAddress self.emailCode = emailCode self.walletGuid = walletGuid self.password = password } } struct WalletPairingEnvironment { let mainQueue: AnySchedulerOf<DispatchQueue> let pollingQueue: AnySchedulerOf<DispatchQueue> let sessionTokenService: SessionTokenServiceAPI let deviceVerificationService: DeviceVerificationServiceAPI let emailAuthorizationService: EmailAuthorizationServiceAPI let smsService: SMSServiceAPI let loginService: LoginServiceAPI let errorRecorder: ErrorRecording init( mainQueue: AnySchedulerOf<DispatchQueue>, pollingQueue: AnySchedulerOf<DispatchQueue>, sessionTokenService: SessionTokenServiceAPI, deviceVerificationService: DeviceVerificationServiceAPI, emailAuthorizationService: EmailAuthorizationServiceAPI, smsService: SMSServiceAPI, loginService: LoginServiceAPI, errorRecorder: ErrorRecording ) { self.mainQueue = mainQueue self.pollingQueue = pollingQueue self.sessionTokenService = sessionTokenService self.deviceVerificationService = deviceVerificationService self.emailAuthorizationService = emailAuthorizationService self.smsService = smsService self.loginService = loginService self.errorRecorder = errorRecorder } } let walletPairingReducer = Reducer< WalletPairingState, WalletPairingAction, WalletPairingEnvironment > { state, action, environment in switch action { case .approveEmailAuthorization: return approveEmailAuthorization(state, environment) case .authenticate(let password, let autoTrigger): // credentials reducer will set password here state.password = password return authenticate(password, state, environment, isAutoTrigger: autoTrigger) case .authenticateWithTwoFactorOTP(let code): return authenticateWithTwoFactorOTP(code, state, environment) case .needsEmailAuthorization: return needsEmailAuthorization() case .pollWalletIdentifier: return pollWalletIdentifier(state, environment) case .resendSMSCode: return resendSMSCode(environment) case .setupSessionToken: return setupSessionToken(environment) case .startPolling: return startPolling(environment) case .authenticateDidFail, .authenticateWithTwoFactorOTPDidFail, .decryptWalletWithPassword, .didResendSMSCode, .didSetupSessionToken, .handleSMS, .twoFactorOTPDidVerified, .none: // handled in credentials reducer return .none } } // MARK: - Private Methods private func approveEmailAuthorization( _ state: WalletPairingState, _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { guard let emailCode = state.emailCode else { // we still need to display an alert and poll here, // since we might end up here in case of a deeplink failure return Effect(value: .needsEmailAuthorization) } return environment .deviceVerificationService .authorizeLogin(emailCode: emailCode) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> WalletPairingAction in if case .failure(let error) = result { // If failed, an `Authorize Log In` will be sent to user for manual authorization environment.errorRecorder.error(error) // we only want to handle `.expiredEmailCode` case, silent other errors... switch error { case .expiredEmailCode: return .needsEmailAuthorization case .missingSessionToken, .networkError, .recaptchaError, .missingWalletInfo: break } } return .startPolling } } private func authenticate( _ password: String, _ state: WalletPairingState, _ environment: WalletPairingEnvironment, isAutoTrigger: Bool ) -> Effect<WalletPairingAction, Never> { guard !state.walletGuid.isEmpty else { fatalError("GUID should not be empty") } return .concatenate( .cancel(id: WalletPairingCancelations.WalletIdentifierPollingTimerId()), environment .loginService .login(walletIdentifier: state.walletGuid) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> WalletPairingAction in switch result { case .success: if isAutoTrigger { // edge case handling: if auto triggered, we don't want to decrypt wallet return .none } return .decryptWalletWithPassword(password) case .failure(let error): return .authenticateDidFail(error) } } ) } private func authenticateWithTwoFactorOTP( _ code: String, _ state: WalletPairingState, _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { guard !state.walletGuid.isEmpty else { fatalError("GUID should not be empty") } return environment .loginService .login( walletIdentifier: state.walletGuid, code: code ) .receive(on: environment.mainQueue) .catchToEffect() .map { result -> WalletPairingAction in switch result { case .success: return .twoFactorOTPDidVerified case .failure(let error): return .authenticateWithTwoFactorOTPDidFail(error) } } } private func needsEmailAuthorization() -> Effect<WalletPairingAction, Never> { Effect(value: .startPolling) } private func pollWalletIdentifier( _ state: WalletPairingState, _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { .concatenate( .cancel(id: WalletPairingCancelations.WalletIdentifierPollingId()), environment .emailAuthorizationService .authorizeEmailPublisher() .receive(on: environment.mainQueue) .catchToEffect() .cancellable(id: WalletPairingCancelations.WalletIdentifierPollingId()) .map { result -> WalletPairingAction in // Authenticate if the wallet identifier exists in repo guard case .success = result else { return .none } return .authenticate(state.password) } ) } private func resendSMSCode( _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { environment .smsService .request() .receive(on: environment.mainQueue) .catchToEffect() .map { result -> WalletPairingAction in switch result { case .success: return .didResendSMSCode(.success(.noValue)) case .failure(let error): return .didResendSMSCode(.failure(error)) } } } private func setupSessionToken( _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { environment .sessionTokenService .setupSessionToken() .receive(on: environment.mainQueue) .catchToEffect() .map { result -> WalletPairingAction in switch result { case .success: return .didSetupSessionToken(.success(.noValue)) case .failure(let error): return .didSetupSessionToken(.failure(error)) } } } private func startPolling( _ environment: WalletPairingEnvironment ) -> Effect<WalletPairingAction, Never> { // Poll the Guid every 2 seconds Effect .timer( id: WalletPairingCancelations.WalletIdentifierPollingTimerId(), every: 2, on: environment.pollingQueue ) .map { _ in .pollWalletIdentifier } .receive(on: environment.mainQueue) .eraseToEffect() }
ca82ed59867643e848182e09f20cd23c
31.261745
97
0.652798
false
false
false
false
UIKonf/uikonf-app
refs/heads/master
UIKonfApp/UIKonfApp/AppDelegate.swift
mit
1
// // AppDelegate.swift // UIKonfApp // // Created by Maxim Zaks on 14.02.15. // Copyright (c) 2015 Maxim Zaks. All rights reserved. // import UIKit import Entitas @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate { var window: UIWindow? let context = Context() func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { let font = UIFont(name: "BauOT", size: 14)! let fontKey : NSString = NSFontAttributeName let attributes : [NSObject : AnyObject] = [fontKey : font] UIBarButtonItem.appearance().setTitleTextAttributes(attributes, forState:UIControlState.Normal) if NSUserDefaults.standardUserDefaults().stringForKey("uuid") == nil { NSUserDefaults.standardUserDefaults().setObject(NSUUID().UUIDString, forKey: "uuid") } return true } func applicationWillResignActive(application: UIApplication) { } func applicationDidEnterBackground(application: UIApplication) { let ratings = ratingsDict(context) if ratings.count > 0 { NSUserDefaults.standardUserDefaults().setObject(ratings, forKey: "ratings") } } func applicationWillEnterForeground(application: UIApplication) { } func applicationDidBecomeActive(application: UIApplication) { syncData(context) } func applicationWillTerminate(application: UIApplication) { } }
b61a748c007dec7a01c35615c4e09c3f
26.890909
127
0.676662
false
false
false
false
kamawshuang/iOS---Animation
refs/heads/master
Autolayerout动画(十)/结合Autolayerot 与 Animation/PackingList/HorizontalItemList.swift
apache-2.0
1
/* * Copyright (c) 2015 Razeware 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 // // A scroll view, which loads all 10 images, and has a callback // for when the user taps on one of the images // class HorizontalItemList: UIScrollView { var didSelectItem: ((index: Int)->())? let buttonWidth: CGFloat = 60.0 let padding: CGFloat = 10.0 required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } override init(frame: CGRect) { super.init(frame: frame) } convenience init(inView: UIView) { let rect = CGRect(x: inView.bounds.width, y: 120.0, width: inView.frame.width, height: 80.0) self.init(frame: rect) self.alpha = 0.0 for var i = 0; i < 10; i++ { let image = UIImage(named: "summericons_100px_0\(i).png") let imageView = UIImageView(image: image) imageView.center = CGPoint(x: CGFloat(i) * buttonWidth + buttonWidth/2, y: buttonWidth/2) imageView.tag = i imageView.userInteractionEnabled = true addSubview(imageView) let tap = UITapGestureRecognizer(target: self, action: Selector("didTapImage:")) imageView.addGestureRecognizer(tap) } contentSize = CGSize(width: padding * buttonWidth, height: buttonWidth + 2*padding) } func didTapImage(tap: UITapGestureRecognizer) { didSelectItem?(index: tap.view!.tag) } override func didMoveToSuperview() { super.didMoveToSuperview() if superview == nil { return } UIView.animateWithDuration(1.0, delay: 0.01, usingSpringWithDamping: 0.5, initialSpringVelocity: 10.0, options: .CurveEaseIn, animations: { self.alpha = 1.0 self.center.x -= self.frame.size.width }, completion: nil) } }
734a796a19c5fc899538e1b552aaaf18
33.592593
143
0.701892
false
false
false
false
NobodyNada/FireAlarm
refs/heads/master
Sources/Frontend/Commands/Filters/CommandCheckThreshold.swift
mit
3
// // CommandCheckThreshold.swift // FireAlarm // // Created by NobodyNada on 2/9/17. // // import Foundation import SwiftChatSE class CommandCheckThreshold: Command { override class func usage() -> [String] { return ["threshold", "check threshold", "get threshold", "current threshold", "thresholds","check thresholds","get thresholds","current thresholds" ] } override func run() throws { if message.room.thresholds.isEmpty { reply("This room does not report any posts.") } else if message.room.thresholds.count == 1 { let threshold = message.room.thresholds.first!.value reply( "The threshold for this room is \(threshold) (*higher* thresholds report more posts)." ) } else { let siteNames: [String] = try message.room.thresholds.keys.map { try Site.with(id: $0, db: reporter.staticDB)?.domain ?? "<unknown site \($0)>" } let siteThresholds = Array(message.room.thresholds.values.map(String.init)) reply("The thresholds for this room are: (*higher* thresholds report more posts)") post(makeTable(["Site", "Threshold"], contents: siteNames, siteThresholds)) } } }
14c3c038a1cd934ef40bf4c0e355c59b
34.378378
102
0.597403
false
false
false
false
mumbler/PReVo-iOS
refs/heads/trunk
ReVoModeloj/Komunaj/Modeloj/Fako.swift
mit
1
// // Fako.swift // PoshReVo // // Created by Robin Hill on 5/4/20. // Copyright © 2020 Robin Hill. All rights reserved. // import Foundation /* Reprezentas fakon al kiu apartenas vorto aŭ frazaĵo. Uzataj en kelkaj difinoj. */ public struct Fako { public let kodo: String public let nomo: String public init(kodo: String, nomo: String) { self.kodo = kodo self.nomo = nomo } } // MARK: - Equatable extension Fako: Equatable { public static func ==(lhs: Fako, rhs: Fako) -> Bool { return lhs.kodo == rhs.kodo && lhs.nomo == rhs.nomo } } // MARK: - Comparable extension Fako: Comparable { public static func < (lhs: Fako, rhs: Fako) -> Bool { return lhs.nomo.compare(rhs.nomo, options: .caseInsensitive, range: nil, locale: Locale(identifier: "eo")) == .orderedAscending } }
e1863e124131f4c2743eb9aa11386f4a
21.526316
135
0.630841
false
false
false
false
rudkx/swift
refs/heads/main
test/Concurrency/actor_inout_isolation.swift
apache-2.0
1
// RUN: %target-typecheck-verify-swift -disable-availability-checking // REQUIRES: concurrency // Verify that we don't allow actor-isolated state to be passed via inout // Check: // - can't pass it into a normal async function // - can't pass it into a first-class async function as a value // - can't pass it into another actor method // - can't pass it into a curried/partially applied function // - can't pass it inout to a function that doesn't directly touch it // - can't pass it into a function that was passed into the calling method // - can't call async mutating function on actor isolated state struct Point { var x: Int var y: Int var z: Int? = nil mutating func setComponents(x: inout Int, y: inout Int) async { defer { (x, y) = (self.x, self.y) } (self.x, self.y) = (x, y) } } @available(SwiftStdlib 5.1, *) actor TestActor { // expected-note@+1{{mutation of this property is only permitted within the actor}} var position = Point(x: 0, y: 0) var nextPosition = Point(x: 0, y: 1) var value1: Int = 0 var value2: Int = 1 var points: [Point] = [] subscript(x : inout Int) -> Int { // expected-error {{'inout' must not be used on subscript parameters}} x += 1 return x } } @available(SwiftStdlib 5.1, *) func modifyAsynchronously(_ foo: inout Int) async { foo += 1 } @available(SwiftStdlib 5.1, *) enum Container { static let modifyAsyncValue = modifyAsynchronously } // external function call @available(SwiftStdlib 5.1, *) extension TestActor { // Can't pass actor-isolated primitive into a function func inoutAsyncFunctionCall() async { // expected-error@+1{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&value1) } func inoutAsyncClosureCall() async { // expected-error@+1{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} await { (_ foo: inout Int) async in foo += 1 }(&value1) } // Can't pass actor-isolated primitive into first-class function value func inoutAsyncValueCall() async { // expected-error@+1{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} await Container.modifyAsyncValue(&value1) } // Can't pass property of actor-isolated state inout to async function func inoutPropertyStateValueCall() async { // expected-error@+1{{actor-isolated property 'position' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&position.x) } func nestedExprs() async { // expected-error@+1{{actor-isolated property 'position' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&position.z!) // expected-error@+1{{actor-isolated property 'points' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&points[0].z!) } } // internal method call @available(SwiftStdlib 5.1, *) extension TestActor { func modifyByValue(_ other: inout Int) async { other += value1 } func passStateIntoMethod() async { // expected-error@+1{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} await modifyByValue(&value1) } } // external class method call @available(SwiftStdlib 5.1, *) class NonAsyncClass { func modifyOtherAsync(_ other : inout Int) async { // ... } func modifyOtherNotAsync(_ other: inout Int) { // ... } } // Calling external class/struct async function @available(SwiftStdlib 5.1, *) extension TestActor { // Can't pass state into async method of another class func passStateIntoDifferentClassMethod() async { let other = NonAsyncClass() let otherCurry = other.modifyOtherAsync // expected-error@+1{{actor-isolated property 'value2' cannot be passed 'inout' to 'async' function call}} await other.modifyOtherAsync(&value2) // expected-error@+1{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} await otherCurry(&value1) other.modifyOtherNotAsync(&value2) // This is okay since it's not async! } func callMutatingFunctionOnStruct() async { // expected-error@+3:20{{cannot call mutating async function 'setComponents(x:y:)' on actor-isolated property 'position'}} // expected-error@+2:51{{actor-isolated property 'nextPosition' cannot be passed 'inout' to 'async' function call}} // expected-error@+1:71{{actor-isolated property 'nextPosition' cannot be passed 'inout' to 'async' function call}} await position.setComponents(x: &nextPosition.x, y: &nextPosition.y) // expected-error@+3:20{{cannot call mutating async function 'setComponents(x:y:)' on actor-isolated property 'position'}} // expected-error@+2:38{{actor-isolated property 'value1' cannot be passed 'inout' to 'async' function call}} // expected-error@+1:50{{actor-isolated property 'value2' cannot be passed 'inout' to 'async' function call}} await position.setComponents(x: &value1, y: &value2) } } // Check implicit async testing @available(SwiftStdlib 5.1, *) actor DifferentActor { func modify(_ state: inout Int) {} } @available(SwiftStdlib 5.1, *) extension TestActor { func modify(_ state: inout Int) {} // Actor state passed inout to implicitly async function on an actor of the // same type func modifiedByOtherTestActor(_ other: TestActor) async { //expected-error@+1{{actor-isolated property 'value2' cannot be passed 'inout' to implicitly 'async' function call}} await other.modify(&value2) } // Actor state passed inout to an implicitly async function on an actor of a // different type func modifiedByOther(_ other: DifferentActor) async { //expected-error@+1{{actor-isolated property 'value2' cannot be passed 'inout' to implicitly 'async' function call}} await other.modify(&value2) } } @available(SwiftStdlib 5.1, *) actor MyActor { var points: [Point] = [] var int: Int = 0 var maybeInt: Int? var maybePoint: Point? var myActor: TestActor = TestActor() // Checking that various ways of unwrapping emit the right error messages at // the right times and that illegal operations are caught func modifyStuff() async { // expected-error@+1{{actor-isolated property 'points' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&points[0].x) // expected-error@+1{{actor-isolated property 'points' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&points[0].z!) // expected-error@+1{{actor-isolated property 'int' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&int) // expected-error@+1{{actor-isolated property 'maybeInt' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&maybeInt!) // expected-error@+1{{actor-isolated property 'maybePoint' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&maybePoint!.z!) // expected-error@+1{{actor-isolated property 'int' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&(int)) // expected-error@+1{{cannot pass immutable value of type 'Int' as inout argument}} await modifyAsynchronously(&(maybePoint?.z)!) // expected-error@+2{{actor-isolated property 'position' can not be used 'inout' on a non-isolated actor instance}} // expected-error@+1{{actor-isolated property 'myActor' cannot be passed 'inout' to 'async' function call}} await modifyAsynchronously(&myActor.position.x) } } // Verify global actor protection @available(SwiftStdlib 5.1, *) @globalActor struct MyGlobalActor { static let shared = TestActor() } @MyGlobalActor var number: Int = 0 // expected-note@-1{{var declared here}} // expected-note@-2{{var declared here}} // expected-note@-3{{mutation of this var is only permitted within the actor}} // expected-error@+3{{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} // expected-error@+2{{var 'number' isolated to global actor 'MyGlobalActor' can not be used 'inout' from a non-isolated context}} if #available(SwiftStdlib 5.1, *) { let _ = Task.detached { await { (_ foo: inout Int) async in foo += 1 }(&number) } } // attempt to pass global state owned by the global actor to another async function // expected-error@+2{{actor-isolated var 'number' cannot be passed 'inout' to 'async' function call}} @available(SwiftStdlib 5.1, *) @MyGlobalActor func sneaky() async { await modifyAsynchronously(&number) } // It's okay to pass actor state inout to synchronous functions! func globalSyncFunction(_ foo: inout Int) { } @available(SwiftStdlib 5.1, *) @MyGlobalActor func globalActorSyncFunction(_ foo: inout Int) { } @available(SwiftStdlib 5.1, *) @MyGlobalActor func globalActorAsyncOkay() async { globalActorSyncFunction(&number) } @available(SwiftStdlib 5.1, *) @MyGlobalActor func globalActorAsyncOkay2() async { globalSyncFunction(&number) } @available(SwiftStdlib 5.1, *) @MyGlobalActor func globalActorSyncOkay() { globalSyncFunction(&number) } // Gently unwrap things that are fine @available(SwiftStdlib 5.1, *) struct Cat { mutating func meow() async { } } @available(SwiftStdlib 5.1, *) struct Dog { var cat: Cat? mutating func woof() async { // This used to cause the compiler to crash, but should be fine await cat?.meow() } }
df52aee542ba03e264fd202d7b924145
37.346939
129
0.710804
false
false
false
false
RocketChat/Rocket.Chat.iOS
refs/heads/develop
Pods/DifferenceKit/Sources/Extensions/UIKitExtension.swift
mit
1
#if os(iOS) || os(tvOS) import UIKit public extension UITableView { /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - animation: An option to animate the updates. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UITableView. func reload<C>( using stagedChangeset: StagedChangeset<C>, with animation: @autoclosure () -> RowAnimation, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { reload( using: stagedChangeset, deleteSectionsAnimation: animation(), insertSectionsAnimation: animation(), reloadSectionsAnimation: animation(), deleteRowsAnimation: animation(), insertRowsAnimation: animation(), reloadRowsAnimation: animation(), interrupt: interrupt, setData: setData ) } /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - deleteSectionsAnimation: An option to animate the section deletion. /// - insertSectionsAnimation: An option to animate the section insertion. /// - reloadSectionsAnimation: An option to animate the section reload. /// - deleteRowsAnimation: An option to animate the row deletion. /// - insertRowsAnimation: An option to animate the row insertion. /// - reloadRowsAnimation: An option to animate the row reload. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UITableView. func reload<C>( using stagedChangeset: StagedChangeset<C>, deleteSectionsAnimation: @autoclosure () -> RowAnimation, insertSectionsAnimation: @autoclosure () -> RowAnimation, reloadSectionsAnimation: @autoclosure () -> RowAnimation, deleteRowsAnimation: @autoclosure () -> RowAnimation, insertRowsAnimation: @autoclosure () -> RowAnimation, reloadRowsAnimation: @autoclosure () -> RowAnimation, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { if case .none = window, let data = stagedChangeset.last?.data { setData(data) return reloadData() } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) return reloadData() } _performBatchUpdates { setData(changeset.data) if !changeset.sectionDeleted.isEmpty { deleteSections(IndexSet(changeset.sectionDeleted), with: deleteSectionsAnimation()) } if !changeset.sectionInserted.isEmpty { insertSections(IndexSet(changeset.sectionInserted), with: insertSectionsAnimation()) } if !changeset.sectionUpdated.isEmpty { reloadSections(IndexSet(changeset.sectionUpdated), with: reloadSectionsAnimation()) } for (source, target) in changeset.sectionMoved { moveSection(source, toSection: target) } if !changeset.elementDeleted.isEmpty { deleteRows(at: changeset.elementDeleted.map { IndexPath(row: $0.element, section: $0.section) }, with: deleteRowsAnimation()) } if !changeset.elementInserted.isEmpty { insertRows(at: changeset.elementInserted.map { IndexPath(row: $0.element, section: $0.section) }, with: insertRowsAnimation()) } if !changeset.elementUpdated.isEmpty { reloadRows(at: changeset.elementUpdated.map { IndexPath(row: $0.element, section: $0.section) }, with: reloadRowsAnimation()) } for (source, target) in changeset.elementMoved { moveRow(at: IndexPath(row: source.element, section: source.section), to: IndexPath(row: target.element, section: target.section)) } } } } private func _performBatchUpdates(_ updates: () -> Void) { if #available(iOS 11.0, tvOS 11.0, *) { performBatchUpdates(updates) } else { beginUpdates() updates() endUpdates() } } } public extension UICollectionView { /// Applies multiple animated updates in stages using `StagedChangeset`. /// /// - Note: There are combination of changes that crash when applied simultaneously in `performBatchUpdates`. /// Assumes that `StagedChangeset` has a minimum staged changesets to avoid it. /// The data of the data-source needs to be updated synchronously before `performBatchUpdates` in every stages. /// /// - Parameters: /// - stagedChangeset: A staged set of changes. /// - interrupt: A closure that takes an changeset as its argument and returns `true` if the animated /// updates should be stopped and performed reloadData. Default is nil. /// - setData: A closure that takes the collection as a parameter. /// The collection should be set to data-source of UICollectionView. func reload<C>( using stagedChangeset: StagedChangeset<C>, interrupt: ((Changeset<C>) -> Bool)? = nil, setData: (C) -> Void ) { if case .none = window, let data = stagedChangeset.last?.data { setData(data) return reloadData() } for changeset in stagedChangeset { if let interrupt = interrupt, interrupt(changeset), let data = stagedChangeset.last?.data { setData(data) return reloadData() } performBatchUpdates({ setData(changeset.data) if !changeset.sectionDeleted.isEmpty { deleteSections(IndexSet(changeset.sectionDeleted)) } if !changeset.sectionInserted.isEmpty { insertSections(IndexSet(changeset.sectionInserted)) } if !changeset.sectionUpdated.isEmpty { reloadSections(IndexSet(changeset.sectionUpdated)) } for (source, target) in changeset.sectionMoved { moveSection(source, toSection: target) } if !changeset.elementDeleted.isEmpty { deleteItems(at: changeset.elementDeleted.map { IndexPath(item: $0.element, section: $0.section) }) } if !changeset.elementInserted.isEmpty { insertItems(at: changeset.elementInserted.map { IndexPath(item: $0.element, section: $0.section) }) } if !changeset.elementUpdated.isEmpty { reloadItems(at: changeset.elementUpdated.map { IndexPath(item: $0.element, section: $0.section) }) } for (source, target) in changeset.elementMoved { moveItem(at: IndexPath(item: source.element, section: source.section), to: IndexPath(item: target.element, section: target.section)) } }) } } } #endif
4cde7e264bd7bcd8bac8802d6413c95e
44.005155
152
0.599473
false
false
false
false
Swinject/SwinjectMVVMExample
refs/heads/master
ExampleViewModelTests/ImageDetailViewModelSpec.swift
mit
2
// // ImageDetailViewModelSpec.swift // SwinjectMVVMExample // // Created by Yoichi Tagaya on 8/25/15. // Copyright © 2015 Swinject Contributors. All rights reserved. // import Quick import Nimble import ReactiveSwift import Result import ExampleModel @testable import ExampleViewModel class ImageDetailViewModelSpec: QuickSpec { // MARK: Stub class StubNetwork: Networking { func requestJSON(_ url: String, parameters: [String : AnyObject]?) -> SignalProducer<Any, NetworkError> { return SignalProducer.empty } func requestImage(_ url: String) -> SignalProducer<UIImage, NetworkError> { return SignalProducer(value: image1x1).observe(on: QueueScheduler()) } } class ErrorStubNetwork: Networking { func requestJSON(_ url: String, parameters: [String : AnyObject]?) -> SignalProducer<Any, NetworkError> { return SignalProducer.empty } func requestImage(_ url: String) -> SignalProducer<UIImage, NetworkError> { return SignalProducer(error: .InternationalRoamingOff).observe(on: QueueScheduler()) } } // MARK: - Mock class MockExternalAppChannel: ExternalAppChanneling { var passedURL: String? func openURL(_ url: String) { passedURL = url } } // MARK: - Spec override func spec() { var externalAppChannel: MockExternalAppChannel! var viewModel: ImageDetailViewModel! beforeEach { externalAppChannel = MockExternalAppChannel() viewModel = ImageDetailViewModel(network: StubNetwork(), externalAppChannel: externalAppChannel) } describe("Constant values") { it("sets id and username.") { viewModel.update(dummyResponse.images, atIndex: 0) expect(viewModel.id.value) == 10000 expect(viewModel.usernameText.value) == "User0" } it("formats tag and page image size texts.") { viewModel.update(dummyResponse.images, atIndex: 1) expect(viewModel.pageImageSizeText.value) == "1500 x 3000" expect(viewModel.tagText.value) == "x, y" } it("formats count values with a specified locale.") { viewModel.locale = NSLocale(localeIdentifier: "de_DE") as Locale viewModel.update(dummyResponse.images, atIndex: 1) expect(viewModel.viewCountText.value) == "123.456.789" expect(viewModel.downloadCountText.value) == "12.345.678" expect(viewModel.likeCountText.value) == "1.234.567" } } describe("Image") { it("eventually gets an image.") { viewModel.update(dummyResponse.images, atIndex: 0) expect(viewModel.image.value).toEventuallyNot(beNil()) } } describe("Image page") { it("opens the URL of the current image page.") { viewModel.update(dummyResponse.images, atIndex: 1) viewModel.openImagePage() expect(externalAppChannel.passedURL) == "https://somewhere.com/page1/" } } } }
78b4d72fff007fa82c504dd8b7ea8772
35.466667
113
0.599634
false
false
false
false
Ssimboss/Image360
refs/heads/master
Image360/Core/OrientationView.swift
mit
1
// // OrientationView.swift // Image360 // // Copyright © 2017 Andrew Simvolokov. 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 /// ## OrientationView /// The `OrientationView` displays current camera position. internal class OrientationView: UIView { private let lineWidth: CGFloat = 3.0 private let dotSize: CGFloat = 6.0 private var _backgroundColor: UIColor? = nil override open var backgroundColor: UIColor? { set { _backgroundColor = newValue super.backgroundColor = .clear } get { return _backgroundColor } } var orientationAngle: CGFloat = 0 var fieldOfView: CGFloat = CGFloat.pi / 2 open override func draw(_ rect: CGRect) { if let context = UIGraphicsGetCurrentContext() { context.clear(rect) context.beginPath() if let backgroundColor = _backgroundColor { context.setFillColor(backgroundColor.cgColor) context.fillEllipse(in: rect) } if let tintColor = tintColor { context.setFillColor(tintColor.cgColor) context.fillEllipse(in: CGRect(origin: CGPoint(x: rect.midX - dotSize / 2 , y: rect.midY - dotSize / 2), size: CGSize(width: dotSize, height: dotSize) ) ) context.setStrokeColor(tintColor.cgColor) context.setLineCap(.round) context.setLineWidth(lineWidth) let center = CGPoint(x: rect.midX, y: rect.midY) context.addArc(center: center, radius: rect.width / 2 - lineWidth, startAngle: orientationAngle - CGFloat.pi / 2 - fieldOfView / 2, endAngle: orientationAngle - CGFloat.pi / 2 + fieldOfView / 2, clockwise: false) context.addLines(between: [CGPoint(x: center.x - dotSize / 8, y: center.y - dotSize / 4), CGPoint(x: center.x, y: center.y - dotSize / 2), CGPoint(x: center.x + dotSize / 8, y: center.y - dotSize / 4), ]) } context.strokePath() } } } extension OrientationView: Image360ViewObserver { public func image360View(_ view: Image360View, didRotateOverXZ rotationAngleXZ: Float) { orientationAngle = CGFloat(rotationAngleXZ) self.setNeedsDisplay() } public func image360View(_ view: Image360View, didRotateOverY rotationAngleY: Float) { } public func image360View(_ view: Image360View, didChangeFOV cameraFov: Float) { fieldOfView = CGFloat(cameraFov / 180 * Float.pi) self.setNeedsDisplay() } }
b11be622faef1a3cc8c1142302cdf173
40.575758
105
0.589164
false
false
false
false
czechboy0/XcodeServerSDK
refs/heads/master
XcodeServerSDK/Server Entities/Contributor.swift
mit
1
// // Contributor.swift // XcodeServerSDK // // Created by Mateusz Zając on 21/07/15. // Copyright © 2015 Honza Dvorsky. All rights reserved. // import Foundation // MARK: Constants let kContributorName = "XCSContributorName" let kContributorDisplayName = "XCSContributorDisplayName" let kContributorEmails = "XCSContributorEmails" public class Contributor: XcodeServerEntity { public let name: String public let displayName: String public let emails: [String] public required init(json: NSDictionary) throws { self.name = try json.stringForKey(kContributorName) self.displayName = try json.stringForKey(kContributorDisplayName) self.emails = try json.arrayForKey(kContributorEmails) try super.init(json: json) } public override func dictionarify() -> NSDictionary { return [ kContributorName: self.name, kContributorDisplayName: self.displayName, kContributorEmails: self.emails ] } public func description() -> String { return "\(displayName) [\(emails[0])]" } }
28e0d1851033358ebf7ec34a41e2f9fd
26
73
0.669903
false
false
false
false
NewBeeInc/NBFramework
refs/heads/master
Pods/SwiftyJSON/Source/SwiftyJSON.swift
mit
3
// SwiftyJSON.swift // // Copyright (c) 2014 Ruoyu Fu, Pinglin Tang // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import Foundation import CoreFoundation // MARK: - Error ///Error domain public let ErrorDomain: String = "SwiftyJSONErrorDomain" ///Error code public let ErrorUnsupportedType: Int = 999 public let ErrorIndexOutOfBounds: Int = 900 public let ErrorWrongType: Int = 901 public let ErrorNotExist: Int = 500 public let ErrorInvalidJSON: Int = 490 public enum SwiftyJSONError: Error { case empty case errorInvalidJSON(String) } // MARK: - JSON Type /** JSON's type definitions. See http://www.json.org */ public enum Type :Int{ case number case string case bool case array case dictionary case null case unknown } // MARK: - JSON Base public struct JSON { /** Creates a JSON using the data. - parameter data: The Data used to convert to json.Top level object in data is an NSArray or NSDictionary - parameter opt: The JSON serialization reading options. `.AllowFragments` by default. - returns: The created JSON */ public init(data: Data, options opt: JSONSerialization.ReadingOptions = .allowFragments) { do { let object: Any = try JSONSerialization.jsonObject(with: data, options: opt) self.init(object) } catch { // For now do nothing with the error self.init(NSNull() as Any) } } /** Create a JSON from JSON string - parameter string: Normal json string like '{"a":"b"}' - returns: The created JSON */ public static func parse(string:String) -> JSON { return string.data(using: String.Encoding.utf8).flatMap({JSON(data: $0)}) ?? JSON(NSNull()) } /** Creates a JSON using the object. - parameter object: The object must have the following properties: All objects are NSString/String, NSNumber/Int/Float/Double/Bool, NSArray/Array, NSDictionary/Dictionary, or NSNull; All dictionary keys are NSStrings/String; NSNumbers are not NaN or infinity. - returns: The created JSON */ public init(_ object: Any) { self.object = object } /** Creates a JSON from a [JSON] - parameter jsonArray: A Swift array of JSON objects - returns: The created JSON */ public init(_ jsonArray:[JSON]) { self.init(jsonArray.map { $0.object } as Any) } /** Creates a JSON from a [String: JSON] - parameter jsonDictionary: A Swift dictionary of JSON objects - returns: The created JSON */ public init(_ jsonDictionary:[String: JSON]) { var dictionary = [String: Any](minimumCapacity: jsonDictionary.count) for (key, json) in jsonDictionary { dictionary[key] = json.object } self.init(dictionary as Any) } /// Private object var rawString: String = "" var rawNumber: NSNumber = 0 var rawNull: NSNull = NSNull() var rawArray: [Any] = [] var rawDictionary: [String : Any] = [:] var rawBool: Bool = false /// Private type var _type: Type = .null /// prviate error var _error: NSError? = nil /// Object in JSON public var object: Any { get { switch self.type { case .array: return self.rawArray case .dictionary: return self.rawDictionary case .string: return self.rawString case .number: return self.rawNumber case .bool: return self.rawBool default: return self.rawNull } } set { _error = nil #if os(Linux) let (type, value) = self.setObjectHelper(newValue) _type = type switch (type) { case .array: self.rawArray = value as! [Any] case .bool: self.rawBool = value as! Bool if let number = newValue as? NSNumber { self.rawNumber = number } else { self.rawNumber = self.rawBool ? NSNumber(value: 1) : NSNumber(value: 0) } case .dictionary: self.rawDictionary = value as! [String:Any] case .null: break case .number: self.rawNumber = value as! NSNumber case .string: self.rawString = value as! String case .unknown: _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey: "It is a unsupported type"]) print("==> error=\(_error). type=\(type(of: newValue))") } #else if type(of: newValue) == Bool.self { _type = .bool self.rawBool = newValue as! Bool } else { switch newValue { case let number as NSNumber: if number.isBool { _type = .bool self.rawBool = number.boolValue } else { _type = .number self.rawNumber = number } case let string as String: _type = .string self.rawString = string case _ as NSNull: _type = .null case let array as [Any]: _type = .array self.rawArray = array case let dictionary as [String : Any]: _type = .dictionary self.rawDictionary = dictionary default: _type = .unknown _error = NSError(domain: ErrorDomain, code: ErrorUnsupportedType, userInfo: [NSLocalizedDescriptionKey as NSObject: "It is a unsupported type"]) } } #endif } } #if os(Linux) private func setObjectHelper(_ newValue: Any) -> (Type, Any) { var type: Type var value: Any switch newValue { case let bool as Bool: type = .bool value = bool case let number as NSNumber: if number.isBool { type = .bool value = number.boolValue } else { type = .number value = number } case let number as Double: type = .number value = NSNumber(value: number) case let number as Int: type = .number value = NSNumber(value: number) case let string as String: type = .string value = string case let string as NSString: type = .string value = string._bridgeToSwift() case _ as NSNull: type = .null value = "" case let array as NSArray: type = .array value = array._bridgeToSwift().map { $0 as Any } case let dictionary as NSDictionary: type = .dictionary var dict = [String: Any]() dictionary.enumerateKeysAndObjects(using: {(key: Any, val: Any, stop: UnsafeMutablePointer<ObjCBool>) in let keyStr = key as! String dict[keyStr] = val }) value = dict default: let mirror = Mirror(reflecting: newValue) if mirror.displayStyle == .collection { type = .array value = mirror.children.map { $0.value as Any } } else if mirror.displayStyle == .dictionary { let children = mirror.children.map { $0.value } let elems = convertToKeyValues(children) if children.count == elems.count { type = .dictionary var dict = [String: Any]() for (key, val) in elems { dict[key] = val as Any } value = dict } else { type = .unknown value = "" } } else { type = .unknown value = "" } } return (type, value) } private func convertToKeyValues(_ pairs: [Any]) -> [(String, Any)] { var result = [(String, Any)]() for pair in pairs { let pairMirror = Mirror(reflecting: pair) if pairMirror.displayStyle == .tuple && pairMirror.children.count == 2 { let generator = pairMirror.children.makeIterator() if let key = generator.next()!.value as? String { result.append((key, generator.next()!.value)) } else { break } } } return result } #endif /// json type public var type: Type { get { return _type } } /// Error in JSON public var error: NSError? { get { return self._error } } /// The static null json @available(*, unavailable, renamed:"null") public static var nullJSON: JSON { get { return null } } public static var null: JSON { get { return JSON(NSNull() as Any) } } #if os(Linux) internal static func stringFromNumber(_ number: NSNumber) -> String { let type = CFNumberGetType(unsafeBitCast(number, to: CFNumber.self)) switch(type) { case kCFNumberFloat32Type: return String(number.floatValue) case kCFNumberFloat64Type: return String(number.doubleValue) default: return String(number.int64Value) } } #endif } // MARK: - CollectionType, SequenceType extension JSON : Collection, Sequence { public typealias Generator = JSONGenerator public typealias Index = JSONIndex public var startIndex: JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.startIndex) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.startIndex) default: return JSONIndex() } } public var endIndex: JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.endIndex) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.endIndex) default: return JSONIndex() } } public func index(after i: JSON.Index) -> JSON.Index { switch self.type { case .array: return JSONIndex(arrayIndex: self.rawArray.index(after: i.arrayIndex!)) case .dictionary: return JSONIndex(dictionaryIndex: self.rawDictionary.index(after: i.dictionaryIndex!)) default: return JSONIndex() } } public subscript (position: JSON.Index) -> Generator.Element { switch self.type { case .array: return (String(describing: position.arrayIndex), JSON(self.rawArray[position.arrayIndex!])) case .dictionary: let (key, value) = self.rawDictionary[position.dictionaryIndex!] return (key, JSON(value)) default: return ("", JSON.null) } } /// If `type` is `.Array` or `.Dictionary`, return `array.isEmpty` or `dictonary.isEmpty` otherwise return `true`. public var isEmpty: Bool { get { switch self.type { case .array: return self.rawArray.isEmpty case .dictionary: return self.rawDictionary.isEmpty default: return true } } } /// If `type` is `.Array` or `.Dictionary`, return `array.count` or `dictonary.count` otherwise return `0`. public var count: Int { switch self.type { case .array: return self.rawArray.count case .dictionary: return self.rawDictionary.count default: return 0 } } public func underestimateCount() -> Int { switch self.type { case .array: return self.rawArray.underestimatedCount case .dictionary: return self.rawDictionary.underestimatedCount default: return 0 } } /** If `type` is `.Array` or `.Dictionary`, return a generator over the elements like `Array` or `Dictionary`, otherwise return a generator over empty. - returns: Return a *generator* over the elements of JSON. */ public func generate() -> Generator { return JSON.Generator(self) } } public struct JSONIndex: _Incrementable, Equatable, Comparable { let arrayIndex: Array<Any>.Index? let dictionaryIndex: DictionaryIndex<String, Any>? let type: Type init(){ self.arrayIndex = nil self.dictionaryIndex = nil self.type = .unknown } init(arrayIndex: Array<Any>.Index) { self.arrayIndex = arrayIndex self.dictionaryIndex = nil self.type = .array } init(dictionaryIndex: DictionaryIndex<String, Any>) { self.arrayIndex = nil self.dictionaryIndex = dictionaryIndex self.type = .dictionary } } public func ==(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): return lhs.arrayIndex == rhs.arrayIndex case (.dictionary, .dictionary): return lhs.dictionaryIndex == rhs.dictionaryIndex default: return false } } public func <(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func <=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func >=(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public func >(lhs: JSONIndex, rhs: JSONIndex) -> Bool { switch (lhs.type, rhs.type) { case (.array, .array): guard let lhsArrayIndex = lhs.arrayIndex, let rhsArrayIndex = rhs.arrayIndex else { return false } return lhsArrayIndex < rhsArrayIndex case (.dictionary, .dictionary): guard let lhsDictionaryIndex = lhs.dictionaryIndex, let rhsDictionaryIndex = rhs.dictionaryIndex else { return false } return lhsDictionaryIndex < rhsDictionaryIndex default: return false } } public struct JSONGenerator : IteratorProtocol { public typealias Element = (String, JSON) private let type: Type private var dictionayGenerate: DictionaryIterator<String, Any>? private var arrayGenerate: IndexingIterator<[Any]>? private var arrayIndex: Int = 0 init(_ json: JSON) { self.type = json.type if type == .array { self.arrayGenerate = json.rawArray.makeIterator() }else { self.dictionayGenerate = json.rawDictionary.makeIterator() } } public mutating func next() -> JSONGenerator.Element? { switch self.type { case .array: if let o = self.arrayGenerate?.next() { let i = self.arrayIndex self.arrayIndex += 1 return (String(i), JSON(o)) } else { return nil } case .dictionary: guard let (k, v): (String, Any) = self.dictionayGenerate?.next() else { return nil } return (k, JSON(v)) default: return nil } } } // MARK: - Subscript /** * To mark both String and Int can be used in subscript. */ public enum JSONKey { case index(Int) case key(String) } public protocol JSONSubscriptType { var jsonKey:JSONKey { get } } extension Int: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.index(self) } } extension String: JSONSubscriptType { public var jsonKey:JSONKey { return JSONKey.key(self) } } extension JSON { /// If `type` is `.Array`, return json whose object is `array[index]`, otherwise return null json with error. private subscript(index index: Int) -> JSON { get { if self.type != .array { var r = JSON.null r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] failure, It is not an array" as Any]) return r } else if index >= 0 && index < self.rawArray.count { return JSON(self.rawArray[index]) } else { var r = JSON.null #if os(Linux) r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey: "Array[\(index)] is out of bounds" as Any]) #else r._error = NSError(domain: ErrorDomain, code:ErrorIndexOutOfBounds, userInfo: [NSLocalizedDescriptionKey as AnyObject as! NSObject: "Array[\(index)] is out of bounds" as AnyObject]) #endif return r } } set { if self.type == .array { if self.rawArray.count > index && newValue.error == nil { self.rawArray[index] = newValue.object } } } } /// If `type` is `.Dictionary`, return json whose object is `dictionary[key]` , otherwise return null json with error. private subscript(key key: String) -> JSON { get { var r = JSON.null if self.type == .dictionary { if let o = self.rawDictionary[key] { r = JSON(o) } else { #if os(Linux) r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] does not exist" as Any]) #else r._error = NSError(domain: ErrorDomain, code: ErrorNotExist, userInfo: [NSLocalizedDescriptionKey as NSObject: "Dictionary[\"\(key)\"] does not exist" as AnyObject]) #endif } } else { #if os(Linux) r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey: "Dictionary[\"\(key)\"] failure, It is not an dictionary" as Any]) #else r._error = self._error ?? NSError(domain: ErrorDomain, code: ErrorWrongType, userInfo: [NSLocalizedDescriptionKey as NSObject: "Dictionary[\"\(key)\"] failure, It is not an dictionary" as AnyObject]) #endif } return r } set { if self.type == .dictionary && newValue.error == nil { self.rawDictionary[key] = newValue.object } } } /// If `sub` is `Int`, return `subscript(index:)`; If `sub` is `String`, return `subscript(key:)`. private subscript(sub sub: JSONSubscriptType) -> JSON { get { switch sub.jsonKey { case .index(let index): return self[index: index] case .key(let key): return self[key: key] } } set { switch sub.jsonKey { case .index(let index): self[index: index] = newValue case .key(let key): self[key: key] = newValue } } } /** Find a json in the complex data structuresby using the Int/String's array. - parameter path: The target json's path. Example: let json = JSON[data] let path = [9,"list","person","name"] let name = json[path] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: [JSONSubscriptType]) -> JSON { get { return path.reduce(self) { $0[sub: $1] } } set { switch path.count { case 0: self.object = newValue.object case 1: self[sub:path[0]].object = newValue.object default: var aPath = path; aPath.remove(at: 0) var nextJSON = self[sub: path[0]] nextJSON[aPath] = newValue self[sub: path[0]] = nextJSON } } } /** Find a json in the complex data structures by using the Int/String's array. - parameter path: The target json's path. Example: let name = json[9,"list","person","name"] The same as: let name = json[9]["list"]["person"]["name"] - returns: Return a json found by the path or a null json with error */ public subscript(path: JSONSubscriptType...) -> JSON { get { return self[path] } set { self[path] = newValue } } } // MARK: - LiteralConvertible extension JSON: Swift.StringLiteralConvertible { public init(stringLiteral value: StringLiteralType) { self.init(value as Any) } public init(extendedGraphemeClusterLiteral value: StringLiteralType) { self.init(value as Any) } public init(unicodeScalarLiteral value: StringLiteralType) { self.init(value as Any) } } extension JSON: Swift.IntegerLiteralConvertible { public init(integerLiteral value: IntegerLiteralType) { self.init(value as Any) } } extension JSON: Swift.BooleanLiteralConvertible { public init(booleanLiteral value: BooleanLiteralType) { self.init(value as Any) } } extension JSON: Swift.FloatLiteralConvertible { public init(floatLiteral value: FloatLiteralType) { self.init(value as Any) } } extension JSON: Swift.DictionaryLiteralConvertible { public init(dictionaryLiteral elements: (String, Any)...) { self.init(elements.reduce([String : Any](minimumCapacity: elements.count)){(dictionary: [String : Any], element:(String, Any)) -> [String : Any] in var d = dictionary d[element.0] = element.1 return d } as Any) } } extension JSON: Swift.ArrayLiteralConvertible { public init(arrayLiteral elements: Any...) { self.init(elements as Any) } } extension JSON: Swift.NilLiteralConvertible { public init(nilLiteral: ()) { self.init(NSNull() as Any) } } // MARK: - Raw extension JSON: Swift.RawRepresentable { public init?(rawValue: Any) { if JSON(rawValue).type == .unknown { return nil } else { self.init(rawValue) } } public var rawValue: Any { return self.object } #if os(Linux) public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard LclJSONSerialization.isValidJSONObject(self.object) else { throw SwiftyJSONError.errorInvalidJSON("JSON is invalid") } return try LclJSONSerialization.dataWithJSONObject(self.object, options: opt) } #else public func rawData(options opt: JSONSerialization.WritingOptions = JSONSerialization.WritingOptions(rawValue: 0)) throws -> Data { guard JSONSerialization.isValidJSONObject(self.object) else { throw SwiftyJSONError.errorInvalidJSON("JSON is invalid") } return try JSONSerialization.data(withJSONObject: self.object, options: opt) } #endif #if os(Linux) public func rawString(encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: do { let data = try self.rawData(options: opt) return String(data: data, encoding: encoding) } catch _ { return nil } case .string: return self.rawString case .number: return JSON.stringFromNumber(self.rawNumber) case .bool: return self.rawBool.description case .null: return "null" default: return nil } } #else public func rawString(encoding: String.Encoding = String.Encoding.utf8, options opt: JSONSerialization.WritingOptions = .prettyPrinted) -> String? { switch self.type { case .array, .dictionary: do { let data = try self.rawData(options: opt) return String(data: data, encoding: encoding) } catch _ { return nil } case .string: return self.rawString case .number: return self.rawNumber.stringValue case .bool: return self.rawBool.description case .null: return "null" default: return nil } } #endif } // MARK: - Printable, DebugPrintable extension JSON { public var description: String { let prettyString = self.rawString(options:.prettyPrinted) if let string = prettyString { return string } else { return "unknown" } } public var debugDescription: String { return description } } // MARK: - Array extension JSON { //Optional [JSON] public var array: [JSON]? { get { if self.type == .array { return self.rawArray.map{ JSON($0) } } else { return nil } } } //Non-optional [JSON] public var arrayValue: [JSON] { get { return self.array ?? [] } } //Optional [AnyType] public var arrayObject: [Any]? { get { switch self.type { case .array: return self.rawArray default: return nil } } set { if let array = newValue { self.object = array as Any } else { self.object = NSNull() } } } } // MARK: - Dictionary extension JSON { //Optional [String : JSON] public var dictionary: [String : JSON]? { if self.type == .dictionary { return self.rawDictionary.reduce([String : JSON]()) { (dictionary: [String : JSON], element: (String, Any)) -> [String : JSON] in var d = dictionary d[element.0] = JSON(element.1) return d } } else { return nil } } //Non-optional [String : JSON] public var dictionaryValue: [String : JSON] { return self.dictionary ?? [:] } //Optional [String : AnyType] public var dictionaryObject: [String : Any]? { get { switch self.type { case .dictionary: return self.rawDictionary default: return nil } } set { if let v = newValue { self.object = v as Any } else { self.object = NSNull() } } } } // MARK: - Bool extension JSON { //Optional bool public var bool: Bool? { get { switch self.type { case .bool: return self.rawBool default: return nil } } set { if let newValue = newValue { self.object = newValue as Bool } else { self.object = NSNull() } } } //Non-optional bool public var boolValue: Bool { get { switch self.type { case .bool: return self.rawBool case .number: return self.rawNumber.boolValue case .string: return self.rawString.caseInsensitiveCompare("true") == .orderedSame default: return false } } set { self.object = newValue } } } // MARK: - String extension JSON { //Optional string public var string: String? { get { switch self.type { case .string: return self.object as? String default: return nil } } set { if let newValue = newValue { self.object = NSString(string:newValue) } else { self.object = NSNull() } } } //Non-optional string public var stringValue: String { get { #if os(Linux) switch self.type { case .string: return self.object as? String ?? "" case .number: return JSON.stringFromNumber(self.object as! NSNumber) case .bool: return String(self.object as! Bool) default: return "" } #else switch self.type { case .string: return self.object as? String ?? "" case .number: return self.rawNumber.stringValue case .bool: return (self.object as? Bool).map { String($0) } ?? "" default: return "" } #endif } set { self.object = NSString(string:newValue) } } } // MARK: - Number extension JSON { //Optional number public var number: NSNumber? { get { switch self.type { case .number: return self.rawNumber case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return nil } } set { self.object = newValue ?? NSNull() } } //Non-optional number public var numberValue: NSNumber { get { switch self.type { case .string: #if os(Linux) if let decimal = Double(self.object as! String) { return NSNumber(value: decimal) } else { // indicates parse error return NSNumber(value: 0.0) } #else let decimal = NSDecimalNumber(string: self.object as? String) if decimal == NSDecimalNumber.notANumber { // indicates parse error return NSDecimalNumber.zero } return decimal #endif case .number: return self.object as? NSNumber ?? NSNumber(value: 0) case .bool: return NSNumber(value: self.rawBool ? 1 : 0) default: return NSNumber(value: 0.0) } } set { self.object = newValue } } } //MARK: - Null extension JSON { public var null: NSNull? { get { switch self.type { case .null: return self.rawNull default: return nil } } set { self.object = NSNull() } } public func exists() -> Bool{ if let errorValue = error, errorValue.code == ErrorNotExist{ return false } return true } } //MARK: - URL extension JSON { //Optional URL public var URL: NSURL? { get { switch self.type { case .string: guard let encodedString_ = self.rawString.addingPercentEncoding(withAllowedCharacters: CharacterSet.urlQueryAllowed) else { return nil } return NSURL(string: encodedString_) default: return nil } } set { #if os(Linux) self.object = newValue?.absoluteString._bridgeToObjectiveC() #else self.object = newValue?.absoluteString #endif } } } // MARK: - Int, Double, Float, Int8, Int16, Int32, Int64 extension JSON { public var double: Double? { get { return self.number?.doubleValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var doubleValue: Double { get { return self.numberValue.doubleValue } set { self.object = NSNumber(value: newValue) } } public var float: Float? { get { return self.number?.floatValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var floatValue: Float { get { return self.numberValue.floatValue } set { self.object = NSNumber(value: newValue) } } public var int: Int? { get { return self.number?.intValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var intValue: Int { get { return self.numberValue.intValue } set { self.object = NSNumber(value: newValue) } } public var uInt: UInt? { get { return self.number?.uintValue } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uIntValue: UInt { get { return self.numberValue.uintValue } set { self.object = NSNumber(value: newValue) } } public var int8: Int8? { get { return self.number?.int8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int8Value: Int8 { get { return self.numberValue.int8Value } set { self.object = NSNumber(value: newValue) } } public var uInt8: UInt8? { get { return self.number?.uint8Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt8Value: UInt8 { get { return self.numberValue.uint8Value } set { self.object = NSNumber(value: newValue) } } public var int16: Int16? { get { return self.number?.int16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int16Value: Int16 { get { return self.numberValue.int16Value } set { self.object = NSNumber(value: newValue) } } public var uInt16: UInt16? { get { return self.number?.uint16Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt16Value: UInt16 { get { return self.numberValue.uint16Value } set { self.object = NSNumber(value: newValue) } } public var int32: Int32? { get { return self.number?.int32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int32Value: Int32 { get { return self.numberValue.int32Value } set { self.object = NSNumber(value: newValue) } } public var uInt32: UInt32? { get { return self.number?.uint32Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt32Value: UInt32 { get { return self.numberValue.uint32Value } set { self.object = NSNumber(value: newValue) } } public var int64: Int64? { get { return self.number?.int64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var int64Value: Int64 { get { return self.numberValue.int64Value } set { self.object = NSNumber(value: newValue) } } public var uInt64: UInt64? { get { return self.number?.uint64Value } set { if let newValue = newValue { self.object = NSNumber(value: newValue) } else { self.object = NSNull() } } } public var uInt64Value: UInt64 { get { return self.numberValue.uint64Value } set { self.object = NSNumber(value: newValue) } } } //MARK: - Comparable extension JSON : Swift.Comparable {} public func ==(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber == rhs.rawNumber case (.string, .string): return lhs.rawString == rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func <=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber <= rhs.rawNumber case (.string, .string): return lhs.rawString <= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func >=(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber >= rhs.rawNumber case (.string, .string): return lhs.rawString >= rhs.rawString case (.bool, .bool): return lhs.rawBool == rhs.rawBool case (.array, .array): #if os(Linux) return lhs.rawArray._bridgeToObjectiveC() == rhs.rawArray._bridgeToObjectiveC() #else return lhs.rawArray as NSArray == rhs.rawArray as NSArray #endif case (.dictionary, .dictionary): #if os(Linux) return lhs.rawDictionary._bridgeToObjectiveC() == rhs.rawDictionary._bridgeToObjectiveC() #else return lhs.rawDictionary as NSDictionary == rhs.rawDictionary as NSDictionary #endif case (.null, .null): return true default: return false } } public func >(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber > rhs.rawNumber case (.string, .string): return lhs.rawString > rhs.rawString default: return false } } public func <(lhs: JSON, rhs: JSON) -> Bool { switch (lhs.type, rhs.type) { case (.number, .number): return lhs.rawNumber < rhs.rawNumber case (.string, .string): return lhs.rawString < rhs.rawString default: return false } } private let trueNumber = NSNumber(value: true) private let falseNumber = NSNumber(value: false) private let trueObjCType = String(describing: trueNumber.objCType) private let falseObjCType = String(describing: falseNumber.objCType) // MARK: - NSNumber: Comparable extension NSNumber { var isBool:Bool { get { #if os(Linux) let type = CFNumberGetType(unsafeBitCast(self, to: CFNumber.self)) if type == kCFNumberSInt8Type && (self.compare(trueNumber) == ComparisonResult.orderedSame || self.compare(falseNumber) == ComparisonResult.orderedSame){ return true } else { return false } #else let objCType = String(describing: self.objCType) if (self.compare(trueNumber) == ComparisonResult.orderedSame && objCType == trueObjCType) || (self.compare(falseNumber) == ComparisonResult.orderedSame && objCType == falseObjCType){ return true } else { return false } #endif } } } func ==(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedSame } } func !=(lhs: NSNumber, rhs: NSNumber) -> Bool { return !(lhs == rhs) } func <(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedAscending } } func >(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) == ComparisonResult.orderedDescending } } func <=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != ComparisonResult.orderedDescending } } func >=(lhs: NSNumber, rhs: NSNumber) -> Bool { switch (lhs.isBool, rhs.isBool) { case (false, true): return false case (true, false): return false default: return lhs.compare(rhs) != ComparisonResult.orderedAscending } }
7f4972c827af1e9e1275dcd63fee1b61
26.852232
264
0.543277
false
false
false
false
pointfreeco/swift-web
refs/heads/main
Sources/Css/CssSelector.swift
mit
1
import Prelude public enum CssSelector { public enum Attribute { public enum Modifier { case begins case contains case ends case hyphen case space case val } case exists(String) case match(String, Modifier, String) } public enum PseudoElem { case after case before case firstLetter case firstSentence case selection } public enum PseudoClass { case active case checked case disabled case empty case enabled case firstChild case firstOfType case focus case hover case inRange case invalid case lang(String) case lastChild case lastOfType case link case nthChild(Int) case nthLastChild(Int) case nthLastOfType(Int) case nthOfType(Int) case onlyChild case onlyOfType case optional case outOfRange case readOnly case readWrite case required case root case target case valid case visited indirect case not(CssSelector) } public enum Element { case a case abbr case address case article case aside case audio case b case blockquote case body case canvas case caption case cite case code case dd case details case div case dl case dt case em case embed case fieldset case figcaption case figure case footer case form case h1 case h2 case h3 case h4 case h5 case h6 case header case hgroup case html case i case iframe case img case input case label case legend case li case menu case nav case ol case other(String) case p case pre case q case section case span case strong case summary case table case tbody case td case tfoot case th case thead case time case tr case u case ul case video } /// i.e.: * case star /// e.g.: body, a, span, div, ... case elem(Element) /// e.g.: #home, #nav, #sidebar, ... case id(String) /// e.g.: .active, .error, .item, ... case `class`(String) /// e.g.: :first-child, :active, :disabled, ... indirect case pseudo(PseudoClass) /// e.g.: ::before, ::after, ::first-letter, ... case pseudoElem(PseudoElem) /// e.g.: *[class^='col-'], input[type='submit'], ... indirect case attr(CssSelector, Attribute) /// i.e.: sel1 > sel2 indirect case child(CssSelector, CssSelector) /// i.e.: sel1 ~ sel2 indirect case sibling(CssSelector, CssSelector) /// i.e.: sel1 sel2 indirect case deep(CssSelector, CssSelector) /// i.e. sel1 + sel2 indirect case adjacent(CssSelector, CssSelector) /// e.g. input.active#email indirect case combined(CssSelector, CssSelector) /// e.g. sel1, sel2 indirect case union(CssSelector, CssSelector) } extension CssSelector { public subscript(index: Attribute) -> CssSelector { return .attr(self, index) } } extension CssSelector { public subscript(index: String) -> CssSelector { return .attr(self, .exists(index)) } } public func ^=(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .begins, rhs) } public func *=(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .contains, rhs) } public func ==(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .val, rhs) } infix operator ¢= public func ¢=(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .ends, rhs) } public func ~=(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .space, rhs) } public func |=(lhs: String, rhs: String) -> CssSelector.Attribute { return .match(lhs, .hyphen, rhs) } extension CssSelector: ExpressibleByStringLiteral { public init(stringLiteral value: String) { switch value.first { case .some("#"): self = .id(String(value.dropFirst())) case .some("."): self = .`class`(String(value.dropFirst())) default: self = .elem(.other(value)) } } } extension CssSelector: Semigroup { public static func <>(lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .union(lhs, rhs) } } infix operator **: infixr6 public func ** (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .deep(lhs, rhs) } public func > (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .child(lhs, rhs) } public func + (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .adjacent(lhs, rhs) } public func | (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .union(lhs, rhs) } public func & (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .combined(lhs, rhs) } infix operator ~: infixr6 public func ~ (lhs: CssSelector, rhs: CssSelector) -> CssSelector { return .sibling(lhs, rhs) } extension CssSelector { public var idString: String? { switch self { case .star, .elem, .class, .pseudo, .pseudoElem, .attr, .child, .sibling, .deep, .adjacent, .combined, .union: return nil case let .id(id): return id } } }
53b01461da8b74bbeb83eaecd06674dc
19.220472
106
0.635709
false
false
false
false
stuartbreckenridge/UISearchControllerWithSwift
refs/heads/master
SearchController/ViewController.swift
mit
1
// // ViewController.swift // SearchController // // Created by Stuart Breckenridge on 17/8/14. // Copyright (c) 2014 Stuart Breckenridge. All rights reserved. // import UIKit class ViewController: UIViewController { @IBOutlet weak var countryTable: UITableView! var searchArray = [String]() { didSet { NotificationCenter.default.post(name: NSNotification.Name.init("searchResultsUpdated"), object: searchArray) } } lazy var countrySearchController: UISearchController = ({ // Display search results in a separate view controller let storyBoard = UIStoryboard(name: "Main", bundle: Bundle.main) let alternateController = storyBoard.instantiateViewController(withIdentifier: "aTV") as! AlternateTableViewController let controller = UISearchController(searchResultsController: alternateController) //let controller = UISearchController(searchResultsController: nil) controller.hidesNavigationBarDuringPresentation = false controller.dimsBackgroundDuringPresentation = false controller.searchBar.searchBarStyle = .minimal controller.searchResultsUpdater = self controller.searchBar.sizeToFit() return controller })() override func viewDidLoad() { super.viewDidLoad() definesPresentationContext = true // Configure navigation item to display search controller. navigationItem.searchController = countrySearchController navigationItem.hidesSearchBarWhenScrolling = false } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } } extension ViewController: UITableViewDataSource { func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { switch countrySearchController.isActive { case true: return searchArray.count case false: return countries.count } } func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = countryTable.dequeueReusableCell(withIdentifier: "Cell") as! SearchTableViewCell cell.textLabel?.text = "" cell.textLabel?.attributedText = NSAttributedString(string: "") switch countrySearchController.isActive { case true: cell.configureCell(with: countrySearchController.searchBar.text!, cellText: searchArray[indexPath.row]) return cell case false: cell.textLabel?.text! = countries[indexPath.row] return cell } } } extension ViewController: UITableViewDelegate { func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) { tableView.deselectRow(at: indexPath, animated: true) } } extension ViewController: UISearchResultsUpdating { func updateSearchResults(for searchController: UISearchController) { if searchController.searchBar.text?.utf8.count == 0 { searchArray = countries countryTable.reloadData() } else { searchArray.removeAll(keepingCapacity: false) let range = searchController.searchBar.text!.startIndex ..< searchController.searchBar.text!.endIndex var searchString = String() searchController.searchBar.text?.enumerateSubstrings(in: range, options: .byComposedCharacterSequences, { (substring, substringRange, enclosingRange, success) in searchString.append(substring!) searchString.append("*") }) let searchPredicate = NSPredicate(format: "SELF LIKE[cd] %@", searchString) searchArray = countries.filter({ searchPredicate.evaluate(with: $0) }) countryTable.reloadData() } } }
500d3af0b0de1fefb6b7a49150b85dfc
34.666667
173
0.672392
false
false
false
false
startupthekid/CoordinatorKit
refs/heads/develop
CoordinatorKitTests/MulticastDelegateSpec.swift
mit
1
// // MulticastDelegateSpec.swift // CoordinatorKit // // Created by Brendan Conron on 8/10/17. // Copyright © 2017 Brendan Conron. All rights reserved. // import Quick import Nimble import CoordinatorKit private protocol MockProtocol { func didReceiveMessage() } class MulticastDelegateSpec: QuickSpec { private class MockListener: MockProtocol { var messagesReceived: Int = 0 func didReceiveMessage() { messagesReceived += 1 } } override func spec() { describe("MulticastDelegate") { var multicastDelegate: MulticastDelegate<MockListener>! beforeEach { multicastDelegate = MulticastDelegate() } context("when using multiple listeners") { var mockListener1: MockListener! var mockListener2: MockListener! beforeEach { mockListener1 = MockListener() mockListener2 = MockListener() multicastDelegate += mockListener1 multicastDelegate += mockListener2 } afterEach { mockListener1 = nil mockListener2 = nil } it("should send a message to each listener") { multicastDelegate => { $0.didReceiveMessage() } expect(mockListener1.messagesReceived).to(equal(1)) expect(mockListener2.messagesReceived).to(equal(1)) } } context("when adding delegates") { var mockListener: MockListener! beforeEach { mockListener = MockListener() } it("should contain that delegate") { multicastDelegate += mockListener expect(multicastDelegate.containsDelegate(mockListener)).to(beTrue()) } } context("when removing delegates") { var mockListener: MockListener! beforeEach { mockListener = MockListener() multicastDelegate += mockListener } it("should not contain the delegate") { multicastDelegate -= mockListener expect(multicastDelegate.containsDelegate(mockListener)).to(beFalse()) expect(multicastDelegate.isEmpty).to(beTrue()) } } afterEach { multicastDelegate.removeAll() } } } }
11cc63ceda3961702c87c97289131ba4
28.55
90
0.468697
false
false
false
false
SquidKit/SquidKit
refs/heads/master
SquidKit/AccountHelper.swift
mit
1
// // ACAccount+SquidStore.swift // SquidKit // // Created by Mike Leavy on 8/17/14. // Copyright © 2014-2019 Squid Store, LLC. All rights reserved. // import UIKit import Accounts public protocol AccountHelperLoggable { func log<T>( _ output:@autoclosure () -> T?) } open class AccountHelper { let acAccountTypeIdentifier:String! open var accountUserFullName:String? open var accountUsername:String? open var accountIdentifier:String? // facebook required options open var facebookAppId:String? open var facebookPermissions:[String]? public init(accountIdentifier:String) { self.acAccountTypeIdentifier = accountIdentifier } open func authenticateWithCompletion(_ completion:@escaping (Bool) -> Void) { if (self.acAccountTypeIdentifier == ACAccountTypeIdentifierTwitter) { self.authenticateTwitter(completion) } else { completion(false) } } open func authenticateTwitter(_ completion:@escaping (Bool) -> Void) { let accountStore = ACAccountStore() guard let acAccountTypeTwitter = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierTwitter) else { completion(false) return } accountStore.requestAccessToAccounts(with: acAccountTypeTwitter, options: nil, completion: {[weak self] (success:Bool, error:Error?) -> Void in if success { guard let strongSelf = self else { completion(false) return } if let twitterAccount = self?.firstAccount(accountStore, accountType: acAccountTypeTwitter) { strongSelf.logAccountAccessResult("Twitter: ", userFullName: String.nonNilString(twitterAccount.userFullName, stringForNil:"<nil>"), userName: twitterAccount.username, userIdentifier: twitterAccount.identifier as String?) } } completion(success) }) } open func authenticateFacebook(_ completion:@escaping (Bool) -> Void) { let accountStore = ACAccountStore() guard let acAccountTypeFacebook = accountStore.accountType(withAccountTypeIdentifier: ACAccountTypeIdentifierFacebook) else { completion(false) return } accountStore.requestAccessToAccounts(with: acAccountTypeFacebook, options: self.makeFacebookOptions(), completion: {[weak self] (success:Bool, error:Error?) -> Void in if success { guard let strongSelf = self else { completion(false) return } if let facebookAccount = self?.firstAccount(accountStore, accountType: acAccountTypeFacebook) { strongSelf.logAccountAccessResult("Facebook: ", userFullName: String.nonNilString(facebookAccount.userFullName, stringForNil:"<nil>"), userName: facebookAccount.username, userIdentifier: facebookAccount.identifier as String?) } } completion(success) }) } fileprivate func logAccountAccessResult(_ accountPrefix:String, userFullName:String, userName:String, userIdentifier:String?) { if let loaggable = self as? AccountHelperLoggable { loaggable.log ( accountPrefix + "\(userFullName)" + "\n" + accountPrefix + "\(userName)" + "\n" + accountPrefix + "\(String(describing: userIdentifier))" ) } } fileprivate func makeFacebookOptions() -> [AnyHashable : Any] { var options = [AnyHashable: Any]() if let appId = self.facebookAppId { options[ACFacebookAppIdKey] = appId } if let permissions = self.facebookPermissions { options[ACFacebookPermissionsKey] = permissions } return options } fileprivate func firstAccount(_ accountStore:ACAccountStore, accountType:ACAccountType) -> ACAccount? { var account:ACAccount? if let accountsOfType = accountStore.accounts(with: accountType) as? [ACAccount] { if accountsOfType.count > 0 { account = accountsOfType[0] } } return account } }
2e4cf08c3e428c5085faf16f8c257367
35.560976
245
0.605515
false
false
false
false
joshpar/Lyrebird
refs/heads/master
LyrebirdSynth/Lyrebird/LyrebirdClock.swift
artistic-2.0
1
// // LyrebirdClock.swift // Lyrebird // // Created by Joshua Parmenter on 6/10/16. // Copyright © 2016 Op133Studios. All rights reserved. // public let LyrebirdDefaultClockResolution: LyrebirdFloat = 0.01 public struct LyrebirdScheduler { var curTime: LyrebirdFloat public var queue: [LyrebirdScheduledEvent] public init(){ curTime = 0.0 queue = [] } public mutating func updateCurTime(newCurTime: LyrebirdFloat) { curTime = newCurTime var indiciesToRemove: [Int] = [] if queue.count > 0 { for index in 0 ..< queue.count { var event = queue[index] if curTime > event.startTime! { event.run(curTime: curTime) if let nextTime = event.nextTime { event.startTime = curTime + nextTime } else { indiciesToRemove.append(index) } } } for index in indiciesToRemove { queue.remove(at: index) } } //print("\(queue)") } public mutating func addEventToQueue(event: LyrebirdScheduledEvent) { queue.append(event) } } public typealias LyrebirdEventBlock = (_ curTime: LyrebirdFloat, _ iteration: LyrebirdInt) -> LyrebirdFloat? public struct LyrebirdScheduledEvent { public var startTime: LyrebirdFloat? var nextTime: LyrebirdFloat? var eventBlock: LyrebirdEventBlock public var iteration: LyrebirdInt public init(startTime: LyrebirdFloat, eventBlock: @escaping LyrebirdEventBlock){ iteration = 0 self.startTime = startTime self.eventBlock = eventBlock } mutating func run(curTime: LyrebirdFloat){ nextTime = eventBlock(curTime, iteration) iteration = iteration + 1 } }
cae47aabc927f12a5b7661cc37785b05
27.666667
108
0.591438
false
false
false
false
devincoughlin/swift
refs/heads/master
test/Reflection/typeref_decoding_asan.swift
apache-2.0
5
// REQUIRES: asan_runtime // RUN: %empty-directory(%t) // RUN: %target-build-swift %S/Inputs/ConcreteTypes.swift %S/Inputs/GenericTypes.swift %S/Inputs/Protocols.swift %S/Inputs/Extensions.swift %S/Inputs/Closures.swift -parse-as-library -emit-module -emit-library -module-name TypesToReflect -sanitize=address -o %t/%target-library-name(TypesToReflect) // RUN: %target-swift-reflection-dump -binary-filename %t/%target-library-name(TypesToReflect) | %FileCheck %s // CHECK: FIELDS: // CHECK: ======= // CHECK: TypesToReflect.Box // CHECK: ------------------ // CHECK: item: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: anEnum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: aTupleWithLabels: (a: TypesToReflect.C, s: TypesToReflect.S, e: TypesToReflect.E) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithVarArgs: (TypesToReflect.C, TypesToReflect.S...) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (variadic // CHECK: (struct TypesToReflect.S)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout1: (inout TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout2: (TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithInout3: (inout TypesToReflect.C, inout Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (inout // CHECK: (class TypesToReflect.C)) // CHECK: (inout // CHECK: (struct Swift.Int)) // CHECK: (result // CHECK: (tuple)) // CHECK: aFunctionWithShared: (__shared TypesToReflect.C) -> () // CHECK: (function // CHECK: (parameters // CHECK: (shared // CHECK: (class TypesToReflect.C)) // CHECK: (result // CHECK: (tuple)) // CHECK: TypesToReflect.S // CHECK: ---------------- // CHECK: aClass: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: aTuple: (TypesToReflect.C, TypesToReflect.Box<TypesToReflect.S>, TypesToReflect.Box<TypesToReflect.E>, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (struct TypesToReflect.S)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (enum TypesToReflect.E)) // CHECK: (struct Swift.Int)) // CHECK: aMetatype: TypesToReflect.C.Type // CHECK: (metatype // CHECK: (class TypesToReflect.C)) // CHECK: aFunction: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (struct Swift.Int)) // CHECK: aFunctionWithThinRepresentation: @convention(thin) () -> () // CHECK: (function convention=thin // CHECK: (tuple)) // CHECK: aFunctionWithCRepresentation: @convention(c) () -> () // CHECK: (function convention=c // CHECK: (tuple)) // CHECK: TypesToReflect.S.NestedS // CHECK: ------------------------ // CHECK: aField: Swift.Int // CHECK: (struct Swift.Int) // CHECK: TypesToReflect.E // CHECK: ---------------- // CHECK: Class: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: Struct: TypesToReflect.S // CHECK: (struct TypesToReflect.S) // CHECK: Enum: TypesToReflect.E // CHECK: (enum TypesToReflect.E) // CHECK: Function: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) -> () // CHECK: (function // CHECK: (parameters // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int) // CHECK: (result // CHECK: (tuple)) // CHECK: Tuple: (TypesToReflect.C, TypesToReflect.S, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (struct Swift.Int)) // CHECK: IndirectTuple: (TypesToReflect.C, TypesToReflect.S, TypesToReflect.E, Swift.Int) // CHECK: (tuple // CHECK: (class TypesToReflect.C) // CHECK: (struct TypesToReflect.S) // CHECK: (enum TypesToReflect.E) // CHECK: (struct Swift.Int)) // CHECK: NestedStruct: TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S.NestedS // CHECK: (struct TypesToReflect.S)) // CHECK: Metatype // CHECK: EmptyCase // CHECK: TypesToReflect.References // CHECK: ------------------------- // CHECK: strongRef: TypesToReflect.C // CHECK: (class TypesToReflect.C) // CHECK: weakRef: weak Swift.Optional<TypesToReflect.C> // CHECK: (weak_storage // CHECK: (bound_generic_enum Swift.Optional // CHECK: (class TypesToReflect.C))) // CHECK: unownedRef: unowned TypesToReflect.C // CHECK: (unowned_storage // CHECK: (class TypesToReflect.C)) // CHECK: unownedUnsafeRef: unowned(unsafe) TypesToReflect.C // CHECK: (unmanaged_storage // CHECK: (class TypesToReflect.C)) // CHECK: TypesToReflect.C1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, TypesToReflect.E1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: dependentMember: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.C2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, TypesToReflect.E2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.C3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: anEnum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, TypesToReflect.E3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.C4 // CHECK: ----------------- // CHECK: TypesToReflect.S1 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E1<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C1<A>) -> (TypesToReflect.S1<A>) -> (TypesToReflect.E1<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C1<A>, TypesToReflect.Box<TypesToReflect.S1<A>>, TypesToReflect.Box<TypesToReflect.E1<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: TypesToReflect.S2 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E2<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C2<A>) -> (TypesToReflect.S2<A>) -> (TypesToReflect.E2<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C2<A>, TypesToReflect.Box<TypesToReflect.S2<A>>, TypesToReflect.Box<TypesToReflect.E2<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: TypesToReflect.S3 // CHECK: ----------------- // CHECK: aClass: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: aStruct: TypesToReflect.Box<TypesToReflect.S3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: anEnum: TypesToReflect.Box<TypesToReflect.E3<A>> // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: function: (TypesToReflect.C3<A>) -> (TypesToReflect.S3<A>) -> (TypesToReflect.E3<A>) -> Swift.Int // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (function // CHECK: (parameters // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (struct Swift.Int)))) // CHECK: tuple: (TypesToReflect.C3<A>, TypesToReflect.Box<TypesToReflect.S3<A>>, TypesToReflect.Box<TypesToReflect.E3<A>>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (bound_generic_class TypesToReflect.Box // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (struct Swift.Int)) // CHECK: primaryArchetype: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: dependentMember1: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: dependentMember2: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.S4 // CHECK: ----------------- // CHECK: TypesToReflect.E1 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C1<A> // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S1<A> // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E1<A> // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Int: Swift.Int // CHECK: (struct Swift.Int) // CHECK: Function: (A) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C1<A>, TypesToReflect.S1<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S1 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: Metatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E2 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C2<A> // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S2<A> // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E2<A> // CHECK: (bound_generic_enum TypesToReflect.E2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C2<A>, TypesToReflect.S2<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S2 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberInner: A.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (generic_type_parameter depth=0 index=0) member=Inner) // CHECK: ExistentialMetatype: A.Type // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: TypesToReflect.E3 // CHECK: ----------------- // CHECK: Class: TypesToReflect.C3<A> // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Struct: TypesToReflect.S3<A> // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Enum: TypesToReflect.E3<A> // CHECK: (bound_generic_enum TypesToReflect.E3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: Function: (A.Type.Type) -> TypesToReflect.E1<A> // CHECK: (function // CHECK: (parameters // CHECK: (metatype // CHECK: (metatype // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: (result // CHECK: (bound_generic_enum TypesToReflect.E1 // CHECK: (generic_type_parameter depth=0 index=0))) // CHECK: Tuple: (TypesToReflect.C3<A>, TypesToReflect.S3<A>, Swift.Int) // CHECK: (tuple // CHECK: (bound_generic_class TypesToReflect.C3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (bound_generic_struct TypesToReflect.S3 // CHECK: (generic_type_parameter depth=0 index=0)) // CHECK: (struct Swift.Int)) // CHECK: Primary: A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: DependentMemberOuter: A.TypesToReflect.P2.Outer // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) // CHECK: DependentMemberInner: A.TypesToReflect.P2.Outer.TypesToReflect.P1.Inner // CHECK: (dependent_member protocol=14TypesToReflect2P1P // CHECK: (dependent_member protocol=14TypesToReflect2P2P // CHECK: (generic_type_parameter depth=0 index=0) member=Outer) member=Inner) // CHECK: TypesToReflect.E4 // CHECK: ----------------- // CHECK: TypesToReflect.P1 // CHECK: ----------------- // CHECK: TypesToReflect.P2 // CHECK: ----------------- // CHECK: TypesToReflect.P3 // CHECK: ----------------- // CHECK: TypesToReflect.P4 // CHECK: ----------------- // CHECK: TypesToReflect.ClassBoundP // CHECK: -------------------------- // CHECK: TypesToReflect.(FileprivateProtocol in _{{[0-9A-F]+}}) // CHECK: ------------------------------------------------------------------------- // CHECK: TypesToReflect.HasFileprivateProtocol // CHECK: ------------------------------------- // CHECK: x: TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}) // CHECK: (protocol_composition // CHECK-NEXT: (protocol TypesToReflect.(FileprivateProtocol in ${{[0-9a-fA-F]+}}))) // CHECK: ASSOCIATED TYPES: // CHECK: ================= // CHECK: - TypesToReflect.C1 : TypesToReflect.ClassBoundP // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.C4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.S4 : TypesToReflect.P2 // CHECK: typealias Outer = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P1 // CHECK: typealias Inner = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: - TypesToReflect.E4 : TypesToReflect.P2 // CHECK: typealias Outer = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.E4 : TypesToReflect.P3 // CHECK: typealias First = A // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: typealias Second = B // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: - TypesToReflect.S : TypesToReflect.P4 // CHECK: typealias Result = Swift.Int // CHECK: (struct Swift.Int) // CHECK: BUILTIN TYPES: // CHECK: ============== // CHECK: CAPTURE DESCRIPTORS: // CHECK: ==================== // CHECK: - Capture types: // CHECK: (builtin Builtin.NativeObject) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (closure_binding index=1) // CHECK: - Capture types: // CHECK: (struct Swift.Int) // CHECK: - Metadata sources: // CHECK: - Capture types: // CHECK: (bound_generic_class TypesToReflect.C1 // CHECK: (generic_type_parameter depth=0 index=1)) // CHECK: - Metadata sources: // CHECK: (generic_type_parameter depth=0 index=0) // CHECK: (closure_binding index=0) // CHECK: (generic_type_parameter depth=0 index=1) // CHECK: (generic_argument index=0 // CHECK: (reference_capture index=0))
4c360ea8a633e70a829c8f15b7ae9ad0
35.742818
298
0.667411
false
false
false
false
vazteam/ProperMediaView
refs/heads/master
Classes/ProperMediaView/ProperMediaView.swift
mit
1
// // ProperMoviePlayView.swift // ProperNowDetailViewController // // Created by Murawaki on 2017/01/30. // Copyright © 2017年 VAZ inc. All rights reserved. // import Foundation import AVFoundation import UIKit import SDWebImage @objc protocol ProperMediaViewDelegate: class { @objc optional func moviePlayViewVolumeChanged(isVolume: Bool) } public class ProperMediaView: UIView { @IBOutlet weak var playerView: AVPlayerView! @IBOutlet weak var imageView: ProgressImageView! @IBOutlet weak var topProgressView: UIProgressView! @IBOutlet weak var bottomProgressView: UIView! @IBOutlet weak var operationAreaView: UIView! @IBOutlet weak var replayButton: UIButton! @IBOutlet weak var playAndPauseButton: UIButton! @IBOutlet weak var bottomOperateStackView: UIStackView! @IBOutlet weak var playTimeLabel: UILabel! @IBOutlet weak var laodingProgressView: UIProgressView! @IBOutlet weak var seekSlider: UISlider! @IBOutlet weak var durationTimeLabel: UILabel! @IBOutlet weak var volumeButton: UIButton! @IBOutlet weak var translucentView: UIView! var media: ProperMedia var isNeedsDownloadOriginal: Bool = false var isLoadedOriginalImage: Bool = false var isPlaying: Bool = false var isFullScreen: Bool var isPlayWaiting: Bool = false var progressColor: UIColor { didSet{ self.topProgressView.progressTintColor = progressColor self.seekSlider.minimumTrackTintColor = progressColor } } weak var delegate: ProperMediaViewDelegate? private weak var fromViewController: UIViewController? var videoPlayer: AVPlayer! fileprivate var playerItem: AVPlayerItem? fileprivate var isPausedBySeekSlider: Bool = false fileprivate var isFullScreenViewFetchWaiting: Bool = false fileprivate var currentImageUrl: URL? var displaceMovieView: ProperMediaView! private var movieDurationSeconds: Double { var dutarion: CMTime = kCMTimeZero if let videoDuration = self.videoPlayer.currentItem?.duration { dutarion = videoDuration } return CMTimeGetSeconds( dutarion ) } private var isShowPlayingOperaters: Bool { return bottomOperateStackView.alpha == 1.0 } private var isShowEndedOperaters: Bool { return replayButton.alpha == 1.0 } private var bounceAnimation: CAKeyframeAnimation { let anim = CAKeyframeAnimation(keyPath: "transform.scale") anim.duration = 0.3 anim.values = [0.6, 1.2, 1, 1.1, 1] anim.keyTimes = [0, 0.4, 0.6, 0.8, 1.0] return anim } public init(frame: CGRect, media: ProperMedia, isNeedsDownloadOriginalImage: Bool = false, isFullScreen: Bool = false) { self.media = media self.isFullScreen = isFullScreen self.progressColor = UIColor(red:0.92, green:0.26, blue:0.21, alpha:1.00) self.isNeedsDownloadOriginal = isNeedsDownloadOriginalImage super.init(frame: frame) commonInit() fetchContent(media: media) } public convenience init(frame: CGRect, media: ProperMedia, videoPlayer: AVPlayer) { self.init(frame: frame, media: media) self.media = media self.isFullScreen = true self.videoPlayer = videoPlayer self.playerItem = videoPlayer.currentItem } required public init?(coder aDecoder: NSCoder) { fatalError("ProperMediaView can't init from nib") } private func commonInit() { self.backgroundColor = UIColor.clear let bundle = Bundle(for: type(of: self)) let nib = UINib(nibName: "ProperMediaView", bundle: bundle) let view = nib.instantiate(withOwner: self, options: nil).first as! UIView addSubview(view) view.translatesAutoresizingMaskIntoConstraints = false let bindings = ["view": view] addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "H:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) addConstraints(NSLayoutConstraint.constraints(withVisualFormat: "V:|[view]|", options:NSLayoutFormatOptions(rawValue: 0), metrics:nil, views: bindings)) //下のビューのグラデーション let bottomColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3) let gradientColors: [CGColor] = [UIColor.clear.cgColor, bottomColor.cgColor] let gradientLayer: CAGradientLayer = CAGradientLayer() gradientLayer.colors = gradientColors gradientLayer.frame = self.bottomOperateStackView.bounds self.bottomOperateStackView.layer.insertSublayer(gradientLayer, at: 0) self.translucentView.alpha = 0 self.bottomOperateStackView.isUserInteractionEnabled = true self.operationAreaView.addGestureRecognizer(UITapGestureRecognizer(target: self, action: #selector(self.tappedOperationAreaView(gesture:)))) self.seekSlider.setThumbImage(UIImage.bundledImage(named: "icon_sliderThumb")?.resizeImage(size: CGSize(sideLength: 17)), for: .normal) self.dissmissMovieEndedOperaters() self.dismissMoviePlayingOperaters() self.layer.masksToBounds = true } deinit { if self.videoPlayer != nil { self.videoPlayer.pause() self.videoPlayer = nil } self.playerItem = nil } // MARK: - public func public func fetchContent(media: ProperMedia) { removeVideoItems() self.media = media if !media.isMovie { //画像の時 imageView.dismissLoading() topProgressView.isHidden = true playerView.isHidden = true bottomProgressView.isHidden = true } else { //動画のとき imageView.showLoading() topProgressView.isHidden = false playerView.isHidden = false bottomProgressView.isHidden = false } self.superview?.layoutIfNeeded() if self.playerItem != nil { if let currentUrl: URL = (videoPlayer.currentItem?.asset as? AVURLAsset)?.url { if media.mediaUrl == currentUrl { return } } } self.seekSlider.maximumTrackTintColor = UIColor.clear self.laodingProgressView.trackTintColor = UIColor(red: 1, green: 1, blue: 1, alpha: 0.3) self.laodingProgressView.setProgress(0, animated: false) startDownloadImage() } //フルスクリーン時に複製される時用 (動画 func fetchContent(media: ProperMedia, player: AVPlayer, fullScreen: Bool) { fetchContent(media: media) videoPlayer = player isFullScreen = fullScreen topProgressView.isHidden = true whenReadyToPlay() } //フルスクリーン時に複製される時用 (画像 func fetchContent(media: ProperMedia, originalImage: UIImage?) { self.media = media isFullScreen = true isNeedsDownloadOriginal = true imageView.dismissLoading() topProgressView.isHidden = true playerView.isHidden = true if let originalImage: UIImage = originalImage { self.imageView.image = originalImage self.isLoadedOriginalImage = true return } startDownloadImage() } public func setEnableFullScreen(fromViewController: UIViewController) { self.fromViewController = fromViewController } public func play() { guard isVideo() else { return } ifNeedStartDownload() if self.videoPlayer != nil { self.videoPlayer.play() self.isPlaying = true self.isPlayWaiting = false self.isPausedBySeekSlider = false let duration = CMTimeGetSeconds((videoPlayer.currentItem?.asset.duration)!) self.durationTimeLabel.text = self.stringFromSeconds(seconds: duration) DispatchQueue.main.async { self.playAndPauseButton.setBackgroundImage(UIImage.bundledImage(named: "btn_movie_pause"), for: .normal) self.dismissMoviePlayingOperaters(animation: true) //フルスクリーンなら音声を入れる AVAudioSession.setVolumeWhenMannerMode(isVolume: self.isFullScreen && self.isVideo()) } } else { isPlayWaiting = true } } public func pause() { if self.videoPlayer == nil && !isPlaying { return } videoPlayer.pause() isPlaying = false self.playAndPauseButton.setBackgroundImage(UIImage.bundledImage(named: "btn_movie_play"), for: .normal) } public func playOrPause() { if isPlaying { self.pause() } else { self.play() } } public func changeVolume(isVolume: Bool) { guard self.videoPlayer != nil else { return } if isVolume { self.volumeButton.setImage(UIImage.bundledImage(named: "volume_off"), for: .normal) self.videoPlayer.volume = 0 } else { self.volumeButton.setImage(UIImage.bundledImage(named: "volume_on"), for: .normal) self.videoPlayer.volume = 1.0 } self.delegate?.moviePlayViewVolumeChanged?(isVolume: isVolume) } //ビューの状態を保ったまま渡すために複製 func initDisplacement() -> ProperMediaView { displaceMovieView = ProperMediaView(frame: CGRect.zero, media: media) displaceMovieView.bounds = self.bounds displaceMovieView.center = self.center displaceMovieView.delegate = self.delegate displaceMovieView.layer.masksToBounds = true //動画の時 if isVideo() { if videoPlayer != nil { displaceMovieView.fetchContent(media: media, player: videoPlayer, fullScreen: true) } else { displaceMovieView.fetchContent(media: media) } return displaceMovieView } //画像のとき if isLoadedOriginalImage { displaceMovieView.fetchContent(media: media, originalImage: imageView.image) return displaceMovieView } displaceMovieView.fetchContent(media: media, originalImage: nil) return displaceMovieView } public func isVideo() -> Bool { return media.isMovie } // MARK: - private func private func removeVideoItems() { pause() dissmissMovieEndedOperaters() playerItem?.removeObserver(self, forKeyPath: "status") videoPlayer = nil playerItem = nil isPlayWaiting = false } private func startDownloadImage() { if let currentImageUrl = self.currentImageUrl, currentImageUrl == media.mediaUrl { return } imageView.sd_setImage(with: media.thumbnailImageUrl, placeholderImage: UIImage.bundledImage(named: "default_image"), options: .allowInvalidSSLCertificates) { (image, error, cacheType, url) in //サムネイルだけでなく、オリジナルサイズの画像もダウンロードする場合は続行 if !self.isNeedsDownloadOriginal { return } self.topProgressView.isHidden = false self.topProgressView.progress = 0.0 self.topProgressView.progressTintColor = self.progressColor self.translucentView.alpha = 1.0 self.imageView.sd_setImage(with: self.media.mediaUrl, placeholderImage: self.imageView.image, progress: { (done, entity, url) in DispatchQueue.main.async { var progress: Float = 0 if done > 0 { progress = Float(entity/done) } self.topProgressView.setProgress(progress, animated: true) } }) { (image, error, cachType, url) in DispatchQueue.main.async { UIView.animate(withDuration: 0.2, animations: { self.translucentView.alpha = 0 }, completion: { _ in self.isLoadedOriginalImage = true self.topProgressView.isHidden = true self.currentImageUrl = self.media.mediaUrl }) } } } } private func startDownloadMovie() { let avAsset = AVURLAsset(url: media.mediaUrl, options: nil) avAsset.loadValuesAsynchronously(forKeys: ["tracks"], completionHandler: { DispatchQueue.main.async { var error: NSError? let status = avAsset.statusOfValue(forKey: "tracks", error: &error) if status == .loaded { self.playerItem = AVPlayerItem(asset: avAsset) self.playerItem?.addObserver(self, forKeyPath: "status", options:[.new, .initial], context: nil) self.videoPlayer = AVPlayer(playerItem: self.playerItem) } else { if let error = error { print(error.localizedDescription) } } } }) } private func updateFirstLoadingProgress() { if self.videoPlayer == nil { //前半50%は見た目だけ let currentProgress = self.topProgressView.progress let randomAddProgress = (arc4random() % 20) var nextProgress = currentProgress + Float(randomAddProgress)/1000 if nextProgress > 0.5 { nextProgress = 0.5 } DispatchQueue.main.async { self.topProgressView.progress = nextProgress } } else { //残りの50%は進捗に合わせる if let loadedTimeRangeDuration = playerItem?.loadedTimeRanges.first?.timeRangeValue.duration { let loadedRatio = loadedTimeRangeDuration.seconds / 5.0 self.topProgressView.setProgress(Float(loadedRatio * 0.5) + 0.5, animated: true) } } if self.isPlaying { //再生が始まったら隠す self.topProgressView.setProgress(1.0, animated: true) UIView.animate(withDuration: 0.3, animations: { self.topProgressView.alpha = 0 }) } else { //再生が始まっていなければ再帰的に繰り返す DispatchQueue.main.asyncAfter(deadline: .now() + 0.03) { self.updateFirstLoadingProgress() } } } private func ifNeedStartDownload() { if videoPlayer == nil && !isPlayWaiting { self.updateFirstLoadingProgress() self.startDownloadMovie() } } private func showMoviePlayingOperaters() { if !isFullScreen { return } UIView.animate(withDuration: 0.3) { self.bottomOperateStackView.alpha = 1.0 self.playAndPauseButton.alpha = 1.0 } } private func dismissMoviePlayingOperaters(animation: Bool = false) { var duration: Double = 0 if animation { duration = 0.3 } UIView.animate(withDuration: TimeInterval(duration)) { self.bottomOperateStackView.alpha = 0 self.playAndPauseButton.alpha = 0 } } @objc private func showMovieEndedOperaters() { self.dismissMoviePlayingOperaters(animation: true) UIView.animate(withDuration: 0.3) { self.operationAreaView.backgroundColor = UIColor.black.withAlphaComponent(0.3) self.replayButton.transform = CGAffineTransform.identity self.replayButton.alpha = 1.0 } } private func dissmissMovieEndedOperaters(animation: Bool = false) { var duration: Double = 0 if animation { duration = 0.3 } UIView.animate(withDuration: TimeInterval(duration)) { self.operationAreaView.backgroundColor = UIColor.black.withAlphaComponent(0.0) self.replayButton.transform = CGAffineTransform(translationX: 0, y: 15) self.replayButton.alpha = 0.0 } } //ex: (125) -> "02:05" private func stringFromSeconds(seconds: Double) -> String { if seconds > 0 { let minStr = NSString(format: "%02d", Int(seconds) / 60) let secStr = NSString(format: "%02d", Int(seconds) % 60) return (minStr as String) + ":" + (secStr as String) } return "00:00" } // MARK: - Observer & Notification override public func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) { if keyPath == "status" { let status: AVPlayerItemStatus? = self.playerItem?.status if status == .readyToPlay { print("status readyToPlay") whenReadyToPlay() return } else if status == .unknown { print("status unknown") } else if status == .failed { print("status failed") } } else { super.observeValue(forKeyPath: keyPath, of: object, change: change, context: context) } } private func whenReadyToPlay() { guard videoPlayer != nil else { return } let layer = self.playerView.layer as! AVPlayerLayer layer.videoGravity = AVLayerVideoGravityResizeAspect layer.player = self.videoPlayer //再生時間の同期 let timeInterval: CMTime = CMTimeMakeWithSeconds(0.05, Int32(NSEC_PER_SEC)) self.videoPlayer.addPeriodicTimeObserver(forInterval: timeInterval, queue: nil) { (_) -> Void in self.whenMoviePlayingPeriodic() } //最後まで再生した時のNotification NotificationCenter.default.addObserver(self, selector: #selector(self.showMovieEndedOperaters), name: NSNotification.Name.AVPlayerItemDidPlayToEndTime, object: self.playerItem) self.playerView.backgroundColor = UIColor.black if isFullScreenViewFetchWaiting { displaceMovieView.fetchContent(media: media, player: videoPlayer, fullScreen: true) } if isPlayWaiting { DispatchQueue.main.async { self.play() } } } //再生時の同期 private func whenMoviePlayingPeriodic() { guard isPlaying else { return } let time = CMTimeGetSeconds(self.videoPlayer.currentTime()) let ratio = time / movieDurationSeconds //playTimeLabel self.playTimeLabel.text = stringFromSeconds(seconds: time) //movieSlider self.seekSlider.value = Float(ratio) //bottomProgress let lineWidth: CGFloat = 3.0 UIGraphicsBeginImageContextWithOptions(self.frame.size, false, 0) let path = UIBezierPath() path.move(to: CGPoint(x: 0, y: self.bounds.height - lineWidth/2)) path.addLine(to: CGPoint(x: self.bounds.width * CGFloat(ratio), y: self.bounds.height - lineWidth/2)) if isShowEndedOperaters { UIColor.clear.setStroke() } else { progressColor.setStroke() } path.lineWidth = lineWidth path.stroke() bottomProgressView.layer.contents = UIGraphicsGetImageFromCurrentImageContext()?.cgImage UIGraphicsEndImageContext() //Operator if isShowEndedOperaters { dissmissMovieEndedOperaters(animation: true) } //loading Progress guard let currentItem = videoPlayer.currentItem else { return } if let loadedTimeRangeDuration = currentItem.loadedTimeRanges.first?.timeRangeValue.duration { let ratio = loadedTimeRangeDuration.seconds / currentItem.asset.duration.seconds self.laodingProgressView.setProgress(Float(ratio), animated: false) } } @IBAction func touchUppedReplayButton(_ sender: UIButton) { if videoPlayer == nil { return } videoPlayer.seek(to: CMTimeMakeWithSeconds(0, Int32(NSEC_PER_SEC))) videoPlayer.play() dissmissMovieEndedOperaters(animation: true) } @IBAction func touchDownedLikeButton(_ sender: UIButton) { sender.imageView?.layer.add(self.bounceAnimation, forKey: "TouchDownLikeButton") } @IBAction func touchDownedReplayButton(_ sender: UIButton) { let anim = CABasicAnimation(keyPath: "transform.rotation") anim.duration = 0.5 anim.toValue = -Double.pi / 2 sender.imageView?.layer.add(anim, forKey: "TouchDownReplayButton") } @IBAction func touchUppedPlayAndPauseButton(_ sender: UIButton) { self.playOrPause() sender.layer.add(self.bounceAnimation, forKey: "TouchUppedPlayAndPauseButtonAnimation") } @IBAction func touchUppedVolumeButton(_ sender: UIButton) { guard self.videoPlayer != nil else { return } if self.videoPlayer.volume == 0 { self.changeVolume(isVolume: false) } else { self.changeVolume(isVolume: true) } } @IBAction func touchDownedSeekSlider(_ sender: UISlider) { if isPlaying { self.pause() self.isPausedBySeekSlider = true } } @IBAction func touchUpInsideSeekSlider(_ sender: UISlider) { if isPausedBySeekSlider { self.play() } } @IBAction func touchUpOutsideSeekSlider(_ sender: UISlider) { if isPausedBySeekSlider { self.play() } } @IBAction func valueChangedSeekSlider(_ sender: UISlider) { let seekSeconds = CMTimeMakeWithSeconds(movieDurationSeconds*Double(sender.value), Int32(NSEC_PER_SEC)) videoPlayer.seek(to: seekSeconds, toleranceBefore: kCMTimeZero, toleranceAfter: kCMTimeZero) } func tappedOperationAreaView(gesture: UITapGestureRecognizer) { if !isFullScreen { if let vc: UIViewController = fromViewController { ProperMediaFullScreenViewController.show(mediaView: self, fromViewController: vc) } } if isShowPlayingOperaters { dismissMoviePlayingOperaters(animation: true) } else { if !isShowEndedOperaters && isVideo() { showMoviePlayingOperaters() } } } }
5628b6eec90bdba45eabe0720e79d940
34.403349
199
0.594712
false
false
false
false
mendesbarreto/IOS
refs/heads/master
Swift.playground/Contents.swift
mit
1
//: Playground - noun: a place where people can play import Cocoa private func insertOptionsLinkAtrributesToRange( inout attriutedString attStr:NSMutableAttributedString, range:NSRange, option:String ){ let foregroundAttr = [ NSForegroundColorAttributeName: "UIColor.greenColor()" ]; let underLineAttr = [ NSUnderlineStyleAttributeName: NSUnderlineStyle.StyleDouble.rawValue ]; let linkAttr = [ NSLinkAttributeName: NSURL(string: "\(option)")!]; attStr.addAttributes(foregroundAttr, range: range); attStr.addAttributes(underLineAttr, range: range); attStr.addAttributes(linkAttr, range: range); //print(attStr); } private func replaceVariablenName( name:String , valueToAdd:String, inout attString:NSMutableAttributedString){ let tempStr = attString.string as NSString; var rangeStr = tempStr.rangeOfString(name); attString.replaceCharactersInRange(rangeStr, withString: valueToAdd); rangeStr = NSMakeRange(rangeStr.location, valueToAdd.characters.count); insertOptionsLinkAtrributesToRange(attriutedString: &attString, range: rangeStr, option: valueToAdd); //print(attString); } var attString:NSMutableAttributedString = NSMutableAttributedString(string: "Douglas Mendes Barreto"); let tempStr = attString.string as NSString; let rangeStr = tempStr.rangeOfString("Mendes"); attString.replaceCharactersInRange(rangeStr, withString: "Mendes Barreto") let text = "Douglas Mendes Barreto"; var att = NSMutableAttributedString(string: text); print(rangeStr); var range = NSMakeRange(rangeStr.location, 30); print(range); replaceVariablenName("Mendes", valueToAdd: "Mayara", attString: &att);
81aea379b30bc55fd19f9d1e290e6df3
27.576271
136
0.763345
false
false
false
false
yuyan7/YNBluetooth
refs/heads/master
YNBluetooth/YNCentralManager.swift
mit
1
// // YNCentralManager.swift // YNBluetooth // // Created by yuyan7 on 2017/07/08. // Copyright © 2017年 yuyan7. All rights reserved. // import CoreBluetooth /// YNCentralManagerDelegate public protocol YNCentralManagerDelegate: class { /// Found Peripheral /// /// - Parameters: /// - central: CentralManager /// - peripheral: Peripheral func findPeripheral(central: YNCentralManager, find peripheral: YNCPeripheral) } /// YNCentralManager public class YNCentralManager: NSObject { /// CentralManager var centralManager: CBCentralManager! /// Delegate public weak var delegate: YNCentralManagerDelegate? /// Peripherals public internal(set) var peripherals: [WeakRef<YNCPeripheral>] fileprivate var tmpPeripheral: CBPeripheral? /// Target Service UUID's var targets: [CBUUID]? /// Initialize /// /// - Parameters: /// - input: Target Service UUID's /// - queue: DispatchQueue /// - options: Option public init(input: [String]?, queue: DispatchQueue?, options: [String: Any]?) { if let strs = input { targets = strs.map({ (uuid) -> CBUUID in return CBUUID(string: uuid) }) } else { targets = nil } peripherals = [WeakRef<YNCPeripheral>]() super.init() centralManager = CBCentralManager(delegate: self, queue: queue, options: options) } /// Convenience Initialize /// /// - Parameters: /// - input: Target Service UUID's /// - queue: DispatchQueue public convenience init(input: [String]?, queue: DispatchQueue?) { self.init(input: input, queue: queue, options: nil) } /// Convenience Initialize /// /// - Parameter input: Target Service UUID's public convenience init(input: [String]?) { let options = [ CBCentralManagerOptionShowPowerAlertKey: NSNumber(value: true), CBCentralManagerOptionRestoreIdentifierKey: Bundle.main.bundleIdentifier as Any ] as [String : Any] self.init(input: input, queue: nil, options: options) } /// Start Scan /// /// If Need Scan Please Call public func startScan() { debugLog("Start Scan") centralManager.scanForPeripherals(withServices: targets, options: nil) } /// Stop Scan /// /// Stop Scan must call public func stopScan() { debugLog("Stop Scan") centralManager.stopScan() } /// Connect Peripheral /// /// add YNCPeripheral object connect peripheral /// return findPeripheral Delegate /// please change Reference /// /// - Parameter peripheral: target connect Peripheral public func connectPeripheral(peripheral: YNCPeripheral) { centralManager.connect(peripheral.peripheral, options: nil) } /// Search input YNCPeripheral /// /// - Parameter peripheral: target /// - Returns: Found YNCPeripheral func getTargetPeripheral(peripheral: CBPeripheral) -> YNCPeripheral? { return peripherals.first { (inner) -> Bool in return inner.value?.peripheral == peripheral }?.value } } // MARK: - CBPeripheralDelegate extension YNCentralManager: CBPeripheralDelegate { /// Discover Service /// /// - Parameters: /// - peripheral: Peripheral /// - error: error public func peripheral(_ peripheral: CBPeripheral, didDiscoverServices error: Error?) { guard let services = peripheral.services else { return } debugLog("Discover Service \(services)") let obj = YNCPeripheral(peripheral: peripheral, services: services) delegate?.findPeripheral(central: self, find: obj) self.peripherals.append(WeakRef(value: obj)) } /// Discover Included Service /// /// - Parameters: /// - peripheral: Peripheral /// - service: Service /// - error: error public func peripheral(_ peripheral: CBPeripheral, didDiscoverIncludedServicesFor service: CBService, error: Error?) { } /// Modify Service /// /// - Parameters: /// - peripheral: Peripheral /// - invalidatedServices: changed Service public func peripheral(_ peripheral: CBPeripheral, didModifyServices invalidatedServices: [CBService]) { guard let services = peripheral.services else { return } debugLog("Discover Service \(services)") let obj = YNCPeripheral(peripheral: peripheral, services: services) delegate?.findPeripheral(central: self, find: obj) self.peripherals.append(WeakRef(value: obj)) } } // MARK: - CBCentralManagerDelegate extension YNCentralManager: CBCentralManagerDelegate { /// /// /// - Parameters: /// - central: centralmanager /// - dict: parameter public func centralManager(_ central: CBCentralManager, willRestoreState dict: [String : Any]) { debugLog("RestoreState \(dict)") targets = dict[CBCentralManagerRestoredStateScanServicesKey] as? [CBUUID] if let peripherals = dict[CBCentralManagerRestoredStatePeripheralsKey] as? [CBPeripheral] { // 接続していたペリフェラルが存在する時、再接続 for peripheral in peripherals { self.tmpPeripheral = peripheral central.connect(peripheral, options: nil) } } else { // スキャン開始 startScan() } } /// CentralManagerDidupdateState /// /// - Parameter central: CentralManager public func centralManagerDidUpdateState(_ central: CBCentralManager) { switch central.state { case .poweredOff: break case .poweredOn: startScan() break case .resetting: break case .unauthorized: break case .unknown: break case .unsupported: break } } /// CentralManager is Discover Peripheral /// /// - Parameters: /// - central: CentralManager /// - peripheral: Discover Peripheral /// - advertisementData: advertisementData /// - RSSI: RSSI public func centralManager(_ central: CBCentralManager, didDiscover peripheral: CBPeripheral, advertisementData: [String : Any], rssi RSSI: NSNumber) { debugLog("Discovered \(peripheral)") self.tmpPeripheral = peripheral central.connect(peripheral, options: nil) } /// CentralManager is Connect Peripheral /// /// - Parameters: /// - central: CentralManager /// - peripheral: Connect Peripheral public func centralManager(_ central: CBCentralManager, didConnect peripheral: CBPeripheral) { debugLog("Connect Peripheral \(peripheral)") peripheral.delegate = self peripheral.discoverServices(targets) } /// CentralManager is Failed Connection to Peripheral /// /// - Parameters: /// - central: CentralManager /// - peripheral: Failed to Connect Peripheral /// - error: error public func centralManager(_ central: CBCentralManager, didFailToConnect peripheral: CBPeripheral, error: Error?) { debugLog("FailToConnect Peripheral \(peripheral)") if let error = error { debugLog("Error \(error.localizedDescription)") } // リトライ self.tmpPeripheral = peripheral central.connect(peripheral, options: nil) } /// CentralManager is Disconnect Peripheral /// /// - Parameters: /// - central: CentralManager /// - peripheral: Disconnecte Peripheral /// - error: Error public func centralManager(_ central: CBCentralManager, didDisconnectPeripheral peripheral: CBPeripheral, error: Error?) { debugLog("Disconnect Peripheral \(peripheral)") if let error = error { debugLog("Error \(error.localizedDescription)") } self.tmpPeripheral = peripheral central.connect(peripheral, options: nil) } }
ce377f7f894533bfc953802c1003520d
30.29845
155
0.624025
false
false
false
false
Sega-Zero/Cereal
refs/heads/master
Example/EditTrainViewController.swift
bsd-3-clause
2
// // EditTrainViewController.swift // Cereal // // Created by James Richard on 9/30/15. // Copyright © 2015 Weebly. All rights reserved. // import UIKit protocol EditTrainViewControllerDelegate: class { func editTrainViewController(_ editTrainViewController: EditTrainViewController, didSaveTrain train: Train) } class EditTrainViewController: UIViewController { var train: Train! weak var delegate: EditTrainViewControllerDelegate? @IBOutlet var makeTextField: UITextField! @IBOutlet var modelTextField: UITextField! @IBOutlet var carsLabel: UILabel! @IBOutlet var stepperView: UIStepper! override func viewDidLoad() { super.viewDidLoad() makeTextField.text = train.make modelTextField.text = train.model carsLabel.text = String(train.cars) stepperView.value = Double(train.cars) } @IBAction func savePressed() { delegate?.editTrainViewController(self, didSaveTrain: train) performSegue(withIdentifier: "UnwindToVehicleList", sender: self) } @IBAction func textValueChanged(_ textField: UITextField) { switch textField { case makeTextField: train = Train(make: textField.text ?? "", model: train.model, cars: train.cars) case modelTextField: train = Train(make: train.make, model: textField.text ?? "", cars: train.cars) default: break } } @IBAction func cylindersStepperChanged(_ stepper: UIStepper) { let cars = Int(stepper.value) train.cars = cars carsLabel.text = String(cars) } }
215a4e9c1e002e091b1a9cd7e0fe59d7
31.204082
111
0.690748
false
false
false
false
coderZsq/coderZsq.target.swift
refs/heads/master
StudyNotes/Swift Note/PhotoBrowser/PhotoBrowser/Classes/Home/Animation/HomeAnimation.swift
mit
1
// // HomeAnimation.swift // PhotoBrowser // // Created by 朱双泉 on 2018/10/30. // Copyright © 2018 Castie!. All rights reserved. // import UIKit protocol HomeAnimationPresentDelegate: class { func presentAnimationView() -> UIView func presentAnimationFromFrame() -> CGRect func presentAnimationToFrame() -> CGRect } protocol HomeAnimationDismissDelegate: class { func dismissAnimationView() -> UIView func dismissAnimationFromFrame() -> CGRect func dismissAnimationToFrame() -> CGRect } class HomeAnimation: NSObject, UIViewControllerTransitioningDelegate { weak var presentDelegate: HomeAnimationPresentDelegate? weak var dismissDelegate: HomeAnimationDismissDelegate? var isPresent = true func animationController(forPresented presented: UIViewController, presenting: UIViewController, source: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = true return self } func animationController(forDismissed dismissed: UIViewController) -> UIViewControllerAnimatedTransitioning? { isPresent = false return self } } extension HomeAnimation: UIViewControllerAnimatedTransitioning { func transitionDuration(using transitionContext: UIViewControllerContextTransitioning?) -> TimeInterval { return 1 } func animateTransition(using transitionContext: UIViewControllerContextTransitioning) { if isPresent { presentAnimation(transitionContext: transitionContext) } else { dismissAnimation(transitionContext: transitionContext) } } func dismissAnimation(transitionContext: UIViewControllerContextTransitioning) { guard let dismissDelegate = dismissDelegate else { return } let containerView = transitionContext.containerView let animationView = dismissDelegate.dismissAnimationView() let fromFrame = dismissDelegate.dismissAnimationFromFrame() let toFrame = dismissDelegate.dismissAnimationToFrame() containerView.addSubview(animationView) animationView.frame = fromFrame let fromView = transitionContext.view(forKey: .from) UIView.animate(withDuration: 1, animations: { animationView.frame = toFrame fromView?.alpha = 0 }) { (complete) in animationView.removeFromSuperview() fromView?.removeFromSuperview() transitionContext.completeTransition(true) } } func presentAnimation(transitionContext: UIViewControllerContextTransitioning) { guard let presentDelegate = presentDelegate else { return } let containerView = transitionContext.containerView let animationView = presentDelegate.presentAnimationView() let fromFrame = presentDelegate.presentAnimationFromFrame() let toFrame = presentDelegate.presentAnimationToFrame() containerView.addSubview(animationView) animationView.frame = fromFrame let detailView = transitionContext.view(forKey: .to) detailView?.frame = kScreenBounds containerView.addSubview(detailView!) detailView?.alpha = 0 UIView.animate(withDuration: 1, animations: { animationView.frame = toFrame detailView?.alpha = 1 }) { (complete) in animationView.removeFromSuperview() transitionContext.completeTransition(true) } } }
8ad44cec9fea5c3e27f0704e0fe274c4
32.333333
170
0.683611
false
false
false
false
pgawlowski/Stylish-2
refs/heads/master
Stylish-2/Styleable/StyleableUIImageView.swift
mit
1
// // UIImagePropertySet.swift // Stylish-2.0 // // Created by Piotr Gawlowski on 08/05/2017. // Copyright © 2017 Piotr Gawlowski. All rights reserved. // import Foundation import UIKit struct UIImageViewPropertySet : DynamicStylePropertySet { var propertySet: Dictionary<String, Any> = UIImageView().retriveDynamicPropertySet() var image:UIImage? var customUIImageViewStyleBlock:((UIImageView)->())? mutating func setStyleProperty<T>(named name: String, toValue value: T) { switch name { case _ where name.isVariant(of: "Image"): image = value as? UIImage case _ where name.isVariant(of: "Template"): image = (value as? UIImage)?.withRenderingMode(.alwaysTemplate) default : return } } } extension StyleClass { var UIImageView:UIImageViewPropertySet { get { return self.retrieve(propertySet: UIImageViewPropertySet.self) } set { self.register(propertySet: newValue) } } } @IBDesignable public class StyleableUIImageView : UIImageView, Styleable { class var StyleApplicators: [StyleApplicator] { return StyleableUIView.StyleApplicators + [{ (style:StyleClass, target:Any) in if let imageView = target as? UIImageView { imageView.image =? style.UIImageView.image if let customStyleBlock = style.UIImageView.customUIImageViewStyleBlock { customStyleBlock(imageView) } } }] } @IBInspectable var styles:String = "" { didSet { parseAndApplyStyles() } } @IBInspectable var stylesheet:String = "" { didSet { parseAndApplyStyles() } } override public func prepareForInterfaceBuilder() { showErrorIfInvalidStyles() } }
fe6a4cb2e45d4bb7c11c2613e97ba2a8
29.813559
162
0.643014
false
false
false
false
Zewo/ContentNegotiationMiddleware
refs/heads/master
Source/ContentMapperMiddleware.swift
mit
1
// ContentMapperMiddleware.swift // // The MIT License (MIT) // // Copyright (c) 2015 Zewo // // 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. public protocol ContentMappable: Mappable { static var key: String { get } } extension ContentMappable { public static var key: String { return String(reflecting: self) } } public struct ContentMapperMiddleware: Middleware { let type: ContentMappable.Type public init(mappingTo type: ContentMappable.Type) { self.type = type } public func respond(to request: Request, chainingTo next: Responder) throws -> Response { guard let content = request.content else { return try next.respond(to: request) } var request = request do { let target = try type.init(structuredData: content) request.storage[type.key] = target } catch StructuredData.Error.incompatibleType { return Response(status: .badRequest) } catch { throw error } return try next.respond(to: request) } }
e1398d5e539dc25751a3b8aa72d76af2
33.590164
93
0.700474
false
false
false
false
mpullman/ios-charts
refs/heads/master
Charts/Classes/Data/BarChartDataSet.swift
apache-2.0
1
// // BarChartDataSet.swift // Charts // // Created by Daniel Cohen Gindi on 4/3/15. // // Copyright 2015 Daniel Cohen Gindi & Philipp Jahoda // A port of MPAndroidChart for iOS // Licensed under Apache License 2.0 // // https://github.com/danielgindi/ios-charts // import Foundation import CoreGraphics import UIKit public class BarChartDataSet: BarLineScatterCandleChartDataSet { /// space indicator between the bars in percentage of the whole width of one value (0.15 == 15% of bar width) public var barSpace: CGFloat = 0.15 /// the maximum number of bars that are stacked upon each other, this value /// is calculated from the Entries that are added to the DataSet private var _stackSize = 1 /// the color used for drawing the bar-shadows. The bar shadows is a surface behind the bar that indicates the maximum value public var barShadowColor = UIColor(red: 215.0/255.0, green: 215.0/255.0, blue: 215.0/255.0, alpha: 1.0) /// the alpha value (transparency) that is used for drawing the highlight indicator bar. min = 0.0 (fully transparent), max = 1.0 (fully opaque) public var highLightAlpha = CGFloat(120.0 / 255.0) /// the overall entry count, including counting each stack-value individually private var _entryCountStacks = 0 /// array of labels used to describe the different values of the stacked bars public var stackLabels: [String] = ["Stack"] public override init() { super.init() self.highlightColor = UIColor.blackColor() } public override init(yVals: [ChartDataEntry]?, label: String?) { super.init(yVals: yVals, label: label) self.highlightColor = UIColor.blackColor() self.calcStackSize(yVals as! [BarChartDataEntry]?) self.calcEntryCountIncludingStacks(yVals as! [BarChartDataEntry]?) } // MARK: NSCopying public override func copyWithZone(zone: NSZone) -> AnyObject { var copy = super.copyWithZone(zone) as! BarChartDataSet copy.barSpace = barSpace copy._stackSize = _stackSize copy.barShadowColor = barShadowColor copy.highLightAlpha = highLightAlpha copy._entryCountStacks = _entryCountStacks copy.stackLabels = stackLabels return copy } /// Calculates the total number of entries this DataSet represents, including /// stacks. All values belonging to a stack are calculated separately. private func calcEntryCountIncludingStacks(yVals: [BarChartDataEntry]!) { _entryCountStacks = 0 for (var i = 0; i < yVals.count; i++) { var vals = yVals[i].values if (vals == nil) { _entryCountStacks++ } else { _entryCountStacks += vals!.count } } } /// calculates the maximum stacksize that occurs in the Entries array of this DataSet private func calcStackSize(yVals: [BarChartDataEntry]!) { for (var i = 0; i < yVals.count; i++) { if let vals = yVals[i].values { if vals.count > _stackSize { _stackSize = vals.count } } } } internal override func calcMinMax(#start : Int, end: Int) { let yValCount = _yVals.count if yValCount == 0 { return } var endValue : Int if end == 0 || end >= yValCount { endValue = yValCount - 1 } else { endValue = end } _lastStart = start _lastEnd = endValue _yMin = DBL_MAX _yMax = -DBL_MAX for (var i = start; i <= endValue; i++) { if let e = _yVals[i] as? BarChartDataEntry { if !e.value.isNaN { if e.values == nil { if e.value < _yMin { _yMin = e.value } if e.value > _yMax { _yMax = e.value } } else { if -e.negativeSum < _yMin { _yMin = -e.negativeSum } if e.positiveSum > _yMax { _yMax = e.positiveSum } } } } } if (_yMin == DBL_MAX) { _yMin = 0.0 _yMax = 0.0 } } /// Returns the maximum number of bars that can be stacked upon another in this DataSet. public var stackSize: Int { return _stackSize } /// Returns true if this DataSet is stacked (stacksize > 1) or not. public var isStacked: Bool { return _stackSize > 1 ? true : false } /// returns the overall entry count, including counting each stack-value individually public var entryCountStacks: Int { return _entryCountStacks } }
5eb4b57ec6e00f996d3a3d8f39b05a86
28.005263
148
0.508167
false
false
false
false
anishathalye/skipchat
refs/heads/master
Contagged/Contagged.swift
mit
1
// Contagged.swift // SkipChat // // Created by Ankush Gupta on 1/17/15. // Copyright (c) 2015 SkipChat. All rights reserved. // import AddressBook import AddressBookUI import UIKit protocol ContaggedPickerDelegate { func peoplePickerNavigationControllerDidCancel() func personSelected(person: SwiftAddressBookPerson?) } protocol ContaggedUnknownPersonDelegate { func didResolveToPerson(person: SwiftAddressBookPerson?) } class ContaggedManager: NSObject, ABPeoplePickerNavigationControllerDelegate, ABUnknownPersonViewControllerDelegate { var pickerDelegate : ContaggedPickerDelegate? var unknownPersonDelegate : ContaggedUnknownPersonDelegate? var viewController : UIViewController? var pickerField : String? // MARK: Authorization Methods class func getAuthorizationStatus() -> ABAuthorizationStatus { return SwiftAddressBook.authorizationStatus() } func requestAuthorizationWithCompletion(completion: (Bool, CFError?) -> Void ) { swiftAddressBook?.requestAccessWithCompletion(completion) } // MARK: People Picker Methods func pickContact(fieldName: String) -> Void { pickerField = fieldName; let picker = ABPeoplePickerNavigationController() picker.peoplePickerDelegate = self if picker.respondsToSelector(Selector("predicateForEnablingPerson")) { picker.predicateForEnablingPerson = NSPredicate(format: "%K.length>0", ABPersonNoteProperty) } viewController?.presentViewController(picker, animated: true, completion: nil) } func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, didSelectPerson person: ABRecordRef!) { pickerDelegate?.personSelected(swiftAddressBook?.personWithRecordId(ABRecordGetRecordID(person))) } func peoplePickerNavigationController(peoplePicker: ABPeoplePickerNavigationController!, shouldContinueAfterSelectingPerson person: ABRecordRef!) -> Bool { peoplePickerNavigationController(peoplePicker, didSelectPerson: person) peoplePicker.dismissViewControllerAnimated(true, completion: nil) return false; } func peoplePickerNavigationControllerDidCancel(peoplePicker: ABPeoplePickerNavigationController!) { peoplePicker.dismissViewControllerAnimated(true, completion: nil) pickerDelegate?.peoplePickerNavigationControllerDidCancel(); } // MARK: Unknown Person Methods func addUnknownContact(fieldName: String, value: String) -> Void { if(ContaggedManager.getAuthorizationStatus() == ABAuthorizationStatus.NotDetermined){ swiftAddressBook?.requestAccessWithCompletion({ (success, error) -> Void in if success { let unknownPersonViewController = ABUnknownPersonViewController() unknownPersonViewController.unknownPersonViewDelegate = self unknownPersonViewController.allowsAddingToAddressBook = true unknownPersonViewController.allowsActions = false // user can tap an email address to switch to mail, for example let person : SwiftAddressBookPerson = SwiftAddressBookPerson.create() self.addFieldToContact(fieldName, value: value, person: person) unknownPersonViewController.displayedPerson = person self.viewController!.showViewController(unknownPersonViewController, sender:self.viewController!) // push onto navigation controller } else { println("Access to contacts denied!") } }) } } func unknownPersonViewController( unknownCardViewController: ABUnknownPersonViewController!, didResolveToPerson person: ABRecord!) { unknownPersonDelegate?.didResolveToPerson(swiftAddressBook?.personWithRecordId( ABRecordGetRecordID(person))) } // MARK: General access methods /** Add a field to a contact :param: field The name of our custom field :param: value The value for our custom field :param: record The ABRecord pointing to the specific contact to which we want to add the field :returns: A reference to a CFError object. */ func addFieldToContact(field:String, value:String, person:SwiftAddressBookPerson) -> CFError? { person.note = value return swiftAddressBook?.save() } /** Find all contacts who have a given field :param: field The name of our custom field :returns: An Array of SwiftAddressBookPersons */ // func findContactsWithField(field:String) -> [SwiftAddressBookPerson]? { // // return all contacts who have at least one url with a matching label and value // return swiftAddressBook?.allPeople?.filter( { // $0.note != nil // }) // } func noteEquals(person: SwiftAddressBookPerson?, fieldValue:String) -> Bool { return person?.note? == fieldValue; } /** Find all contacts who have a given value for a given field :param: field The name of our custom field :param: value The value for our custom field :returns: An Array of SwiftAddressBookPersons */ func findContactsByFieldValue(field:String, fieldValue:String) -> SwiftAddressBookPerson? { // return all contacts who have at least one url with a matching label and value if let people = swiftAddressBook?.allPeople { for person in people { if let note = person.note{ if note == fieldValue{ return person; } } } } return nil; } /** Find the values of contacts who have a given value for the desired field :param: field The name of our custom field :param: record The value for our custom field :returns: An Array of SwiftAddressBookPersons */ func findValueForPerson(field:String, person:SwiftAddressBookPerson?) -> String? { return person?.note; } func getPeerName(field: String, value:String) -> String{ return findContactsByFieldValue(field, fieldValue: value)?.firstName ?? "Unknown User"; } }
8dacb65764113aee60c9229e44ef4dde
37.473054
159
0.674086
false
false
false
false
allbto/Swiftility
refs/heads/master
Swiftility/Sources/Core/Dynamic.swift
mit
2
// // Dynamic.swift // Swiftility // // Created by Allan Barbato on 9/9/15. // Copyright © 2015 Allan Barbato. All rights reserved. // import Foundation public struct Dynamic<T> { public typealias Listener = (T) -> Void // MARK: - Private fileprivate var _listener: Listener? // MARK: - Properties /// Contained value. Changes fire listener if `self.shouldFire == true` public var value: T { didSet { guard shouldFire == true else { return } self.fire() } } /// Whether value didSet should fire or not public var shouldFire: Bool = true /// Whether fire() should call listener on main thread or not public var fireOnMainThread: Bool = true // Has a listener public var isBinded: Bool { return _listener != nil } // MARK: - Life cycle /// Init with a value public init(_ v: T) { value = v } // MARK: - Binding /** Bind a listener to value changes - parameter listener: Closure called when value changes */ public mutating func bind(_ listener: Listener?) { _listener = listener } /** Same as `bind` but also fires immediately - parameter listener: Closure called immediately and when value changes */ public mutating func bindAndFire(_ listener: Listener?) { self.bind(listener) self.fire() } // MARK: - Actions // Fires listener if not nil. Regardless of `self.shouldFire` public func fire() { if fireOnMainThread && !Thread.isMainThread { async_main { self._listener?(self.value) } } else { self._listener?(self.value) } } /** Set value with optional firing. Regardless of `self.shouldFire` - parameter value: Value to update to - parameter =true;fire: Should fire changes of value */ public mutating func setValue(_ value: T, fire: Bool = true) { let originalShouldFire = shouldFire shouldFire = fire self.value = value shouldFire = originalShouldFire } } // MARK: - Convenience precedencegroup Assignement { associativity: left assignment: true higherThan: CastingPrecedence } infix operator .= : Assignement public func .= <T>(lhs: inout Dynamic<T>, rhs: T) { lhs.value = rhs }
4bb6e490b55db892063148b81d30778a
20.547826
76
0.5795
false
false
false
false
devincoughlin/swift
refs/heads/master
stdlib/public/core/BridgeObjectiveC.swift
apache-2.0
2
//===----------------------------------------------------------------------===// // // 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 Swift Array or Dictionary of types conforming to /// `_ObjectiveCBridgeable` can be passed to Objective-C as an NSArray or /// NSDictionary, respectively. The elements of the resulting NSArray /// or NSDictionary will be the result of calling `_bridgeToObjectiveC` /// on each element of the source container. public protocol _ObjectiveCBridgeable { associatedtype _ObjectiveCType: AnyObject /// Convert `self` to Objective-C. func _bridgeToObjectiveC() -> _ObjectiveCType /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for forced downcasting (e.g., /// via as), and may defer complete checking until later. For /// example, when bridging from `NSArray` to `Array<Element>`, we can defer /// the checking for the individual elements of the array. /// /// - parameter result: The location where the result is written. The optional /// will always contain a value. static func _forceBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) /// Try to bridge from an Objective-C object of the bridged class /// type to a value of the Self type. /// /// This conditional bridging operation is used for conditional /// downcasting (e.g., via as?) and therefore must perform a /// complete conversion to the value type; it cannot defer checking /// to a later time. /// /// - parameter result: The location where the result is written. /// /// - Returns: `true` if bridging succeeded, `false` otherwise. This redundant /// information is provided for the convenience of the runtime's `dynamic_cast` /// implementation, so that it need not look into the optional representation /// to determine success. @discardableResult static func _conditionallyBridgeFromObjectiveC( _ source: _ObjectiveCType, result: inout Self? ) -> Bool /// Bridge from an Objective-C object of the bridged class type to a /// value of the Self type. /// /// This bridging operation is used for unconditional bridging when /// interoperating with Objective-C code, either in the body of an /// Objective-C thunk or when calling Objective-C code, and may /// defer complete checking until later. For example, when bridging /// from `NSArray` to `Array<Element>`, we can defer the checking /// for the individual elements of the array. /// /// \param source The Objective-C object from which we are /// bridging. This optional value will only be `nil` in cases where /// an Objective-C method has returned a `nil` despite being marked /// as `_Nonnull`/`nonnull`. In most such cases, bridging will /// generally force the value immediately. However, this gives /// bridging the flexibility to substitute a default value to cope /// with historical decisions, e.g., an existing Objective-C method /// that returns `nil` to for "empty result" rather than (say) an /// empty array. In such cases, when `nil` does occur, the /// implementation of `Swift.Array`'s conformance to /// `_ObjectiveCBridgeable` will produce an empty array rather than /// dynamically failing. @_effects(readonly) static func _unconditionallyBridgeFromObjectiveC(_ source: _ObjectiveCType?) -> Self } #if _runtime(_ObjC) @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) @available(*, deprecated) @_cdecl("_SwiftCreateBridgedArray") @usableFromInline internal func _SwiftCreateBridgedArray( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = Array(bufPtr)._bridgeToObjectiveCImpl() return Unmanaged<AnyObject>.passRetained(bridged) } @available(macOS 9999, iOS 9999, tvOS 9999, watchOS 9999, *) @available(*, deprecated) @_cdecl("_SwiftCreateBridgedMutableArray") @usableFromInline internal func _SwiftCreateBridgedMutableArray( values: UnsafePointer<AnyObject>, numValues: Int ) -> Unmanaged<AnyObject> { let bufPtr = UnsafeBufferPointer(start: values, count: numValues) let bridged = _SwiftNSMutableArray(Array(bufPtr)) return Unmanaged<AnyObject>.passRetained(bridged) } @_silgen_name("swift_stdlib_connectNSBaseClasses") internal func _connectNSBaseClasses() -> Bool private let _bridgeInitializedSuccessfully = _connectNSBaseClasses() internal var _orphanedFoundationSubclassesReparented: Bool = false /// Reparents the SwiftNativeNS*Base classes to be subclasses of their respective /// Foundation types, or is false if they couldn't be reparented. Must be run /// in order to bridge Swift Strings, Arrays, Dictionarys, Sets, or Enumerators to ObjC. internal func _connectOrphanedFoundationSubclassesIfNeeded() -> Void { let bridgeWorks = _bridgeInitializedSuccessfully _debugPrecondition(bridgeWorks) _orphanedFoundationSubclassesReparented = true } //===--- Bridging for metatypes -------------------------------------------===// /// A stand-in for a value of metatype type. /// /// The language and runtime do not yet support protocol conformances for /// structural types like metatypes. However, we can use a struct that contains /// a metatype, make it conform to _ObjectiveCBridgeable, and its witness table /// will be ABI-compatible with one that directly provided conformance to the /// metatype type itself. public struct _BridgeableMetatype: _ObjectiveCBridgeable { internal var value: AnyObject.Type internal init(value: AnyObject.Type) { self.value = value } public typealias _ObjectiveCType = AnyObject public func _bridgeToObjectiveC() -> AnyObject { return value } public static func _forceBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) { result = _BridgeableMetatype(value: source as! AnyObject.Type) } public static func _conditionallyBridgeFromObjectiveC( _ source: AnyObject, result: inout _BridgeableMetatype? ) -> Bool { if let type = source as? AnyObject.Type { result = _BridgeableMetatype(value: type) return true } result = nil return false } @_effects(readonly) public static func _unconditionallyBridgeFromObjectiveC(_ source: AnyObject?) -> _BridgeableMetatype { var result: _BridgeableMetatype? _forceBridgeFromObjectiveC(source!, result: &result) return result! } } //===--- Bridging facilities written in Objective-C -----------------------===// // Functions that must discover and possibly use an arbitrary type's // conformance to a given protocol. See ../runtime/Casting.cpp for // implementations. //===----------------------------------------------------------------------===// /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC @inlinable public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { if _fastPath(_isClassOrObjCExistential(T.self)) { return unsafeBitCast(x, to: AnyObject.self) } return _bridgeAnythingNonVerbatimToObjectiveC(x) } @_silgen_name("") public // @testable func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: __owned T) -> AnyObject /// Convert a purportedly-nonnull `id` value from Objective-C into an Any. /// /// Since Objective-C APIs sometimes get their nullability annotations wrong, /// this includes a failsafe against nil `AnyObject`s, wrapping them up as /// a nil `AnyObject?`-inside-an-`Any`. /// // COMPILER_INTRINSIC public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any { if let nonnullObject = possiblyNullObject { return nonnullObject // AnyObject-in-Any } return possiblyNullObject as Any } /// Convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, trap; /// + otherwise, returns the result of `T._forceBridgeFromObjectiveC(x)`; /// - otherwise, trap. @inlinable public func _forceBridgeFromObjectiveC<T>(_ x: AnyObject, _: T.Type) -> T { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as! T } var result: T? _bridgeNonVerbatimFromObjectiveC(x, T.self, &result) return result! } /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. /// /// - If `T` is a class type: /// - if the dynamic type of `x` is `T` or a subclass of it, it is bridged /// verbatim, the function returns `x`; /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`: /// + otherwise, if the dynamic type of `x` is not `T._ObjectiveCType` /// or a subclass of it, the result is empty; /// + otherwise, returns the result of /// `T._conditionallyBridgeFromObjectiveC(x)`; /// - otherwise, the result is empty. @inlinable public func _conditionallyBridgeFromObjectiveC<T>( _ x: AnyObject, _: T.Type ) -> T? { if _fastPath(_isClassOrObjCExistential(T.self)) { return x as? T } var result: T? _ = _bridgeNonVerbatimFromObjectiveCConditional(x, T.self, &result) return result } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } @_silgen_name("") @usableFromInline internal func _bridgeNonVerbatimFromObjectiveC<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) /// Helper stub to upcast to Any and store the result to an inout Any? /// on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimFromObjectiveCToAny") internal func _bridgeNonVerbatimFromObjectiveCToAny( _ x: AnyObject, _ result: inout Any? ) { result = x as Any } /// Helper stub to upcast to Optional on the C++ runtime's behalf. @_silgen_name("_bridgeNonVerbatimBoxedValue") internal func _bridgeNonVerbatimBoxedValue<NativeType>( _ x: UnsafePointer<NativeType>, _ result: inout NativeType? ) { result = x.pointee } /// Runtime optional to conditionally perform a bridge from an object to a value /// type. /// /// - parameter result: Will be set to the resulting value if bridging succeeds, and /// unchanged otherwise. /// /// - Returns: `true` to indicate success, `false` to indicate failure. @_silgen_name("") public func _bridgeNonVerbatimFromObjectiveCConditional<T>( _ x: AnyObject, _ nativeType: T.Type, _ result: inout T? ) -> Bool /// Determines if values of a given type can be converted to an Objective-C /// representation. /// /// - If `T` is a class type, returns `true`; /// - otherwise, returns whether `T` conforms to `_ObjectiveCBridgeable`. public func _isBridgedToObjectiveC<T>(_: T.Type) -> Bool { if _fastPath(_isClassOrObjCExistential(T.self)) { return true } return _isBridgedNonVerbatimToObjectiveC(T.self) } @_silgen_name("") public func _isBridgedNonVerbatimToObjectiveC<T>(_: T.Type) -> Bool /// A type that's bridged "verbatim" does not conform to /// `_ObjectiveCBridgeable`, and can have its bits reinterpreted as an /// `AnyObject`. When this function returns true, the storage of an /// `Array<T>` can be `unsafeBitCast` as an array of `AnyObject`. @inlinable // FIXME(sil-serialize-all) public func _isBridgedVerbatimToObjectiveC<T>(_: T.Type) -> Bool { return _isClassOrObjCExistential(T.self) } /// Retrieve the Objective-C type to which the given type is bridged. @inlinable // FIXME(sil-serialize-all) public func _getBridgedObjectiveCType<T>(_: T.Type) -> Any.Type? { if _fastPath(_isClassOrObjCExistential(T.self)) { return T.self } return _getBridgedNonVerbatimObjectiveCType(T.self) } @_silgen_name("") public func _getBridgedNonVerbatimObjectiveCType<T>(_: T.Type) -> Any.Type? // -- Pointer argument bridging /// A mutable pointer addressing an Objective-C reference that doesn't own its /// target. /// /// `Pointee` must be a class type or `Optional<C>` where `C` is a class. /// /// This type has implicit conversions to allow passing any of the following /// to a C or ObjC API: /// /// - `nil`, which gets passed as a null pointer, /// - an inout argument of the referenced type, which gets passed as a pointer /// to a writeback temporary with autoreleasing ownership semantics, /// - an `UnsafeMutablePointer<Pointee>`, which is passed as-is. /// /// Passing pointers to mutable arrays of ObjC class pointers is not /// directly supported. Unlike `UnsafeMutablePointer<Pointee>`, /// `AutoreleasingUnsafeMutablePointer<Pointee>` must reference storage that /// does not own a reference count to the referenced /// value. UnsafeMutablePointer's operations, by contrast, assume that /// the referenced storage owns values loaded from or stored to it. /// /// This type does not carry an owner pointer unlike the other C*Pointer types /// because it only needs to reference the results of inout conversions, which /// already have writeback-scoped lifetime. @frozen public struct AutoreleasingUnsafeMutablePointer<Pointee /* TODO : class */> : _Pointer { public let _rawValue: Builtin.RawPointer @_transparent public // COMPILER_INTRINSIC init(_ _rawValue: Builtin.RawPointer) { self._rawValue = _rawValue } /// Retrieve or set the `Pointee` instance referenced by `self`. /// /// `AutoreleasingUnsafeMutablePointer` is assumed to reference a value with /// `__autoreleasing` ownership semantics, like `NSFoo **` declarations in /// ARC. Setting the pointee autoreleases the new value before trivially /// storing it in the referenced memory. /// /// - Precondition: the pointee has been initialized with an instance of type /// `Pointee`. @inlinable public var pointee: Pointee { @_transparent get { // The memory addressed by this pointer contains a non-owning reference, // therefore we *must not* point an `UnsafePointer<AnyObject>` to // it---otherwise we would allow the compiler to assume it has a +1 // refcount, enabling some optimizations that wouldn't be valid. // // Instead, we need to load the pointee as a +0 unmanaged reference. For // an extra twist, `Pointee` is allowed (but not required) to be an // optional type, so we actually need to load it as an optional, and // explicitly handle the nil case. let unmanaged = UnsafePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee return _unsafeReferenceCast( unmanaged?.takeUnretainedValue(), to: Pointee.self) } @_transparent nonmutating set { // Autorelease the object reference. let object = _unsafeReferenceCast(newValue, to: Optional<AnyObject>.self) Builtin.retain(object) Builtin.autorelease(object) // Convert it to an unmanaged reference and trivially assign it to the // memory addressed by this pointer. let unmanaged: Optional<Unmanaged<AnyObject>> if let object = object { unmanaged = Unmanaged.passUnretained(object) } else { unmanaged = nil } UnsafeMutablePointer<Optional<Unmanaged<AnyObject>>>(_rawValue).pointee = unmanaged } } /// Access the `i`th element of the raw array pointed to by /// `self`. /// /// - Precondition: `self != nil`. @inlinable // unsafe-performance public subscript(i: Int) -> Pointee { @_transparent get { return self.advanced(by: i).pointee } } /// Explicit construction from an UnsafeMutablePointer. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init<U>(_ from: UnsafeMutablePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from an UnsafeMutablePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe; UnsafeMutablePointer assumes the /// referenced memory has +1 strong ownership semantics, whereas /// AutoreleasingUnsafeMutablePointer implies +0 semantics. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @_transparent public init?<U>(_ from: UnsafeMutablePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } /// Explicit construction from a UnsafePointer. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init<U>(_ from: UnsafePointer<U>) { self._rawValue = from._rawValue } /// Explicit construction from a UnsafePointer. /// /// Returns nil if `from` is nil. /// /// This is inherently unsafe because UnsafePointers do not imply /// mutability. /// /// - Warning: Accessing `pointee` as a type that is unrelated to /// the underlying memory's bound type is undefined. @usableFromInline @_transparent internal init?<U>(_ from: UnsafePointer<U>?) { guard let unwrapped = from else { return nil } self.init(unwrapped) } } extension UnsafeMutableRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } extension UnsafeRawPointer { /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. @_transparent public init<T>(_ other: AutoreleasingUnsafeMutablePointer<T>) { _rawValue = other._rawValue } /// Creates a new raw pointer from an `AutoreleasingUnsafeMutablePointer` /// instance. /// /// - Parameter other: The pointer to convert. If `other` is `nil`, the /// result is `nil`. @_transparent public init?<T>(_ other: AutoreleasingUnsafeMutablePointer<T>?) { guard let unwrapped = other else { return nil } self.init(unwrapped) } } internal struct _CocoaFastEnumerationStackBuf { // Clang uses 16 pointers. So do we. internal var _item0: UnsafeRawPointer? internal var _item1: UnsafeRawPointer? internal var _item2: UnsafeRawPointer? internal var _item3: UnsafeRawPointer? internal var _item4: UnsafeRawPointer? internal var _item5: UnsafeRawPointer? internal var _item6: UnsafeRawPointer? internal var _item7: UnsafeRawPointer? internal var _item8: UnsafeRawPointer? internal var _item9: UnsafeRawPointer? internal var _item10: UnsafeRawPointer? internal var _item11: UnsafeRawPointer? internal var _item12: UnsafeRawPointer? internal var _item13: UnsafeRawPointer? internal var _item14: UnsafeRawPointer? internal var _item15: UnsafeRawPointer? @_transparent internal var count: Int { return 16 } internal init() { _item0 = nil _item1 = _item0 _item2 = _item0 _item3 = _item0 _item4 = _item0 _item5 = _item0 _item6 = _item0 _item7 = _item0 _item8 = _item0 _item9 = _item0 _item10 = _item0 _item11 = _item0 _item12 = _item0 _item13 = _item0 _item14 = _item0 _item15 = _item0 _internalInvariant(MemoryLayout.size(ofValue: self) >= MemoryLayout<Optional<UnsafeRawPointer>>.size * count) } } /// Get the ObjC type encoding for a type as a pointer to a C string. /// /// This is used by the Foundation overlays. The compiler will error if the /// passed-in type is generic or not representable in Objective-C @_transparent public func _getObjCTypeEncoding<T>(_ type: T.Type) -> UnsafePointer<Int8> { // This must be `@_transparent` because `Builtin.getObjCTypeEncoding` is // only supported by the compiler for concrete types that are representable // in ObjC. return UnsafePointer(Builtin.getObjCTypeEncoding(type)) } #endif //===--- Bridging without the ObjC runtime --------------------------------===// #if !_runtime(_ObjC) /// Convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _forceBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable> ( _ x: T._ObjectiveCType, _: T.Type ) -> T { var result: T? T._forceBridgeFromObjectiveC(x, result: &result) return result! } /// Attempt to convert `x` from its Objective-C representation to its Swift /// representation. // COMPILER_INTRINSIC @inlinable public func _conditionallyBridgeFromObjectiveC_bridgeable<T:_ObjectiveCBridgeable>( _ x: T._ObjectiveCType, _: T.Type ) -> T? { var result: T? T._conditionallyBridgeFromObjectiveC (x, result: &result) return result } public // SPI(Foundation) protocol _NSSwiftValue: class { init(_ value: Any) var value: Any { get } static var null: AnyObject { get } } @usableFromInline internal class __SwiftValue { @usableFromInline let value: Any @usableFromInline init(_ value: Any) { self.value = value } @usableFromInline static let null = __SwiftValue(Optional<Any>.none as Any) } // Internal stdlib SPI @_silgen_name("swift_unboxFromSwiftValueWithType") public func swift_unboxFromSwiftValueWithType<T>( _ source: inout AnyObject, _ result: UnsafeMutablePointer<T> ) -> Bool { if source === _nullPlaceholder { if let unpacked = Optional<Any>.none as? T { result.initialize(to: unpacked) return true } } if let box = source as? __SwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } else if let box = source as? _NSSwiftValue { if let value = box.value as? T { result.initialize(to: value) return true } } return false } // Internal stdlib SPI @_silgen_name("swift_swiftValueConformsTo") public func _swiftValueConformsTo<T>(_ type: T.Type) -> Bool { if let foundationType = _foundationSwiftValueType { return foundationType is T.Type } else { return __SwiftValue.self is T.Type } } @_silgen_name("_swift_extractDynamicValue") public func _extractDynamicValue<T>(_ value: T) -> AnyObject? @_silgen_name("_swift_bridgeToObjectiveCUsingProtocolIfPossible") public func _bridgeToObjectiveCUsingProtocolIfPossible<T>(_ value: T) -> AnyObject? internal protocol _Unwrappable { func _unwrap() -> Any? } extension Optional: _Unwrappable { internal func _unwrap() -> Any? { return self } } private let _foundationSwiftValueType = _typeByName("Foundation.__SwiftValue") as? _NSSwiftValue.Type @usableFromInline internal var _nullPlaceholder: AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.null } else { return __SwiftValue.null } } @usableFromInline func _makeSwiftValue(_ value: Any) -> AnyObject { if let foundationType = _foundationSwiftValueType { return foundationType.init(value) } else { return __SwiftValue(value) } } /// Bridge an arbitrary value to an Objective-C object. /// /// - If `T` is a class type, it is always bridged verbatim, the function /// returns `x`; /// /// - otherwise, if `T` conforms to `_ObjectiveCBridgeable`, /// returns the result of `x._bridgeToObjectiveC()`; /// /// - otherwise, we use **boxing** to bring the value into Objective-C. /// The value is wrapped in an instance of a private Objective-C class /// that is `id`-compatible and dynamically castable back to the type of /// the boxed value, but is otherwise opaque. /// // COMPILER_INTRINSIC public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject { var done = false var result: AnyObject! let source: Any = x if let dynamicSource = _extractDynamicValue(x) { result = dynamicSource as AnyObject done = true } if !done, let wrapper = source as? _Unwrappable { if let value = wrapper._unwrap() { result = value as AnyObject } else { result = _nullPlaceholder } done = true } if !done { if type(of: source) as? AnyClass != nil { result = unsafeBitCast(x, to: AnyObject.self) } else if let object = _bridgeToObjectiveCUsingProtocolIfPossible(source) { result = object } else { result = _makeSwiftValue(source) } } return result } #endif // !_runtime(_ObjC)
691f9cf180b065554a3bf064776077bb
31.807882
101
0.691742
false
false
false
false
ronaldho/visionproject
refs/heads/master
EMIT/EMIT/AboutViewController.swift
mit
1
// // AboutViewController.swift // EMIT // // Created by Andrew on 4/06/16. // Copyright © 2016 Andrew. All rights reserved. // import UIKit class AboutViewController: AGViewController, UIWebViewDelegate { let aboutUrl = "http://emitcare.ca/about/" @IBOutlet weak var webView: UIWebView! @IBOutlet var activityIndicator: UIActivityIndicatorView! override func viewWillDisappear(animated: Bool) { // Apparently it's important to nil the delegate webView.delegate = nil } override func viewWillAppear(animated: Bool) { activityIndicator.hidden = true; webView.delegate = self let url = NSURL(string: aboutUrl) let request = NSURLRequest(URL: url!) webView.loadRequest(request) } override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view. } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } func webView(webView: UIWebView, didFailLoadWithError error: NSError?) { activityIndicator.stopAnimating() activityIndicator.hidden = true; let alertController = UIAlertController(title: nil, message: error?.localizedDescription, preferredStyle: .Alert) let ok = UIAlertAction(title: "OK", style: .Default, handler: { (action) -> Void in }) alertController.addAction(ok) presentViewController(alertController, animated: true, completion: nil) } func webViewDidStartLoad(webView: UIWebView) { activityIndicator.hidden = false; activityIndicator.startAnimating() } func webViewDidFinishLoad(webView: UIWebView) { activityIndicator.hidden = true; activityIndicator.stopAnimating() } /* // 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. } */ }
5b1c0a33b4f7e2eb758ee958ad8a298c
29.689189
121
0.667107
false
false
false
false
Legoless/Alpha
refs/heads/master
Demo/UIKitCatalog/CollectionViewController.swift
mit
1
/* Copyright (C) 2016 Apple Inc. All Rights Reserved. See LICENSE.txt for this sample’s licensing information Abstract: A view controller that demonstrates how to use a `UICollectionViewController`. A custom `UIView` subclass, `GradientMaskView` is used to mask the contents of the collection view as it scrolls beneath the containing `UINavigationController`'s `UINavigationBar`. */ import UIKit class CollectionViewController: UICollectionViewController { // MARK: Properties private let items = DataItem.sampleItems private let cellComposer = DataItemCellComposer() // MARK: UIViewController override func viewDidLoad() { super.viewDidLoad() guard let collectionView = collectionView else { return } /* Add a gradient mask to the collection view. This will fade out the contents of the collection view as it scrolls beneath the transparent navigation bar. */ collectionView.mask = GradientMaskView(frame: CGRect(origin: CGPoint.zero, size: collectionView.bounds.size)) } override func viewDidLayoutSubviews() { super.viewDidLayoutSubviews() guard let collectionView = collectionView, let maskView = collectionView.mask as? GradientMaskView, let layout = collectionView.collectionViewLayout as? UICollectionViewFlowLayout else { return } /* Update the mask view to have fully faded out any collection view content above the navigation bar's label. */ maskView.maskPosition.end = topLayoutGuide.length * 0.8 /* Update the position from where the collection view's content should start to fade out. The size of the fade increases as the collection view scrolls to a maximum of half the navigation bar's height. */ let maximumMaskStart = maskView.maskPosition.end + (topLayoutGuide.length * 0.5) let verticalScrollPosition = max(0, collectionView.contentOffset.y + collectionView.contentInset.top) maskView.maskPosition.start = min(maximumMaskStart, maskView.maskPosition.end + verticalScrollPosition) /* Position the mask view so that it is always fills the visible area of the collection view. */ var rect = CGRect(origin: CGPoint(x: 0, y: collectionView.contentOffset.y), size: collectionView.bounds.size) /* Increase the width of the mask view so that it doesn't clip focus shadows along its edge. Here we are basing the amount to increase the frame by on the spacing defined in the collection view's layout. */ rect = rect.insetBy(dx: -layout.minimumInteritemSpacing, dy: 0) maskView.frame = rect } // MARK: UICollectionViewDataSource override func numberOfSections(in collectionView: UICollectionView) -> Int { // The collection view shows all items in a single section. return 1 } override func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return items.count } override func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { // Dequeue a cell from the collection view. return collectionView.dequeueReusableCell(withReuseIdentifier: DataItemCollectionViewCell.reuseIdentifier, for: indexPath) } // MARK: UICollectionViewDelegate override func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) { guard let cell = cell as? DataItemCollectionViewCell else { fatalError("Expected to display a `DataItemCollectionViewCell`.") } let item = items[(indexPath as NSIndexPath).row] // Configure the cell. cellComposer.compose(cell, withDataItem: item) } }
095dd6c11847e8a2fa8f4a3ef4e310c8
41.103093
264
0.677522
false
false
false
false
ltcarbonell/deckstravaganza
refs/heads/master
Deckstravaganza/GCHelper.swift
mit
1
import GameKit /// Custom delegate used to provide information to the application implementing GCHelper. public protocol GCHelperDelegate { /// Method called when a match has been initiated. func matchStarted() /// Method called when the device received data about the match from another device in the match. func match(_ match: GKMatch, didReceiveData: Data, fromPlayer: String) /// Method called when the match has ended. func matchEnded() } /// A GCHelper instance represents a wrapper around a GameKit match. open class GCHelper: NSObject, GKMatchmakerViewControllerDelegate, GKGameCenterControllerDelegate, GKMatchDelegate, GKLocalPlayerListener { /// The match object provided by GameKit. open var match: GKMatch! fileprivate var delegate: GCHelperDelegate? fileprivate var invite: GKInvite! fileprivate var invitedPlayer: GKPlayer! fileprivate var playersDict = [String:AnyObject]() fileprivate var presentingViewController: UIViewController! fileprivate var authenticated = false fileprivate var matchStarted = false /// The shared instance of GCHelper, allowing you to access the same instance across all uses of the library. open class var sharedInstance: GCHelper { struct Static { static let instance = GCHelper() } return Static.instance } override init() { super.init() NotificationCenter.default.addObserver(self, selector: #selector(GCHelper.authenticationChanged), name: NSNotification.Name(rawValue: GKPlayerAuthenticationDidChangeNotificationName), object: nil) } // MARK: Internal functions internal func authenticationChanged() { if GKLocalPlayer.localPlayer().isAuthenticated && !authenticated { print("Authentication changed: player authenticated") authenticated = true } else { print("Authentication changed: player not authenticated") authenticated = false } } fileprivate func lookupPlayers() { let playerIDs = match.players.map { $0.playerID! } GKPlayer.loadPlayers(forIdentifiers: playerIDs) { (players, error) -> Void in if error != nil { print("Error retrieving player info: \(error!.localizedDescription)") self.matchStarted = false self.delegate?.matchEnded() } else { guard let players = players else { print("Error retrieving players; returned nil") return } for player in players { print("Found player: \(player.alias)") self.playersDict[player.playerID!] = player } self.matchStarted = true GKMatchmaker.shared().finishMatchmaking(for: self.match) self.delegate?.matchStarted() } } } // MARK: User functions /// Authenticates the user with their Game Center account if possible open func authenticateLocalUser() { print("Authenticating local user...") if GKLocalPlayer.localPlayer().isAuthenticated == false { GKLocalPlayer.localPlayer().authenticateHandler = { (view, error) in if error == nil { self.authenticated = true } else { print("\(error?.localizedDescription)") } } } else { print("Already authenticated") } } /** Attempts to pair up the user with other users who are also looking for a match. :param: minPlayers The minimum number of players required to create a match. :param: maxPlayers The maximum number of players allowed to create a match. :param: viewController The view controller to present required GameKit view controllers from. :param: delegate The delegate receiving data from GCHelper. */ open func findMatchWithMinPlayers(_ minPlayers: Int, maxPlayers: Int, viewController: UIViewController, delegate theDelegate: GCHelperDelegate) { matchStarted = false match = nil presentingViewController = viewController delegate = theDelegate presentingViewController.dismiss(animated: false, completion: nil) let request = GKMatchRequest() request.minPlayers = minPlayers request.maxPlayers = maxPlayers let mmvc = GKMatchmakerViewController(matchRequest: request)! mmvc.matchmakerDelegate = self presentingViewController.present(mmvc, animated: true, completion: nil) } /** Presents the game center view controller provided by GameKit. :param: viewController The view controller to present GameKit's view controller from. :param: viewState The state in which to present the new view controller. */ open func showGameCenter(_ viewController: UIViewController, viewState: GKGameCenterViewControllerState) { presentingViewController = viewController let gcvc = GKGameCenterViewController() gcvc.viewState = viewState gcvc.gameCenterDelegate = self presentingViewController.present(gcvc, animated: true, completion: nil) } // MARK: GKGameCenterControllerDelegate open func gameCenterViewControllerDidFinish(_ gameCenterViewController: GKGameCenterViewController) { presentingViewController.dismiss(animated: true, completion: nil) } // MARK: GKMatchmakerViewControllerDelegate open func matchmakerViewControllerWasCancelled(_ viewController: GKMatchmakerViewController) { presentingViewController.dismiss(animated: true, completion: nil) } open func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFailWithError error: Error) { presentingViewController.dismiss(animated: true, completion: nil) print("Error finding match: \(error.localizedDescription)") } open func matchmakerViewController(_ viewController: GKMatchmakerViewController, didFind theMatch: GKMatch) { presentingViewController.dismiss(animated: true, completion: nil) match = theMatch match.delegate = self if !matchStarted && match.expectedPlayerCount == 0 { print("Ready to start match!") self.lookupPlayers() } } // MARK: GKMatchDelegate open func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) { if match != theMatch { return } delegate?.match(theMatch, didReceiveData: data, fromPlayer: playerID) } open func match(_ theMatch: GKMatch, player playerID: String, didChange state: GKPlayerConnectionState) { if match != theMatch { return } switch state { case .stateConnected where !matchStarted && theMatch.expectedPlayerCount == 0: lookupPlayers() case .stateDisconnected: matchStarted = false delegate?.matchEnded() match = nil default: break } } open func match(_ theMatch: GKMatch, didFailWithError error: Error?) { if match != theMatch { return } print("Match failed with error: \(error?.localizedDescription)") matchStarted = false delegate?.matchEnded() } // MARK: GKLocalPlayerListener open func player(_ player: GKPlayer, didAccept inviteToAccept: GKInvite) { let mmvc = GKMatchmakerViewController(invite: inviteToAccept)! mmvc.matchmakerDelegate = self presentingViewController.present(mmvc, animated: true, completion: nil) } }
e34681b003859d3dab60e0a0b6a3d226
36.78673
204
0.64292
false
false
false
false
Dimillian/SwiftHN
refs/heads/master
SwiftHN/SafariViewController.swift
gpl-2.0
1
// // SafariViewController.swift // SwiftHN // // Created by TETRA2000 on 12/23/15. // Copyright © 2015 Thomas Ricouard. All rights reserved. // import SafariServices @available(iOS 9.0, *) class SafariViewController: SFSafariViewController { private var previousBarStyle: UIStatusBarStyle? override func viewWillAppear(animated: Bool) { super.viewWillAppear(animated) overrideStatusBarStyle() } override func viewWillDisappear(animated: Bool) { super.viewWillDisappear(animated) restoreStatusBarStyle() } private func overrideStatusBarStyle() { if previousBarStyle == nil { previousBarStyle = UIApplication.sharedApplication().statusBarStyle } UIApplication.sharedApplication().statusBarStyle = UIStatusBarStyle.Default } private func restoreStatusBarStyle() { if let previousBarStyle = previousBarStyle { UIApplication.sharedApplication().statusBarStyle = previousBarStyle } } }
08d8bb6ecb30e9d71f23f3fd3e01bc6d
25.65
83
0.669794
false
false
false
false
breadwallet/breadwallet-ios
refs/heads/master
breadwallet/src/Views/TransactionCells/TxStatusCell.swift
mit
1
// // TxStatusCell.swift // breadwallet // // Created by Ehsan Rezaie on 2017-12-20. // Copyright © 2017-2019 Breadwinner AG. All rights reserved. // import UIKit class TxStatusCell: UITableViewCell, Subscriber { // MARK: - Views private let container = UIView() private lazy var statusLabel: UILabel = { let label = UILabel(font: UIFont.customBody(size: 14.0)) label.textColor = .darkGray label.textAlignment = .center return label }() private let statusIndicator = TxStatusIndicator(width: 238.0) // MARK: - Init override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) { super.init(style: style, reuseIdentifier: reuseIdentifier) setupViews() } private func setupViews() { addSubviews() addConstraints() } private func addSubviews() { contentView.addSubview(container) container.addSubview(statusLabel) container.addSubview(statusIndicator) } private func addConstraints() { container.constrain(toSuperviewEdges: UIEdgeInsets(top: C.padding[1], left: C.padding[1], bottom: -C.padding[2], right: -C.padding[1])) statusIndicator.constrain([ statusIndicator.topAnchor.constraint(equalTo: container.topAnchor), statusIndicator.centerXAnchor.constraint(equalTo: container.centerXAnchor), statusIndicator.widthAnchor.constraint(equalToConstant: statusIndicator.width), statusIndicator.heightAnchor.constraint(equalToConstant: statusIndicator.height)]) statusLabel.constrain([ statusLabel.leadingAnchor.constraint(equalTo: container.leadingAnchor), statusLabel.trailingAnchor.constraint(equalTo: container.trailingAnchor), statusLabel.topAnchor.constraint(equalTo: statusIndicator.bottomAnchor), statusLabel.bottomAnchor.constraint(equalTo: container.bottomAnchor)]) } // MARK: - func set(txInfo: TxDetailViewModel) { //TODO:CRYPTO hook up refresh logic to System/Wallet tx events IOS-1162 func handleUpdatedTx(_ updatedTx: Transaction) { DispatchQueue.main.async { let updatedInfo = TxDetailViewModel(tx: updatedTx) self.update(status: updatedInfo.status) } } update(status: txInfo.status) } private func update(status: TransactionStatus) { statusIndicator.status = status switch status { case .pending: statusLabel.text = S.Transaction.pending case .confirmed: statusLabel.text = S.Transaction.confirming case .complete: statusLabel.text = S.Transaction.complete case .invalid: statusLabel.text = S.Transaction.invalid } } deinit { Store.unsubscribe(self) } required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented") } }
4acd1bb52ac899ae57b4652fbe766975
33.329787
94
0.611094
false
false
false
false
planvine/Line-Up-iOS-SDK
refs/heads/master
Pod/Classes/Utilities/Theme & Style.swift
mit
1
// // Theme & Style.swift // Pods // // Created by Andrea Ferrando on 08/02/2016. // // import Foundation struct PVScreenSize { static let SCREEN_WIDTH = UIScreen.mainScreen().bounds.size.width static let SCREEN_HEIGHT = UIScreen.mainScreen().bounds.size.height static let SCREEN_MAX_LENGTH = max(PVScreenSize.SCREEN_WIDTH, PVScreenSize.SCREEN_HEIGHT) static let SCREEN_MIN_LENGTH = min(PVScreenSize.SCREEN_WIDTH, PVScreenSize.SCREEN_HEIGHT) } struct PVDeviceType { static let IS_IPHONE_4_OR_LESS = UIDevice.currentDevice().userInterfaceIdiom == .Phone && PVScreenSize.SCREEN_MAX_LENGTH < 568.0 static let IS_IPHONE_5 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && PVScreenSize.SCREEN_MAX_LENGTH == 568.0 static let IS_IPHONE_6 = UIDevice.currentDevice().userInterfaceIdiom == .Phone && PVScreenSize.SCREEN_MAX_LENGTH == 667.0 static let IS_IPHONE_6S = UIDevice.currentDevice().userInterfaceIdiom == .Phone && PVScreenSize.SCREEN_MAX_LENGTH == 736.0 static let IS_IPAD = UIDevice.currentDevice().userInterfaceIdiom == .Pad static let IS_IPAD_PRO = UIDevice.currentDevice().userInterfaceIdiom == .Pad && PVScreenSize.SCREEN_MAX_LENGTH == 1366.0 } struct PVVersion{ static let SYS_VERSION_FLOAT = (UIDevice.currentDevice().systemVersion as NSString).floatValue static let iOS7 = (PVVersion.SYS_VERSION_FLOAT < 8.0 && PVVersion.SYS_VERSION_FLOAT >= 7.0) static let iOS8 = (PVVersion.SYS_VERSION_FLOAT >= 8.0 && PVVersion.SYS_VERSION_FLOAT < 9.0) static let iOS9 = (PVVersion.SYS_VERSION_FLOAT >= 9.0 && PVVersion.SYS_VERSION_FLOAT < 10.0) } func isPortrait() ->Bool { return UIInterfaceOrientationIsPortrait(UIApplication.sharedApplication().statusBarOrientation) } func pageControllerCustomize() { UIPageControl.appearance().pageIndicatorTintColor = PVColor.lightGrayLineColor UIPageControl.appearance().currentPageIndicatorTintColor = PVColor.lightGrayLabelColor } //MARK: - Colors struct PVColor { static var mainColor : UIColor = UIColor(red: 57/255.0, green: 155/255.0, blue: 162/255.0, alpha: 1.0) static let lightGrayLineColor: UIColor = UIColor(red: 228/255.0, green: 228/255.0, blue: 228/255.0, alpha: 1.0) static let lightGrayLabelColor: UIColor = UIColor(red: 153/255.0, green: 153/255.0, blue: 153/255.0, alpha: 1.0) static let lightGrayBackgroundColor: UIColor = UIColor(red: 244/255.0, green: 244/255.0, blue: 244/255.0, alpha: 1.0) static let greenColor: UIColor = UIColor(red: 158/255.0, green: 212/255.0, blue: 57/255.0, alpha: 1.0) } //MARK: - Fonts struct PVFont { static var kMainFontLightName : String = "Lato-Light" static var kMainFontRegularName : String = "Lato-Regular" static var kMainFontBoldName : String = "Lato-Bold" static func mainBold(fontSize : CGFloat) -> UIFont { let mainBold : UIFont! if PVDeviceType.IS_IPAD { mainBold = PVResource.getFontFromResources(PVFont.kMainFontBoldName, size: fontSize + 4) } else { mainBold = PVResource.getFontFromResources(PVFont.kMainFontBoldName, size: fontSize) } UIFont.boldSystemFontOfSize(2.0) return mainBold } static func mainRegular(fontSize : CGFloat) -> UIFont { if PVDeviceType.IS_IPAD { return PVResource.getFontFromResources(PVFont.kMainFontRegularName, size: fontSize + 4) } return PVResource.getFontFromResources(PVFont.kMainFontRegularName, size: fontSize) } static func mainLight(fontSize : CGFloat) -> UIFont { if PVDeviceType.IS_IPAD { return PVResource.getFontFromResources(PVFont.kMainFontLightName, size: fontSize + 4) } return PVResource.getFontFromResources(PVFont.kMainFontLightName, size: fontSize) } }
a2689ccef355d1a696642f973ab111f7
42.747126
132
0.711508
false
false
false
false
abunur/quran-ios
refs/heads/master
Quran/AudioFilesDownloader.swift
gpl-3.0
2
// // AudioFilesDownloader.swift // Quran // // Created by Mohamed Afifi on 5/15/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 BatchDownloader import PromiseKit class AudioFilesDownloader { let audioFileList: QariAudioFileListRetrieval let downloader: DownloadManager let ayahDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse> private var response: DownloadBatchResponse? init(audioFileList: QariAudioFileListRetrieval, downloader: DownloadManager, ayahDownloader: AnyInteractor<AyahsAudioDownloadRequest, DownloadBatchResponse>) { self.audioFileList = audioFileList self.downloader = downloader self.ayahDownloader = ayahDownloader } func cancel() { response?.cancel() response = nil } func needsToDownloadFiles(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> Bool { let files = filesForQari(qari, startAyah: startAyah, endAyah: endAyah) return !files.filter { !FileManager.documentsURL.appendingPathComponent($0.destinationPath).isReachable }.isEmpty } func getCurrentDownloadResponse() -> Promise<DownloadBatchResponse?> { if let response = response { return Promise(value: response) } else { return downloader.getOnGoingDownloads().then { batches -> DownloadBatchResponse? in let downloading = batches.first { $0.isAudio } self.createRequestWithDownloads(downloading) return self.response } } } func download(qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> Promise<DownloadBatchResponse?> { return ayahDownloader .execute(AyahsAudioDownloadRequest(start: startAyah, end: endAyah, qari: qari)) .then(on: .main) { responses -> DownloadBatchResponse? in // wrap the requests self.createRequestWithDownloads(responses) return self.response } } private func createRequestWithDownloads(_ batch: DownloadBatchResponse?) { guard let batch = batch else { return } response = batch response?.promise.always { [weak self] in self?.response = nil } } func filesForQari(_ qari: Qari, startAyah: AyahNumber, endAyah: AyahNumber) -> [DownloadRequest] { return audioFileList.get(for: qari, startAyah: startAyah, endAyah: endAyah).map { DownloadRequest(url: $0.remote, resumePath: $0.local.stringByAppendingPath(Files.downloadResumeDataExtension), destinationPath: $0.local) } } }
ac2529cf93b59b9ef2e1f4433a15e5ca
36.964706
149
0.680508
false
false
false
false